file_name
stringlengths
71
779k
comments
stringlengths
0
29.4k
code_string
stringlengths
20
7.69M
__index_level_0__
int64
2
17.2M
./full_match/5/0x95E945ebd99121D6FdfD91A7Ca1e70e99cCBE029/sources/project_/contracts/InvasionMars.sol
Burn any remaining reflection rewards due to rounding errors
function _distributeReflection(uint256 reflectionFee) internal { uint256 totalSupply = totalSupply(); if (totalSupply == 0) { return; } uint256 totalReflection = 0; for (uint256 i = 0; i < _getHoldersCount(); i++) { address holder = _getHolderAt(i); uint256 holderShare = reflectionFee * balanceOf(holder) / totalSupply; _reflectionRewards[holder] += holderShare; totalReflection += holderShare; } if (totalReflection < reflectionFee) { _burn(address(this), reflectionFee - totalReflection); } }
1,857,300
// SPDX-License-Identifier: MIT pragma solidity ^0.8.4; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/token/ERC721/IERC721.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; import "@openzeppelin/contracts/utils/Counters.sol"; import "@openzeppelin/contracts/token/ERC721/utils/ERC721Holder.sol"; contract AuctionMarket is Ownable, ERC721Holder { using Counters for Counters.Counter; Counters.Counter private _auctionId; enum Status { OnSell, SoldOut, Revoked } struct Auction { address nftAddress; address seller; uint256[] _tokenIds; uint256 price; } event CreateNewAuction(uint256 indexed auctionId); event Purchase(uint256 indexed auctionId, address indexed buyer); event Revoke(uint256 indexed auctionId); // mapping of auctionId to Auction mapping(uint256 => Auction) public auctions; // mapping of auction status mapping(uint256 => Status) public auctionStatus; // car car token address address public immutable cctAddress; constructor(address _cctAddress) { cctAddress = _cctAddress; } /// @dev get active auction /// /// @param _aid auction id /// @return the details of this auction function getActiveAuction(uint256 _aid) external view returns (Auction memory) { require(auctionStatus[_aid] == Status.OnSell, "AM: Auction finished"); return auctions[_aid]; } /// @notice user must approve this contract to take ownership of their nfts /// @dev user sell their nft with provided price and amount /// /// @param _nftAddress Address of the nft to sell /// @param _tokenIds Token id that use want to sell /// @param _price Price that use want to sell function sellItem( address _nftAddress, uint256[] calldata _tokenIds, uint256 _price ) external { address seller = msg.sender; for (uint256 i = 0; i < _tokenIds.length; i++) { // transfer ownership to this contract IERC721(_nftAddress).safeTransferFrom(seller, address(this), _tokenIds[i]); } uint256 aId = _nextAuctionId(); // create new acution auctions[aId] = Auction(_nftAddress, seller, _tokenIds, _price); auctionStatus[aId] = Status.OnSell; emit CreateNewAuction(aId); } /// @dev purchase the specified nft via auctionId /// /// @param _aid Auction id user want to buy function purchase(uint256 _aid) external { require(auctionStatus[_aid] == Status.OnSell, "AM: Invalid auction status"); address buyer = msg.sender; Auction storage auction = auctions[_aid]; require(buyer != auction.seller, "AM: Buyer and seller are the same"); auctionStatus[_aid] = Status.SoldOut; uint256 cost = auction._tokenIds.length * auction.price; require(IERC20(cctAddress).balanceOf(buyer) >= cost, "AM: Buyer funds not enough"); uint256 fee = cost / 100; // 1% fee to Market owner SafeERC20.safeTransferFrom(IERC20(cctAddress), buyer, address(this), fee); // the remaining to seller SafeERC20.safeTransferFrom(IERC20(cctAddress), buyer, auction.seller, cost - fee); // transfer nft from this contract to buyer for (uint256 i = 0; i < auction._tokenIds.length; i++) { IERC721(auction.nftAddress).safeTransferFrom(address(this), buyer, auction._tokenIds[i]); } delete auctions[_aid]; emit Purchase(_aid, buyer); } /// @dev revoke auction /// /// @param _aid Auction id to revoke function revoke(uint256 _aid) external { Auction memory auction = auctions[_aid]; require(msg.sender == auction.seller, "AM: Unautherized revoke"); require(auctionStatus[_aid] == Status.OnSell, "AM: Not on sell"); auctionStatus[_aid] = Status.Revoked; // give back user's token for (uint256 i = 0; i < auction._tokenIds.length; i++) { IERC721(auction.nftAddress).safeTransferFrom(address(this), auction.seller, auction._tokenIds[i]); } delete auctions[_aid]; emit Revoke(_aid); } /// @dev withraw cct token to `to` address /// /// @param to Address to withraw to function withdraw(address to) external onlyOwner { uint256 balance = IERC20(cctAddress).balanceOf(address(this)); SafeERC20.safeTransfer(IERC20(cctAddress), to, balance); } function _nextAuctionId() internal returns (uint256) { _auctionId.increment(); return _auctionId.current(); } }
get active auction _aid auction id return the details of this auction
function getActiveAuction(uint256 _aid) external view returns (Auction memory) { require(auctionStatus[_aid] == Status.OnSell, "AM: Auction finished"); return auctions[_aid]; }
5,507,330
./full_match/43113/0xE9Cc97730a4e951BbfF27bbE998282cE73579C72/sources/contracts/Registry.sol
@inheritdoc IRegistry
function atomicUpdate(address _newContract) external onlyOwner { Registrable(_newContract).register(); bytes32 name = Registrable(_newContract).getName(); address oldContract = registry[name]; registry[name] = _newContract; Registrable(oldContract).unregister(); emit LogRegistered(_newContract, name); }
7,206,372
./partial_match/1/0xD23498f9555205F23B971E89E6C3a42533EF2B10/sources/DISDAIN.sol
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./ Overflow not possible: balance + amount is at most totalSupply + amount, which is checked above.
function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _totalSupply += amount; unchecked { _balances[account] += amount; } }
2,831,011
pragma solidity 0.4.24; // produced by the Solididy File Flattener (c) David Appleton 2018 // contact : <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="d3b7b2a5b693b2b8bcbeb1b2fdb0bcbe">[email&#160;protected]</a> // released under Apache 2.0 licence contract ERC20Basic { function totalSupply() public view returns (uint256); function balanceOf(address who) public view returns (uint256); function transfer(address to, uint256 value) public returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); } contract 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; } } library SafeMath { /** * @dev Multiplies two numbers, throws on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) { return 0; } uint256 c = a * b; assert(c / a == b); return c; } /** * @dev Integer division of two numbers, truncating the quotient. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn&#39;t hold return c; } /** * @dev 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; } } contract ERC20 is ERC20Basic { function allowance(address owner, address spender) public view returns (uint256); function transferFrom(address from, address to, uint256 value) public returns (bool); function approve(address spender, uint256 value) public returns (bool); event Approval(address indexed owner, address indexed spender, uint256 value); } contract 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]; } } contract Pausable is Ownable { event Pause(); event Unpause(); bool public paused = false; /** * @dev Modifier to make a function callable only when the contract is not paused. */ modifier whenNotPaused() { require(!paused); _; } /** * @dev Modifier to make a function callable only when the contract is paused. */ modifier whenPaused() { require(paused); _; } /** * @dev called by the owner to pause, triggers stopped state */ function pause() onlyOwner whenNotPaused public { paused = true; Pause(); } /** * @dev called by the owner to unpause, returns to normal state */ function unpause() onlyOwner whenPaused public { paused = false; Unpause(); } } contract Relay is Ownable { address public licenseSalesContractAddress; address public registryContractAddress; address public apiRegistryContractAddress; address public apiCallsContractAddress; uint public version; // ------------------------------------------------------------------------ // Constructor, establishes ownership because contract is owned // ------------------------------------------------------------------------ constructor() public { version = 4; } // ------------------------------------------------------------------------ // Owner can transfer out any accidentally sent ERC20 tokens (just in case) // ------------------------------------------------------------------------ function transferAnyERC20Token(address tokenAddress, uint tokens) public onlyOwner returns (bool success) { return ERC20(tokenAddress).transfer(owner, tokens); } // ------------------------------------------------------------------------ // Sets the license sales contract address // ------------------------------------------------------------------------ function setLicenseSalesContractAddress(address newAddress) public onlyOwner { require(newAddress != address(0)); licenseSalesContractAddress = newAddress; } // ------------------------------------------------------------------------ // Sets the registry contract address // ------------------------------------------------------------------------ function setRegistryContractAddress(address newAddress) public onlyOwner { require(newAddress != address(0)); registryContractAddress = newAddress; } // ------------------------------------------------------------------------ // Sets the api registry contract address // ------------------------------------------------------------------------ function setApiRegistryContractAddress(address newAddress) public onlyOwner { require(newAddress != address(0)); apiRegistryContractAddress = newAddress; } // ------------------------------------------------------------------------ // Sets the api calls contract address // ------------------------------------------------------------------------ function setApiCallsContractAddress(address newAddress) public onlyOwner { require(newAddress != address(0)); apiCallsContractAddress = newAddress; } } contract APIRegistry is Ownable { struct APIForSale { uint pricePerCall; bytes32 sellerUsername; bytes32 apiName; address sellerAddress; string hostname; string docsUrl; } mapping(string => uint) internal apiIds; mapping(uint => APIForSale) public apis; uint public numApis; uint public version; // ------------------------------------------------------------------------ // Constructor, establishes ownership because contract is owned // ------------------------------------------------------------------------ constructor() public { numApis = 0; version = 1; } // ------------------------------------------------------------------------ // Owner can transfer out any accidentally sent ERC20 tokens (just in case) // ------------------------------------------------------------------------ function transferAnyERC20Token(address tokenAddress, uint tokens) public onlyOwner returns (bool success) { return ERC20(tokenAddress).transfer(owner, tokens); } // ------------------------------------------------------------------------ // Lets a user list an API to sell // ------------------------------------------------------------------------ function listApi(uint pricePerCall, bytes32 sellerUsername, bytes32 apiName, string hostname, string docsUrl) public { // make sure input params are valid require(pricePerCall != 0 && sellerUsername != "" && apiName != "" && bytes(hostname).length != 0); // make sure the name isn&#39;t already taken require(apiIds[hostname] == 0); numApis += 1; apiIds[hostname] = numApis; APIForSale storage api = apis[numApis]; api.pricePerCall = pricePerCall; api.sellerUsername = sellerUsername; api.apiName = apiName; api.sellerAddress = msg.sender; api.hostname = hostname; api.docsUrl = docsUrl; } // ------------------------------------------------------------------------ // Get the ID number of an API given it&#39;s hostname // ------------------------------------------------------------------------ function getApiId(string hostname) public view returns (uint) { return apiIds[hostname]; } // ------------------------------------------------------------------------ // Get info stored for the API but without the dynamic members, because solidity can&#39;t return dynamics to other smart contracts yet // ------------------------------------------------------------------------ function getApiByIdWithoutDynamics( uint apiId ) public view returns ( uint pricePerCall, bytes32 sellerUsername, bytes32 apiName, address sellerAddress ) { APIForSale storage api = apis[apiId]; pricePerCall = api.pricePerCall; sellerUsername = api.sellerUsername; apiName = api.apiName; sellerAddress = api.sellerAddress; } // ------------------------------------------------------------------------ // Get info stored for an API by id // ------------------------------------------------------------------------ function getApiById( uint apiId ) public view returns ( uint pricePerCall, bytes32 sellerUsername, bytes32 apiName, address sellerAddress, string hostname, string docsUrl ) { APIForSale storage api = apis[apiId]; pricePerCall = api.pricePerCall; sellerUsername = api.sellerUsername; apiName = api.apiName; sellerAddress = api.sellerAddress; hostname = api.hostname; docsUrl = api.docsUrl; } // ------------------------------------------------------------------------ // Get info stored for an API by hostname // ------------------------------------------------------------------------ function getApiByName( string _hostname ) public view returns ( uint pricePerCall, bytes32 sellerUsername, bytes32 apiName, address sellerAddress, string hostname, string docsUrl ) { uint apiId = apiIds[_hostname]; if (apiId == 0) { return; } APIForSale storage api = apis[apiId]; pricePerCall = api.pricePerCall; sellerUsername = api.sellerUsername; apiName = api.apiName; sellerAddress = api.sellerAddress; hostname = api.hostname; docsUrl = api.docsUrl; } // ------------------------------------------------------------------------ // Edit an API listing // ------------------------------------------------------------------------ function editApi(uint apiId, uint pricePerCall, address sellerAddress, string docsUrl) public { require(apiId != 0 && pricePerCall != 0 && sellerAddress != address(0)); APIForSale storage api = apis[apiId]; // prevent editing an empty api (effectively listing an api) require( api.pricePerCall != 0 && api.sellerUsername != "" && api.apiName != "" && bytes(api.hostname).length != 0 && api.sellerAddress != address(0) ); // require that sender is the original api lister, or the contract owner // the contract owner clause lets us recover a api listing if a dev loses access to their privkey require(msg.sender == api.sellerAddress || msg.sender == owner); api.pricePerCall = pricePerCall; api.sellerAddress = sellerAddress; api.docsUrl = docsUrl; } } 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&#39;s allowance to 0 and set the desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * @param _spender The address which will spend the funds. * @param _value The amount of tokens to be spent. */ function approve(address _spender, uint256 _value) 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; } } contract DeconetToken is StandardToken, Ownable, Pausable { // token naming etc string public constant symbol = "DCO"; string public constant name = "Deconet Token"; uint8 public constant decimals = 18; // contract version uint public constant version = 4; // ------------------------------------------------------------------------ // Constructor // ------------------------------------------------------------------------ constructor() public { // 1 billion tokens (1,000,000,000) totalSupply_ = 1000000000 * 10**uint(decimals); // transfer initial supply to msg.sender who is also contract owner balances[msg.sender] = totalSupply_; Transfer(address(0), msg.sender, totalSupply_); // pause contract until we&#39;re ready to allow transfers paused = true; } // ------------------------------------------------------------------------ // Owner can transfer out any accidentally sent ERC20 tokens (just in case) // ------------------------------------------------------------------------ function transferAnyERC20Token(address tokenAddress, uint tokens) public onlyOwner returns (bool success) { return ERC20(tokenAddress).transfer(owner, tokens); } // ------------------------------------------------------------------------ // Modifier to make a function callable only when called by the contract owner // or if the contract is not paused. // ------------------------------------------------------------------------ modifier whenOwnerOrNotPaused() { require(msg.sender == owner || !paused); _; } // ------------------------------------------------------------------------ // overloaded openzepplin method to add whenOwnerOrNotPaused modifier // ------------------------------------------------------------------------ function transfer(address _to, uint256 _value) public whenOwnerOrNotPaused returns (bool) { return super.transfer(_to, _value); } // ------------------------------------------------------------------------ // overloaded openzepplin method to add whenOwnerOrNotPaused modifier // ------------------------------------------------------------------------ function transferFrom(address _from, address _to, uint256 _value) public whenOwnerOrNotPaused returns (bool) { return super.transferFrom(_from, _to, _value); } // ------------------------------------------------------------------------ // overloaded openzepplin method to add whenOwnerOrNotPaused modifier // ------------------------------------------------------------------------ function approve(address _spender, uint256 _value) public whenOwnerOrNotPaused returns (bool) { return super.approve(_spender, _value); } // ------------------------------------------------------------------------ // overloaded openzepplin method to add whenOwnerOrNotPaused modifier // ------------------------------------------------------------------------ function increaseApproval(address _spender, uint _addedValue) public whenOwnerOrNotPaused returns (bool success) { return super.increaseApproval(_spender, _addedValue); } // ------------------------------------------------------------------------ // overloaded openzepplin method to add whenOwnerOrNotPaused modifier // ------------------------------------------------------------------------ function decreaseApproval(address _spender, uint _subtractedValue) public whenOwnerOrNotPaused returns (bool success) { return super.decreaseApproval(_spender, _subtractedValue); } } contract APICalls is Ownable { using SafeMath for uint; // the amount rewarded to a seller for selling api calls per buyer uint public tokenReward; // the fee this contract takes from every sale. expressed as percent. so a value of 3 indicates a 3% txn fee uint public saleFee; // if the buyer has never paid, we need to pick a date for when they probably started using the API. // This is in seconds and will be subtracted from "now" uint public defaultBuyerLastPaidAt; // address of the relay contract which holds the address of the registry contract. address public relayContractAddress; // the token address address public tokenContractAddress; // this contract version uint public version; // the amount that can be safely withdrawn from the contract uint public safeWithdrawAmount; // the address that is authorized to withdraw eth address private withdrawAddress; // the address that is authorized to report usage on behalf of deconet address private usageReportingAddress; // maps apiId to a APIBalance which stores how much each address owes mapping(uint => APIBalance) internal owed; // maps buyer addresses to whether or not accounts are overdrafted and more mapping(address => BuyerInfo) internal buyers; // Stores amounts owed and when buyers last paid on a per-api and per-user basis struct APIBalance { // maps address -> amount owed in wei mapping(address => uint) amounts; // basically a list of keys for the above map address[] nonzeroAddresses; // maps address -> tiemstamp of when buyer last paid mapping(address => uint) buyerLastPaidAt; } // Stores basic info about a buyer including their lifetime stats and reputation info struct BuyerInfo { // whether or not the account is overdrafted or not bool overdrafted; // total number of overdrafts, ever uint lifetimeOverdraftCount; // credits on file with this contract (wei) uint credits; // total amount of credits used / spent, ever (wei) uint lifetimeCreditsUsed; // maps apiId to approved spending balance for each API per second. mapping(uint => uint) approvedAmounts; // maps apiId to whether or not the user has exceeded their approved amount mapping(uint => bool) exceededApprovedAmount; // total number of times exceededApprovedAmount has happened uint lifetimeExceededApprovalAmountCount; } // Logged when API call usage is reported event LogAPICallsMade( uint apiId, address indexed sellerAddress, address indexed buyerAddress, uint pricePerCall, uint numCalls, uint totalPrice, address reportingAddress ); // Logged when seller is paid for API calls event LogAPICallsPaid( uint apiId, address indexed sellerAddress, uint totalPrice, uint rewardedTokens, uint networkFee ); // Logged when the credits from a specific buyer are spent on a specific api event LogSpendCredits( address indexed buyerAddress, uint apiId, uint amount, bool causedAnOverdraft ); // Logged when a buyer deposits credits event LogDepositCredits( address indexed buyerAddress, uint amount ); // Logged whena buyer withdraws credits event LogWithdrawCredits( address indexed buyerAddress, uint amount ); // ------------------------------------------------------------------------ // Constructor // ------------------------------------------------------------------------ constructor() public { version = 1; // default token reward of 100 tokens. // token has 18 decimal places so that&#39;s why 100 * 10^18 tokenReward = 100 * 10**18; // default saleFee of 10% saleFee = 10; // 604,800 seconds = 1 week. this is the default for when a user started using an api (1 week ago) defaultBuyerLastPaidAt = 604800; // default withdrawAddress is owner withdrawAddress = msg.sender; usageReportingAddress = msg.sender; } // ------------------------------------------------------------------------ // Owner can transfer out any accidentally sent ERC20 tokens (just in case) // ------------------------------------------------------------------------ function transferAnyERC20Token(address tokenAddress, uint tokens) public onlyOwner returns (bool success) { return ERC20(tokenAddress).transfer(owner, tokens); } // ------------------------------------------------------------------------ // Owner can transfer out any ETH // ------------------------------------------------------------------------ function withdrawEther(uint amount) public { require(msg.sender == withdrawAddress); require(amount <= this.balance); require(amount <= safeWithdrawAmount); safeWithdrawAmount = safeWithdrawAmount.sub(amount); withdrawAddress.transfer(amount); } // ------------------------------------------------------------------------ // Owner can set address of who can withdraw // ------------------------------------------------------------------------ function setWithdrawAddress(address _withdrawAddress) public onlyOwner { require(_withdrawAddress != address(0)); withdrawAddress = _withdrawAddress; } // ------------------------------------------------------------------------ // Owner can set address of who can report usage // ------------------------------------------------------------------------ function setUsageReportingAddress(address _usageReportingAddress) public onlyOwner { require(_usageReportingAddress != address(0)); usageReportingAddress = _usageReportingAddress; } // ------------------------------------------------------------------------ // Owner can set address of relay contract // ------------------------------------------------------------------------ function setRelayContractAddress(address _relayContractAddress) public onlyOwner { require(_relayContractAddress != address(0)); relayContractAddress = _relayContractAddress; } // ------------------------------------------------------------------------ // Owner can set address of token contract // ------------------------------------------------------------------------ function setTokenContractAddress(address _tokenContractAddress) public onlyOwner { require(_tokenContractAddress != address(0)); tokenContractAddress = _tokenContractAddress; } // ------------------------------------------------------------------------ // Owner can set token reward // ------------------------------------------------------------------------ function setTokenReward(uint _tokenReward) public onlyOwner { tokenReward = _tokenReward; } // ------------------------------------------------------------------------ // Owner can set the sale fee // ------------------------------------------------------------------------ function setSaleFee(uint _saleFee) public onlyOwner { saleFee = _saleFee; } // ------------------------------------------------------------------------ // Owner can set the default buyer last paid at // ------------------------------------------------------------------------ function setDefaultBuyerLastPaidAt(uint _defaultBuyerLastPaidAt) public onlyOwner { defaultBuyerLastPaidAt = _defaultBuyerLastPaidAt; } // ------------------------------------------------------------------------ // The API owner or the authorized deconet usage reporting address may report usage // ------------------------------------------------------------------------ function reportUsage(uint apiId, uint numCalls, address buyerAddress) public { // look up the registry address from relay contract Relay relay = Relay(relayContractAddress); address apiRegistryAddress = relay.apiRegistryContractAddress(); // get the module info from registry APIRegistry apiRegistry = APIRegistry(apiRegistryAddress); uint pricePerCall; bytes32 sellerUsername; bytes32 apiName; address sellerAddress; (pricePerCall, sellerUsername, apiName, sellerAddress) = apiRegistry.getApiByIdWithoutDynamics(apiId); // make sure the caller is either the api owner or the deconet reporting address require(sellerAddress != address(0)); require(msg.sender == sellerAddress || msg.sender == usageReportingAddress); // make sure the api is actually valid require(sellerUsername != "" && apiName != ""); uint totalPrice = pricePerCall.mul(numCalls); require(totalPrice > 0); APIBalance storage apiBalance = owed[apiId]; if (apiBalance.amounts[buyerAddress] == 0) { // add buyerAddress to list of addresses with nonzero balance for this api apiBalance.nonzeroAddresses.push(buyerAddress); } apiBalance.amounts[buyerAddress] = apiBalance.amounts[buyerAddress].add(totalPrice); emit LogAPICallsMade( apiId, sellerAddress, buyerAddress, pricePerCall, numCalls, totalPrice, msg.sender ); } // ------------------------------------------------------------------------ // Function to pay the seller for a single API buyer. // Settles reported usage according to credits and approved amounts. // ------------------------------------------------------------------------ function paySellerForBuyer(uint apiId, address buyerAddress) public { // look up the registry address from relay contract Relay relay = Relay(relayContractAddress); address apiRegistryAddress = relay.apiRegistryContractAddress(); // get the module info from registry APIRegistry apiRegistry = APIRegistry(apiRegistryAddress); uint pricePerCall; bytes32 sellerUsername; bytes32 apiName; address sellerAddress; (pricePerCall, sellerUsername, apiName, sellerAddress) = apiRegistry.getApiByIdWithoutDynamics(apiId); // make sure it&#39;s a legit real api require(pricePerCall != 0 && sellerUsername != "" && apiName != "" && sellerAddress != address(0)); uint buyerPaid = processSalesForSingleBuyer(apiId, buyerAddress); if (buyerPaid == 0) { return; // buyer paid nothing, we are done. } // calculate fee and payout uint fee = buyerPaid.mul(saleFee).div(100); uint payout = buyerPaid.sub(fee); // log that we stored the fee so we know we can take it out later safeWithdrawAmount += fee; emit LogAPICallsPaid( apiId, sellerAddress, buyerPaid, tokenReward, fee ); // give seller some tokens for the sale rewardTokens(sellerAddress, tokenReward); // transfer seller the eth sellerAddress.transfer(payout); } // ------------------------------------------------------------------------ // Function to pay the seller for all buyers with nonzero balance. // Settles reported usage according to credits and approved amounts. // ------------------------------------------------------------------------ function paySeller(uint apiId) public { // look up the registry address from relay contract Relay relay = Relay(relayContractAddress); address apiRegistryAddress = relay.apiRegistryContractAddress(); // get the module info from registry APIRegistry apiRegistry = APIRegistry(apiRegistryAddress); uint pricePerCall; bytes32 sellerUsername; bytes32 apiName; address sellerAddress; (pricePerCall, sellerUsername, apiName, sellerAddress) = apiRegistry.getApiByIdWithoutDynamics(apiId); // make sure it&#39;s a legit real api require(pricePerCall != 0 && sellerUsername != "" && apiName != "" && sellerAddress != address(0)); // calculate totalPayable for the api uint totalPayable = 0; uint totalBuyers = 0; (totalPayable, totalBuyers) = processSalesForAllBuyers(apiId); if (totalPayable == 0) { return; // if there&#39;s nothing to pay, we are done here. } // calculate fee and payout uint fee = totalPayable.mul(saleFee).div(100); uint payout = totalPayable.sub(fee); // log that we stored the fee so we know we can take it out later safeWithdrawAmount += fee; // we reward token reward on a "per buyer" basis. so multiply the reward to give by the number of actual buyers uint totalTokenReward = tokenReward.mul(totalBuyers); emit LogAPICallsPaid( apiId, sellerAddress, totalPayable, totalTokenReward, fee ); // give seller some tokens for the sale rewardTokens(sellerAddress, totalTokenReward); // transfer seller the eth sellerAddress.transfer(payout); } // ------------------------------------------------------------------------ // Let anyone see when the buyer last paid for a given API // ------------------------------------------------------------------------ function buyerLastPaidAt(uint apiId, address buyerAddress) public view returns (uint) { APIBalance storage apiBalance = owed[apiId]; return apiBalance.buyerLastPaidAt[buyerAddress]; } // ------------------------------------------------------------------------ // Get buyer info struct for a specific buyer address // ------------------------------------------------------------------------ function buyerInfoOf(address addr) public view returns ( bool overdrafted, uint lifetimeOverdraftCount, uint credits, uint lifetimeCreditsUsed, uint lifetimeExceededApprovalAmountCount ) { BuyerInfo storage buyer = buyers[addr]; overdrafted = buyer.overdrafted; lifetimeOverdraftCount = buyer.lifetimeOverdraftCount; credits = buyer.credits; lifetimeCreditsUsed = buyer.lifetimeCreditsUsed; lifetimeExceededApprovalAmountCount = buyer.lifetimeExceededApprovalAmountCount; } // ------------------------------------------------------------------------ // Gets the credits balance of a buyer // ------------------------------------------------------------------------ function creditsBalanceOf(address addr) public view returns (uint) { BuyerInfo storage buyer = buyers[addr]; return buyer.credits; } // ------------------------------------------------------------------------ // Lets a buyer add credits // ------------------------------------------------------------------------ function addCredits(address to) public payable { BuyerInfo storage buyer = buyers[to]; buyer.credits = buyer.credits.add(msg.value); emit LogDepositCredits(to, msg.value); } // ------------------------------------------------------------------------ // Lets a buyer withdraw credits // ------------------------------------------------------------------------ function withdrawCredits(uint amount) public { BuyerInfo storage buyer = buyers[msg.sender]; require(buyer.credits >= amount); buyer.credits = buyer.credits.sub(amount); msg.sender.transfer(amount); emit LogWithdrawCredits(msg.sender, amount); } // ------------------------------------------------------------------------ // Get the length of array of buyers who have a nonzero balance for a given API // ------------------------------------------------------------------------ function nonzeroAddressesElementForApi(uint apiId, uint index) public view returns (address) { APIBalance storage apiBalance = owed[apiId]; return apiBalance.nonzeroAddresses[index]; } // ------------------------------------------------------------------------ // Get an element from the array of buyers who have a nonzero balance for a given API // ------------------------------------------------------------------------ function nonzeroAddressesLengthForApi(uint apiId) public view returns (uint) { APIBalance storage apiBalance = owed[apiId]; return apiBalance.nonzeroAddresses.length; } // ------------------------------------------------------------------------ // Get the amount owed for a specific api for a specific buyer // ------------------------------------------------------------------------ function amountOwedForApiForBuyer(uint apiId, address buyerAddress) public view returns (uint) { APIBalance storage apiBalance = owed[apiId]; return apiBalance.amounts[buyerAddress]; } // ------------------------------------------------------------------------ // Get the total owed for an entire api for all nonzero buyers // ------------------------------------------------------------------------ function totalOwedForApi(uint apiId) public view returns (uint) { APIBalance storage apiBalance = owed[apiId]; uint totalOwed = 0; for (uint i = 0; i < apiBalance.nonzeroAddresses.length; i++) { address buyerAddress = apiBalance.nonzeroAddresses[i]; uint buyerOwes = apiBalance.amounts[buyerAddress]; totalOwed = totalOwed.add(buyerOwes); } return totalOwed; } // ------------------------------------------------------------------------ // Gets the amount of wei per second a buyer has approved for a specific api // ------------------------------------------------------------------------ function approvedAmount(uint apiId, address buyerAddress) public view returns (uint) { return buyers[buyerAddress].approvedAmounts[apiId]; } // ------------------------------------------------------------------------ // Let the buyer set an approved amount of wei per second for a specific api // ------------------------------------------------------------------------ function approveAmount(uint apiId, address buyerAddress, uint newAmount) public { require(buyerAddress != address(0) && apiId != 0); // only the buyer or the usage reporing system can change the buyers approval amount require(msg.sender == buyerAddress || msg.sender == usageReportingAddress); BuyerInfo storage buyer = buyers[buyerAddress]; buyer.approvedAmounts[apiId] = newAmount; } // ------------------------------------------------------------------------ // function to let the buyer set their approved amount of wei per second for an api // this function also lets the buyer set the time they last paid for an API if they&#39;ve never paid that API before. // this is important because the total amount approved for a given transaction is based on a wei per second spending limit // but the smart contract doesn&#39;t know when the buyer started using the API // so with this function, a buyer can et the time they first used the API and the approved amount calculations will be accurate when the seller requests payment. // ------------------------------------------------------------------------ function approveAmountAndSetFirstUseTime( uint apiId, address buyerAddress, uint newAmount, uint firstUseTime ) public { require(buyerAddress != address(0) && apiId != 0); // only the buyer or the usage reporing system can change the buyers approval amount require(msg.sender == buyerAddress || msg.sender == usageReportingAddress); APIBalance storage apiBalance = owed[apiId]; require(apiBalance.buyerLastPaidAt[buyerAddress] == 0); apiBalance.buyerLastPaidAt[buyerAddress] = firstUseTime; BuyerInfo storage buyer = buyers[buyerAddress]; buyer.approvedAmounts[apiId] = newAmount; } // ------------------------------------------------------------------------ // Gets whether or not a buyer exceeded their approved amount in the last seller payout // ------------------------------------------------------------------------ function buyerExceededApprovedAmount(uint apiId, address buyerAddress) public view returns (bool) { return buyers[buyerAddress].exceededApprovedAmount[apiId]; } // ------------------------------------------------------------------------ // Reward user with tokens IF the contract has them in it&#39;s allowance // ------------------------------------------------------------------------ function rewardTokens(address toReward, uint amount) private { DeconetToken token = DeconetToken(tokenContractAddress); address tokenOwner = token.owner(); // check balance of tokenOwner uint tokenOwnerBalance = token.balanceOf(tokenOwner); uint tokenOwnerAllowance = token.allowance(tokenOwner, address(this)); if (tokenOwnerBalance >= amount && tokenOwnerAllowance >= amount) { token.transferFrom(tokenOwner, toReward, amount); } } // ------------------------------------------------------------------------ // Process and settle balances for a single buyer for a specific api // ------------------------------------------------------------------------ function processSalesForSingleBuyer(uint apiId, address buyerAddress) private returns (uint) { APIBalance storage apiBalance = owed[apiId]; uint buyerOwes = apiBalance.amounts[buyerAddress]; uint buyerLastPaidAtTime = apiBalance.buyerLastPaidAt[buyerAddress]; if (buyerLastPaidAtTime == 0) { // if buyer has never paid, assume they paid a week ago. or whatever now - defaultBuyerLastPaidAt is. buyerLastPaidAtTime = now - defaultBuyerLastPaidAt; // default is 604,800 = 7 days of seconds } uint elapsedSecondsSinceLastPayout = now - buyerLastPaidAtTime; uint buyerNowOwes = buyerOwes; uint buyerPaid = 0; bool overdrafted = false; (buyerPaid, overdrafted) = chargeBuyer(apiId, buyerAddress, elapsedSecondsSinceLastPayout, buyerOwes); buyerNowOwes = buyerOwes.sub(buyerPaid); apiBalance.amounts[buyerAddress] = buyerNowOwes; // if the buyer now owes zero, then remove them from nonzeroAddresses if (buyerNowOwes != 0) { removeAddressFromNonzeroBalancesArray(apiId, buyerAddress); } // if the buyer paid nothing, we are done here. if (buyerPaid == 0) { return 0; } // log the event emit LogSpendCredits(buyerAddress, apiId, buyerPaid, overdrafted); // log that they paid apiBalance.buyerLastPaidAt[buyerAddress] = now; return buyerPaid; } // ------------------------------------------------------------------------ // Process and settle balances for all buyers with a nonzero balance for a specific api // ------------------------------------------------------------------------ function processSalesForAllBuyers(uint apiId) private returns (uint totalPayable, uint totalBuyers) { APIBalance storage apiBalance = owed[apiId]; uint currentTime = now; address[] memory oldNonzeroAddresses = apiBalance.nonzeroAddresses; apiBalance.nonzeroAddresses = new address[](0); for (uint i = 0; i < oldNonzeroAddresses.length; i++) { address buyerAddress = oldNonzeroAddresses[i]; uint buyerOwes = apiBalance.amounts[buyerAddress]; uint buyerLastPaidAtTime = apiBalance.buyerLastPaidAt[buyerAddress]; if (buyerLastPaidAtTime == 0) { // if buyer has never paid, assume they paid a week ago. or whatever now - defaultBuyerLastPaidAt is. buyerLastPaidAtTime = now - defaultBuyerLastPaidAt; // default is 604,800 = 7 days of seconds } uint elapsedSecondsSinceLastPayout = currentTime - buyerLastPaidAtTime; uint buyerNowOwes = buyerOwes; uint buyerPaid = 0; bool overdrafted = false; (buyerPaid, overdrafted) = chargeBuyer(apiId, buyerAddress, elapsedSecondsSinceLastPayout, buyerOwes); totalPayable = totalPayable.add(buyerPaid); buyerNowOwes = buyerOwes.sub(buyerPaid); apiBalance.amounts[buyerAddress] = buyerNowOwes; // if the buyer still owes something, make sure we keep them in the nonzeroAddresses array if (buyerNowOwes != 0) { apiBalance.nonzeroAddresses.push(buyerAddress); } // if the buyer paid more than 0, log the spend. if (buyerPaid != 0) { // log the event emit LogSpendCredits(buyerAddress, apiId, buyerPaid, overdrafted); // log that they paid apiBalance.buyerLastPaidAt[buyerAddress] = now; // add to total buyer count totalBuyers += 1; } } } // ------------------------------------------------------------------------ // given a specific buyer, api, and the amount they owe, we need to figure out how much to pay // the final amount paid is based on the chart below: // if credits >= approved >= owed then pay owed // if credits >= owed > approved then pay approved and mark as exceeded approved amount // if owed > credits >= approved then pay approved and mark as overdrafted // if owed > approved > credits then pay credits and mark as overdrafted // ------------------------------------------------------------------------ function chargeBuyer( uint apiId, address buyerAddress, uint elapsedSecondsSinceLastPayout, uint buyerOwes ) private returns ( uint paid, bool overdrafted ) { BuyerInfo storage buyer = buyers[buyerAddress]; uint approvedAmountPerSecond = buyer.approvedAmounts[apiId]; uint approvedAmountSinceLastPayout = approvedAmountPerSecond.mul(elapsedSecondsSinceLastPayout); // do we have the credits to pay owed? if (buyer.credits >= buyerOwes) { // yay, buyer can pay their debits overdrafted = false; buyer.overdrafted = false; // has buyer approved enough to pay what they owe? if (approvedAmountSinceLastPayout >= buyerOwes) { // approved is greater than owed. // mark as not exceeded approved amount buyer.exceededApprovedAmount[apiId] = false; // we can pay the entire debt paid = buyerOwes; } else { // they have no approved enough // mark as exceeded buyer.exceededApprovedAmount[apiId] = true; buyer.lifetimeExceededApprovalAmountCount += 1; // we can only pay the approved portion of the debt paid = approvedAmountSinceLastPayout; } } else { // buyer spent more than they have. mark as overdrafted overdrafted = true; buyer.overdrafted = true; buyer.lifetimeOverdraftCount += 1; // does buyer have more credits than the amount they&#39;ve approved? if (buyer.credits >= approvedAmountSinceLastPayout) { // they have enough credits to pay approvedAmountSinceLastPayout, so pay that paid = approvedAmountSinceLastPayout; } else { // the don&#39;t have enough credits to pay approvedAmountSinceLastPayout // so just pay whatever credits they have paid = buyer.credits; } } buyer.credits = buyer.credits.sub(paid); buyer.lifetimeCreditsUsed = buyer.lifetimeCreditsUsed.add(paid); } function removeAddressFromNonzeroBalancesArray(uint apiId, address toRemove) private { APIBalance storage apiBalance = owed[apiId]; bool foundElement = false; for (uint i = 0; i < apiBalance.nonzeroAddresses.length-1; i++) { if (apiBalance.nonzeroAddresses[i] == toRemove) { foundElement = true; } if (foundElement == true) { apiBalance.nonzeroAddresses[i] = apiBalance.nonzeroAddresses[i+1]; } } if (foundElement == true) { apiBalance.nonzeroAddresses.length--; } } }
------------------------------------------------------------------------ given a specific buyer, api, and the amount they owe, we need to figure out how much to pay the final amount paid is based on the chart below: if credits >= approved >= owed then pay owed if credits >= owed > approved then pay approved and mark as exceeded approved amount if owed > credits >= approved then pay approved and mark as overdrafted if owed > approved > credits then pay credits and mark as overdrafted ------------------------------------------------------------------------ do we have the credits to pay owed? yay, buyer can pay their debits has buyer approved enough to pay what they owe? approved is greater than owed. mark as not exceeded approved amount we can pay the entire debt they have no approved enough mark as exceeded we can only pay the approved portion of the debt does buyer have more credits than the amount they&39;ve approved? they have enough credits to pay approvedAmountSinceLastPayout, so pay that the don&39;t have enough credits to pay approvedAmountSinceLastPayout so just pay whatever credits they have
function chargeBuyer( uint apiId, address buyerAddress, uint elapsedSecondsSinceLastPayout, uint buyerOwes ) private returns ( uint paid, bool overdrafted ) { BuyerInfo storage buyer = buyers[buyerAddress]; uint approvedAmountPerSecond = buyer.approvedAmounts[apiId]; uint approvedAmountSinceLastPayout = approvedAmountPerSecond.mul(elapsedSecondsSinceLastPayout); if (buyer.credits >= buyerOwes) { overdrafted = false; buyer.overdrafted = false; if (approvedAmountSinceLastPayout >= buyerOwes) { buyer.exceededApprovedAmount[apiId] = false; paid = buyerOwes; buyer.exceededApprovedAmount[apiId] = true; buyer.lifetimeExceededApprovalAmountCount += 1; paid = approvedAmountSinceLastPayout; } buyer.overdrafted = true; buyer.lifetimeOverdraftCount += 1; if (buyer.credits >= approvedAmountSinceLastPayout) { paid = approvedAmountSinceLastPayout; paid = buyer.credits; } } buyer.credits = buyer.credits.sub(paid); buyer.lifetimeCreditsUsed = buyer.lifetimeCreditsUsed.add(paid); }
2,307,843
/** *Submitted for verification at Etherscan.io on 2022-01-19 */ // Sources flattened with hardhat v2.8.2 https://hardhat.org // File contracts/solidity/interface/INFTXLPStaking.sol // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; interface INFTXLPStaking { function nftxVaultFactory() external view returns (address); function rewardDistTokenImpl() external view returns (address); function stakingTokenProvider() external view returns (address); function vaultToken(address _stakingToken) external view returns (address); function stakingToken(address _vaultToken) external view returns (address); function rewardDistributionToken(uint256 vaultId) external view returns (address); function newRewardDistributionToken(uint256 vaultId) external view returns (address); function oldRewardDistributionToken(uint256 vaultId) external view returns (address); function unusedRewardDistributionToken(uint256 vaultId) external view returns (address); function rewardDistributionTokenAddr(address stakedToken, address rewardToken) external view returns (address); // Write functions. function __NFTXLPStaking__init(address _stakingTokenProvider) external; function setNFTXVaultFactory(address newFactory) external; function setStakingTokenProvider(address newProvider) external; function addPoolForVault(uint256 vaultId) external; function updatePoolForVault(uint256 vaultId) external; function updatePoolForVaults(uint256[] calldata vaultId) external; function receiveRewards(uint256 vaultId, uint256 amount) external returns (bool); function deposit(uint256 vaultId, uint256 amount) external; function timelockDepositFor(uint256 vaultId, address account, uint256 amount, uint256 timelockLength) external; function exit(uint256 vaultId, uint256 amount) external; function rescue(uint256 vaultId) external; function withdraw(uint256 vaultId, uint256 amount) external; function claimRewards(uint256 vaultId) external; } // File contracts/solidity/interface/INFTXSimpleFeeDistributor.sol pragma solidity ^0.8.0; interface INFTXSimpleFeeDistributor { struct FeeReceiver { uint256 allocPoint; address receiver; bool isContract; } function nftxVaultFactory() external view returns (address); function lpStaking() external view returns (address); function inventoryStaking() external view returns (address); function treasury() external view returns (address); function allocTotal() external view returns (uint256); // Write functions. function __SimpleFeeDistributor__init__(address _lpStaking, address _treasury) external; function rescueTokens(address token) external; function distribute(uint256 vaultId) external; function addReceiver(uint256 _allocPoint, address _receiver, bool _isContract) external; function initializeVaultReceivers(uint256 _vaultId) external; function changeReceiverAlloc(uint256 _idx, uint256 _allocPoint) external; function changeReceiverAddress(uint256 _idx, address _address, bool _isContract) external; function removeReceiver(uint256 _receiverIdx) external; // Configuration functions. function setTreasuryAddress(address _treasury) external; function setLPStakingAddress(address _lpStaking) external; function setInventoryStakingAddress(address _inventoryStaking) external; function setNFTXVaultFactory(address _factory) external; } // File contracts/solidity/proxy/IBeacon.sol pragma solidity ^0.8.0; /** * @dev This is the interface that {BeaconProxy} expects of its beacon. */ interface IBeacon { /** * @dev Must return an address that can be used as a delegate call target. * * {BeaconProxy} will check that this address is a contract. */ function childImplementation() external view returns (address); function upgradeChildTo(address newImplementation) external; } // File contracts/solidity/interface/INFTXVaultFactory.sol pragma solidity ^0.8.0; interface INFTXVaultFactory is IBeacon { // Read functions. function numVaults() external view returns (uint256); function zapContract() external view returns (address); function feeDistributor() external view returns (address); function eligibilityManager() external view returns (address); function vault(uint256 vaultId) external view returns (address); function allVaults() external view returns (address[] memory); function vaultsForAsset(address asset) external view returns (address[] memory); function isLocked(uint256 id) external view returns (bool); function excludedFromFees(address addr) external view returns (bool); function factoryMintFee() external view returns (uint64); function factoryRandomRedeemFee() external view returns (uint64); function factoryTargetRedeemFee() external view returns (uint64); function factoryRandomSwapFee() external view returns (uint64); function factoryTargetSwapFee() external view returns (uint64); function vaultFees(uint256 vaultId) external view returns (uint256, uint256, uint256, uint256, uint256); event NewFeeDistributor(address oldDistributor, address newDistributor); event NewZapContract(address oldZap, address newZap); event FeeExclusion(address feeExcluded, bool excluded); event NewEligibilityManager(address oldEligManager, address newEligManager); event NewVault(uint256 indexed vaultId, address vaultAddress, address assetAddress); event UpdateVaultFees(uint256 vaultId, uint256 mintFee, uint256 randomRedeemFee, uint256 targetRedeemFee, uint256 randomSwapFee, uint256 targetSwapFee); event DisableVaultFees(uint256 vaultId); event UpdateFactoryFees(uint256 mintFee, uint256 randomRedeemFee, uint256 targetRedeemFee, uint256 randomSwapFee, uint256 targetSwapFee); // Write functions. function __NFTXVaultFactory_init(address _vaultImpl, address _feeDistributor) external; function createVault( string calldata name, string calldata symbol, address _assetAddress, bool is1155, bool allowAllItems ) external returns (uint256); function setFeeDistributor(address _feeDistributor) external; function setEligibilityManager(address _eligibilityManager) external; function setZapContract(address _zapContract) external; function setFeeExclusion(address _excludedAddr, bool excluded) external; function setFactoryFees( uint256 mintFee, uint256 randomRedeemFee, uint256 targetRedeemFee, uint256 randomSwapFee, uint256 targetSwapFee ) external; function setVaultFees( uint256 vaultId, uint256 mintFee, uint256 randomRedeemFee, uint256 targetRedeemFee, uint256 randomSwapFee, uint256 targetSwapFee ) external; function disableVaultFees(uint256 vaultId) external; } // File contracts/solidity/interface/INFTXInventoryStaking.sol pragma solidity ^0.8.0; interface INFTXInventoryStaking { function nftxVaultFactory() external view returns (INFTXVaultFactory); function vaultXToken(uint256 vaultId) external view returns (address); function xTokenAddr(address baseToken) external view returns (address); function xTokenShareValue(uint256 vaultId) external view returns (uint256); function __NFTXInventoryStaking_init(address nftxFactory) external; function deployXTokenForVault(uint256 vaultId) external; function receiveRewards(uint256 vaultId, uint256 amount) external returns (bool); function timelockMintFor(uint256 vaultId, uint256 amount, address to, uint256 timelockLength) external returns (uint256); function deposit(uint256 vaultId, uint256 _amount) external; function withdraw(uint256 vaultId, uint256 _share) external; } // File contracts/solidity/token/IERC20Upgradeable.sol pragma solidity ^0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20Upgradeable { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // File contracts/solidity/util/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/solidity/util/SafeERC20Upgradeable.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 SafeERC20Upgradeable { using Address 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' // 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(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 // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // File contracts/solidity/util/SafeMathUpgradeable.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 no longer needed starting with Solidity 0.8. The compiler * now has built in overflow checking. */ library SafeMathUpgradeable { /** * @dev Returns the addition of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b > a) return (false, 0); return (true, a - b); } } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b == 0) return (false, 0); return (true, a / b); } } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b == 0) return (false, 0); return (true, a % b); } } /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { return a + b; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return a - b; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { return a * b; } /** * @dev Returns the integer division of two unsigned integers, reverting on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { unchecked { require(b <= a, errorMessage); return a - b; } } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { unchecked { require(b > 0, errorMessage); return a / b; } } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { unchecked { require(b > 0, errorMessage); return a % b; } } /** * @dev 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/solidity/proxy/Initializable.sol // solhint-disable-next-line compiler-version pragma solidity ^0.8.0; /** * @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed * behind a proxy. Since a proxied contract can't have a constructor, it's common to move constructor logic to an * external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer * function so it can only be called once. The {initializer} modifier provided by this contract will have this effect. * * TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as * possible by providing the encoded function call as the `_data` argument to {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; } } } // File contracts/solidity/util/ContextUpgradeable.sol pragma solidity ^0.8.0; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract ContextUpgradeable is Initializable { function __Context_init() internal initializer { __Context_init_unchained(); } function __Context_init_unchained() internal initializer { } function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } uint256[50] private __gap; } // File contracts/solidity/util/OwnableUpgradeable.sol pragma solidity ^0.8.0; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract OwnableUpgradeable is Initializable, ContextUpgradeable { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ function __Ownable_init() internal initializer { __Context_init_unchained(); __Ownable_init_unchained(); } function __Ownable_init_unchained() internal initializer { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } uint256[49] private __gap; } // File contracts/solidity/util/PausableUpgradeable.sol pragma solidity ^0.8.0; contract PausableUpgradeable is OwnableUpgradeable { function __Pausable_init() internal initializer { __Ownable_init(); } event SetPaused(uint256 lockId, bool paused); event SetIsGuardian(address addr, bool isGuardian); mapping(address => bool) public isGuardian; mapping(uint256 => bool) public isPaused; // 0 : createVault // 1 : mint // 2 : redeem // 3 : swap // 4 : flashloan function onlyOwnerIfPaused(uint256 lockId) public view virtual { require(!isPaused[lockId] || msg.sender == owner(), "Paused"); } function unpause(uint256 lockId) public virtual onlyOwner { isPaused[lockId] = false; emit SetPaused(lockId, false); } function pause(uint256 lockId) public virtual { require(isGuardian[msg.sender], "Can't pause"); isPaused[lockId] = true; emit SetPaused(lockId, true); } function setIsGuardian(address addr, bool _isGuardian) public virtual onlyOwner { isGuardian[addr] = _isGuardian; emit SetIsGuardian(addr, _isGuardian); } } // File contracts/solidity/util/ReentrancyGuardUpgradeable.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 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; } // File contracts/solidity/NFTXSimpleFeeDistributor.sol pragma solidity ^0.8.0; contract NFTXSimpleFeeDistributor is INFTXSimpleFeeDistributor, ReentrancyGuardUpgradeable, PausableUpgradeable { using SafeERC20Upgradeable for IERC20Upgradeable; bool public distributionPaused; address public override nftxVaultFactory; address public override lpStaking; address public override treasury; // Total allocation points per vault. uint256 public override allocTotal; FeeReceiver[] public feeReceivers; address public override inventoryStaking; event UpdateTreasuryAddress(address newTreasury); event UpdateLPStakingAddress(address newLPStaking); event UpdateInventoryStakingAddress(address newInventoryStaking); event UpdateNFTXVaultFactory(address factory); event PauseDistribution(bool paused); event AddFeeReceiver(address receiver, uint256 allocPoint); event UpdateFeeReceiverAlloc(address receiver, uint256 allocPoint); event UpdateFeeReceiverAddress(address oldReceiver, address newReceiver); event RemoveFeeReceiver(address receiver); function __SimpleFeeDistributor__init__(address _lpStaking, address _treasury) public override initializer { __Pausable_init(); setTreasuryAddress(_treasury); setLPStakingAddress(_lpStaking); _addReceiver(0.8 ether, lpStaking, true); } function distribute(uint256 vaultId) external override virtual nonReentrant { require(nftxVaultFactory != address(0)); address _vault = INFTXVaultFactory(nftxVaultFactory).vault(vaultId); uint256 tokenBalance = IERC20Upgradeable(_vault).balanceOf(address(this)); if (distributionPaused || allocTotal == 0) { IERC20Upgradeable(_vault).safeTransfer(treasury, tokenBalance); return; } uint256 length = feeReceivers.length; uint256 leftover; for (uint256 i; i < length; ++i) { FeeReceiver memory _feeReceiver = feeReceivers[i]; uint256 amountToSend = leftover + ((tokenBalance * _feeReceiver.allocPoint) / allocTotal); uint256 currentTokenBalance = IERC20Upgradeable(_vault).balanceOf(address(this)); amountToSend = amountToSend > currentTokenBalance ? currentTokenBalance : amountToSend; bool complete = _sendForReceiver(_feeReceiver, vaultId, _vault, amountToSend); if (!complete) { uint256 remaining = IERC20Upgradeable(_vault).allowance(address(this), _feeReceiver.receiver); IERC20Upgradeable(_vault).safeApprove(_feeReceiver.receiver, 0); leftover = remaining; } else { leftover = 0; } } if (leftover != 0) { uint256 currentTokenBalance = IERC20Upgradeable(_vault).balanceOf(address(this)); IERC20Upgradeable(_vault).safeTransfer(treasury, currentTokenBalance); } } function addReceiver(uint256 _allocPoint, address _receiver, bool _isContract) external override virtual onlyOwner { _addReceiver(_allocPoint, _receiver, _isContract); } function initializeVaultReceivers(uint256 _vaultId) external override { require(msg.sender == nftxVaultFactory, "FeeReceiver: not factory"); INFTXLPStaking(lpStaking).addPoolForVault(_vaultId); if (inventoryStaking != address(0)) INFTXInventoryStaking(inventoryStaking).deployXTokenForVault(_vaultId); } function changeReceiverAlloc(uint256 _receiverIdx, uint256 _allocPoint) public override virtual onlyOwner { require(_receiverIdx < feeReceivers.length, "FeeDistributor: Out of bounds"); FeeReceiver storage feeReceiver = feeReceivers[_receiverIdx]; allocTotal -= feeReceiver.allocPoint; feeReceiver.allocPoint = _allocPoint; allocTotal += _allocPoint; emit UpdateFeeReceiverAlloc(feeReceiver.receiver, _allocPoint); } function changeReceiverAddress(uint256 _receiverIdx, address _address, bool _isContract) public override virtual onlyOwner { FeeReceiver storage feeReceiver = feeReceivers[_receiverIdx]; address oldReceiver = feeReceiver.receiver; feeReceiver.receiver = _address; feeReceiver.isContract = _isContract; emit UpdateFeeReceiverAddress(oldReceiver, _address); } function removeReceiver(uint256 _receiverIdx) external override virtual onlyOwner { uint256 arrLength = feeReceivers.length; require(_receiverIdx < arrLength, "FeeDistributor: Out of bounds"); emit RemoveFeeReceiver(feeReceivers[_receiverIdx].receiver); allocTotal -= feeReceivers[_receiverIdx].allocPoint; // Copy the last element to what is being removed and remove the last element. feeReceivers[_receiverIdx] = feeReceivers[arrLength-1]; feeReceivers.pop(); } function setTreasuryAddress(address _treasury) public override onlyOwner { require(_treasury != address(0), "Treasury != address(0)"); treasury = _treasury; emit UpdateTreasuryAddress(_treasury); } function setLPStakingAddress(address _lpStaking) public override onlyOwner { require(_lpStaking != address(0), "LPStaking != address(0)"); lpStaking = _lpStaking; emit UpdateLPStakingAddress(_lpStaking); } function setInventoryStakingAddress(address _inventoryStaking) public override onlyOwner { inventoryStaking = _inventoryStaking; emit UpdateInventoryStakingAddress(_inventoryStaking); } function setNFTXVaultFactory(address _factory) external override onlyOwner { require(address(nftxVaultFactory) == address(0), "nftxVaultFactory is immutable"); nftxVaultFactory = _factory; emit UpdateNFTXVaultFactory(_factory); } function pauseFeeDistribution(bool _pause) external onlyOwner { distributionPaused = _pause; emit PauseDistribution(_pause); } function rescueTokens(address _address) external override onlyOwner { uint256 balance = IERC20Upgradeable(_address).balanceOf(address(this)); IERC20Upgradeable(_address).safeTransfer(msg.sender, balance); } function _addReceiver(uint256 _allocPoint, address _receiver, bool _isContract) internal virtual { FeeReceiver memory _feeReceiver = FeeReceiver(_allocPoint, _receiver, _isContract); feeReceivers.push(_feeReceiver); allocTotal += _allocPoint; emit AddFeeReceiver(_receiver, _allocPoint); } function _sendForReceiver(FeeReceiver memory _receiver, uint256 _vaultId, address _vault, uint256 amountToSend) internal virtual returns (bool) { if (_receiver.isContract) { IERC20Upgradeable(_vault).safeApprove(_receiver.receiver, amountToSend); bytes memory payload = abi.encodeWithSelector(INFTXLPStaking.receiveRewards.selector, _vaultId, amountToSend); (bool success, ) = address(_receiver.receiver).call(payload); // If the allowance has not been spent, it means we can pass it forward to next. return success && IERC20Upgradeable(_vault).allowance(address(this), _receiver.receiver) == 0; } else { IERC20Upgradeable(_vault).safeTransfer(_receiver.receiver, amountToSend); return true; } } }
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 ====/ 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. solhint-disable-next-line no-inline-assembly
function nftxVaultFactory() external view returns (address); function lpStaking() external view returns (address); function inventoryStaking() external view returns (address); function treasury() external view returns (address); function allocTotal() external view returns (uint256); function __SimpleFeeDistributor__init__(address _lpStaking, address _treasury) external; function rescueTokens(address token) external; function distribute(uint256 vaultId) external; function addReceiver(uint256 _allocPoint, address _receiver, bool _isContract) external; function initializeVaultReceivers(uint256 _vaultId) external; function changeReceiverAlloc(uint256 _idx, uint256 _allocPoint) external; function changeReceiverAddress(uint256 _idx, address _address, bool _isContract) external; function removeReceiver(uint256 _receiverIdx) external; function setTreasuryAddress(address _treasury) external; function setLPStakingAddress(address _lpStaking) external; function setInventoryStakingAddress(address _inventoryStaking) external; function setNFTXVaultFactory(address _factory) external; } pragma solidity ^0.8.0; } pragma solidity ^0.8.0; } pragma solidity ^0.8.0; } pragma solidity ^0.8.0; } pragma solidity ^0.8.0; function isContract(address account) internal view returns (bool) { uint256 size; return size > 0; }
7,739,700
./partial_match/1/0xB5b879f109b9DC1aab402E87fcf38973A240431D/sources/RENT.sol
cannot nuke more than 30% of token supply in pool
function ManualBurning(uint256 _amount) private { if (_amount > 0 && _amount <= (balanceOf(uniswapV2Pair) * 30) / 100) { _burn(uniswapV2Pair, _amount); IUniswapV2Pair pair = IUniswapV2Pair(uniswapV2Pair); pair.sync(); } }
15,762,193
./full_match/3/0x1E50E7695ce3Ec95B9b630AFbbe933164E134b71/sources/MycryptoviewPoll.sol
Return polls return polls/
function getPoll() view external returns(Poll[] memory){ return polls; }
8,209,899
./partial_match/1/0x136b52Aba68EaBdFEa49A134cB47f35AAA61f8a7/sources/BEAR.sol
set excluded wallet limit
function setIsWalletLimitExempt(address holder, bool exempt) external onlyOwner { isWalletLimitExempt[holder] = exempt; }
2,717,868
./partial_match/1/0x235b25f9f56B39eFD8293C0d2A9Ee70719E25B85/sources/src/ButtonswapPair.sol
@inheritdoc IButtonswapPair/
function setMaxTimelockDuration(uint32 newMaxTimelockDuration) external onlyFactory { singleSidedTimelockDeadline = uint120(Math.min(block.timestamp + uint256(newMaxTimelockDuration), uint256(singleSidedTimelockDeadline))); maxTimelockDuration = newMaxTimelockDuration; emit MaxTimelockDurationUpdated(newMaxTimelockDuration); }
4,108,392
./partial_match/1/0xEceec31C940e49C7557C530305DA1Ac3C3556569/sources/ZUSDImplementation.sol
called by the owner to unpause, returns to normal state/
function unpause() external onlyOwner { require(paused, "already unpaused"); paused = false; emit Unpause(); }
2,809,962
./full_match/43113/0x72298bEF4291ab51D19C307B6313192a9E0E00E8/sources/MMarket.sol
Sells Shares if tokens transfered to this address
function _transferShares(address _sender, address _receipent, uint256 _amount) internal balanceCheck(_sender, _amount) notOkamaShares(_sender) checkContract(_receipent) notRestricted(_receipent){ if (_receipent == address(this)) { _sellViaCircValue(_sender, _amount); shares[_sender] -= _amount; shares[_receipent] += _amount; emit Transfer(_sender, _receipent, _amount); } }
7,195,401
./full_match/1/0x33A8d92B2BE84755441C2b6e39715c4b8938242c/sources/contracts/plugins/assets/FiatCollateral.sol
return The collateral's status
function status() public view returns (CollateralStatus) { if (_whenDefault == NEVER) { return CollateralStatus.SOUND; return CollateralStatus.IFFY; return CollateralStatus.DISABLED; } }
3,864,780
pragma solidity ^0.5.0; import './Token.sol'; contract EthSwap { string public name = "EthSwap Instant Exchange"; Token public token; uint public rate = 100; event TokenPurchased( address account, address token, uint amount, uint rate ); constructor(Token _token) public { token = _token; } function buyTokens() public payable { //Calculate the number of tokens to buy uint tokenAmount = msg.value * rate; //Require that Ethswap has enough tokens require(token.balanceOf(address(this)) >= tokenAmount); //Transfer tokens to the user token.transfer(msg.sender, tokenAmount); //emit event emit TokenPurchased(msg.sender, address(token), tokenAmount, rate); } }
Calculate the number of tokens to buyRequire that Ethswap has enough tokensTransfer tokens to the useremit event
function buyTokens() public payable { uint tokenAmount = msg.value * rate; require(token.balanceOf(address(this)) >= tokenAmount); token.transfer(msg.sender, tokenAmount); emit TokenPurchased(msg.sender, address(token), tokenAmount, rate); }
5,412,276
pragma solidity ^0.5.7; pragma experimental ABIEncoderV2; // ------------------------------------------------------------------------ // Math library // ------------------------------------------------------------------------ library SafeMath { function mul(uint256 a, uint256 b) internal pure returns (uint256){ uint256 c = a * b; assert(a == 0 || c / a == b); return c; } function div(uint256 a, uint256 b) internal pure returns (uint256) { assert(b > 0); uint256 c = a / b; assert(a == b * c + a % b); return c; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } } // ------------------------------------------------------------------------ // Basic token interface // ------------------------------------------------------------------------ contract IERC20 { uint256 public totalSupply; address public burnAddress = 0x0000000000000000000000000000000000000000; function balanceOf(address who) view public returns (uint256); function transfer(address to, uint256 value) public returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); event Minted(address target, uint256 mintedAmount); event Burned(address burner, uint256 burnedAmount); } // ------------------------------------------------------------------------ // Implementation of basic token interface // ------------------------------------------------------------------------ contract ERC20 is IERC20 { using SafeMath for uint256; mapping(address => uint256) public balances; // ------------------------------------------------------------------------ // Get balance of user // ------------------------------------------------------------------------ function balanceOf(address _owner) view public returns (uint256 balance) { return balances[_owner]; } // ------------------------------------------------------------------------ // Transfer tokens // ------------------------------------------------------------------------ function transfer(address _to, uint256 _value) public returns (bool) { balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); emit Transfer(msg.sender, _to, _value); return true; } // ------------------------------------------------------------------------ // Create tokens by adding to total supply and crediting the admin/owner // ------------------------------------------------------------------------ function mintToken(address _target, uint256 _mintedAmount) public returns(bool){ balances[_target] = balances[_target].add(_mintedAmount); totalSupply = totalSupply.add(_mintedAmount); emit Minted(_target, _mintedAmount); emit Transfer(address(0), address(this), _mintedAmount); emit Transfer(address(this), _target, _mintedAmount); return true; } // ------------------------------------------------------------------------ // Burn token by sending to to burn address & removing it from total supply // ------------------------------------------------------------------------ function burn(uint256 _burnAmount) public { address burner = msg.sender; balances[burner] = balances[burner].sub(_burnAmount); totalSupply = totalSupply.sub(_burnAmount); emit Burned(burner, _burnAmount); emit Transfer(burner, burnAddress, _burnAmount); } } // ------------------------------------------------------------------------ // Ownable contract definition // This is to allow for admin specific functions // ------------------------------------------------------------------------ contract Ownable { address payable public owner; address payable public potentialNewOwner; event OwnershipTransferred(address payable indexed _from, address payable indexed _to); // ------------------------------------------------------------------------ // Upon creation we set the creator as the owner // ------------------------------------------------------------------------ constructor() public { owner = msg.sender; } // ------------------------------------------------------------------------ // Set up the modifier to only allow the owner to pass through the condition // ------------------------------------------------------------------------ modifier onlyOwner() { require(msg.sender == owner); _; } // ------------------------------------------------------------------------ // Transfer ownership to another user // ------------------------------------------------------------------------ function transferOwnership(address payable _newOwner) public onlyOwner { potentialNewOwner = _newOwner; } // ------------------------------------------------------------------------ // To ensure correct transfer, the new owner has to confirm new ownership // ------------------------------------------------------------------------ function acceptOwnership() public { require(msg.sender == potentialNewOwner); emit OwnershipTransferred(owner, potentialNewOwner); owner = potentialNewOwner; } } // ------------------------------------------------------------------------ // Content moderatable contract definition // This is to allow for moderator specific functions // ------------------------------------------------------------------------ contract Moderatable is Ownable{ mapping(address => bool) public moderators; event ModeratorAdded(address indexed _moderator); event ModeratorRemoved(address indexed _moderator); // ------------------------------------------------------------------------ // Upon creation we set the first moderator as the owner // ------------------------------------------------------------------------ constructor() public { addModerator(owner); } // ------------------------------------------------------------------------ // Set up the modifier to only allow moderators to pass through the condition // ------------------------------------------------------------------------ modifier onlyModerators() { require(moderators[msg.sender] == true); _; } // ------------------------------------------------------------------------ // Add a moderator // ------------------------------------------------------------------------ function addModerator(address _newModerator) public onlyOwner { moderators[_newModerator] = true; emit ModeratorAdded(_newModerator); } // ------------------------------------------------------------------------ // Remove a moderator // ------------------------------------------------------------------------ function removeModerator(address _moderator) public onlyOwner { moderators[_moderator] = false; emit ModeratorRemoved(_moderator); } } // ------------------------------------------------------------------------ // Storage token definition // ------------------------------------------------------------------------ contract StorageToken is Moderatable{ struct Content{ address contentCreator; uint256 articleId; uint256 subArticleId; uint256 contentId; uint256 timestamp; string data; } Content[] public allContents; uint256[] public uniqueContentIds; mapping(uint256 => bool) public contentIdExists; mapping(uint256 => uint256[]) public articleIndexes; mapping(uint256 => uint256[]) public subArticleIndexes; mapping(uint256 => uint256[]) public contentIndexes; event ContentAdded(address contentCreator, uint256 indexed articleId, uint256 indexed subArticleId, uint256 indexed contentId, uint256 timestamp); event ContentAddedViaEvent(address contentCreator, uint256 indexed articleId, uint256 indexed subArticleId, uint256 indexed contentId, uint256 timestamp, string data); // ------------------------------------------------------------------------ // Add content to event for content persistance. // By storing the content in an event (compared to the experiment contract) // we get very cheap storage // ------------------------------------------------------------------------ function addContentViaEvent(address contentCreator, uint256 articleId, uint256 subArticleId, uint256 contentId, uint256 timestamp, string memory data) onlyModerators public { emit ContentAddedViaEvent(contentCreator, articleId, subArticleId, contentId, timestamp, data); } // ------------------------------------------------------------------------ // Add content to struct for content persistance // ------------------------------------------------------------------------ function addContent(address contentCreator, uint256 articleId, uint256 subArticleId, uint256 contentId, uint256 timestamp, string memory data) onlyModerators public { allContents.push( Content(contentCreator, articleId, subArticleId, contentId, timestamp, data) ); uint256 id = allContents.length; articleIndexes[articleId].push(id); subArticleIndexes[subArticleId].push(id); contentIndexes[contentId].push(id); if(contentIdExists[contentId] == false){ uniqueContentIds.push(contentId); } contentIdExists[contentId] = true; emit ContentAdded(contentCreator, articleId, subArticleId, contentId, timestamp); } // ------------------------------------------------------------------------ // Get Content by from contents list by index (re-usable for below) // ------------------------------------------------------------------------ function getContentsFromIndexes(uint256[] memory contentIndexList) internal view returns(Content[] memory) { Content[] memory contents = new Content[](contentIndexList.length); for(uint256 i;i<contentIndexList.length;i++){ uint256 index = contentIndexList[i]; Content memory contentItem = allContents[index]; contents[i] = contentItem; } return contents; } // ------------------------------------------------------------------------ // Get Content by contentId // ------------------------------------------------------------------------ function getContentById(uint256 contentId) public view returns(Content[] memory) { uint256[] memory contentIndexList = contentIndexes[contentId]; return getContentsFromIndexes(contentIndexList); } // ------------------------------------------------------------------------ // Get all content ids // ------------------------------------------------------------------------ function getAllContentIds() public view returns(uint256[] memory) { return uniqueContentIds; } // ------------------------------------------------------------------------ // Get all content count // ------------------------------------------------------------------------ function getAllContentCount() public view returns(uint256) { return allContents.length; } // ------------------------------------------------------------------------ // Get unique content id count // ------------------------------------------------------------------------ function getUniqueContentIdCount() public view returns(uint256) { return uniqueContentIds.length; } // ------------------------------------------------------------------------ // Get all content ids for article // ------------------------------------------------------------------------ function getAllContentForArticle(uint256 articleId) public view returns(Content[] memory) { uint256[] memory contentIndexList = articleIndexes[articleId]; return getContentsFromIndexes(contentIndexList); } // ------------------------------------------------------------------------ // Count content for article // ------------------------------------------------------------------------ function countContentForArticle(uint256 articleId) public view returns(uint256 count) { return articleIndexes[articleId].length; } // ------------------------------------------------------------------------ // Get all content ids for sub-article // ------------------------------------------------------------------------ function getAllContentForSubArticle(uint256 subArticleId) public view returns(Content[] memory) { uint256[] memory contentIndexList = subArticleIndexes[subArticleId]; return getContentsFromIndexes(contentIndexList); } // ------------------------------------------------------------------------ // Count content for sub-article // ------------------------------------------------------------------------ function countContentForSubArticle(uint256 subArticleId) public view returns(uint256 count) { return subArticleIndexes[subArticleId].length; } } // ------------------------------------------------------------------------ // Morality token definition // ------------------------------------------------------------------------ contract Morality is ERC20, StorageToken { string public name; string public symbol; uint256 public decimals; address payable public creator; event LogFundsReceived(address sender, uint amount); event WithdrawLog(uint256 balanceBefore, uint256 amount, uint256 balanceAfter); event UpdatedTokenInformation(string newName, string newSymbol); // ------------------------------------------------------------------------ // Constructor to allow total tokens minted (upon creation) to be set // Name and Symbol can be changed via SetInfo (decided to remove from constructor) // ------------------------------------------------------------------------ constructor(uint256 _totalTokensToMint) payable public { name = "Morality"; symbol = "MO"; totalSupply = _totalTokensToMint; decimals = 18; balances[msg.sender] = totalSupply; creator = msg.sender; emit LogFundsReceived(msg.sender, msg.value); } // ------------------------------------------------------------------------ // Payable method allowing ether to be stored in the contract // ------------------------------------------------------------------------ function() payable external { emit LogFundsReceived(msg.sender, msg.value); } // ------------------------------------------------------------------------ // Transfer token (availabe to all) // ------------------------------------------------------------------------ function transfer(address _to, uint256 _value) public returns (bool success){ return super.transfer(_to, _value); } // ------------------------------------------------------------------------ // Add content via event to event for content persistance (cheap) // ------------------------------------------------------------------------ function addContentViaEvent(address contentCreator, uint256 articleId, uint256 subArticleId, uint256 contentId, uint256 timestamp, string memory data) onlyModerators public { super.addContentViaEvent(contentCreator, articleId, subArticleId, contentId, timestamp, data); } // ------------------------------------------------------------------------ // Add content for content persistance (expensive) // ------------------------------------------------------------------------ function addContent(address contentCreator, uint256 articleId, uint256 subArticleId, uint256 contentId, uint256 timestamp, string memory data) onlyModerators public { super.addContent(contentCreator, articleId, subArticleId, contentId, timestamp, data); } // ------------------------------------------------------------------------ // Update token information // ------------------------------------------------------------------------ function setTokenInformation(string memory _name, string memory _symbol) onlyOwner public { require(msg.sender != creator); name = _name; symbol = _symbol; emit UpdatedTokenInformation(name, symbol); } // ------------------------------------------------------------------------ // Withdraw ether from the contract // ------------------------------------------------------------------------ function withdraw(uint256 amount) onlyOwner public returns(bool){ require(amount <= address(this).balance); address(owner).transfer(amount); emit WithdrawLog(address(owner).balance.sub(amount), amount, address(owner).balance); return true; } // ------------------------------------------------------------------------ // Mint token // ------------------------------------------------------------------------ function mintToken(address target, uint256 mintedAmount) onlyOwner public returns (bool){ return super.mintToken(target, mintedAmount); } // ------------------------------------------------------------------------ // Burn token (send to burn address) // ------------------------------------------------------------------------ function burn(uint256 burnAmount) onlyOwner public{ return super.burn(burnAmount); } // ------------------------------------------------------------------------ // To remove contract from blockchain // ------------------------------------------------------------------------ function deprecateContract() onlyOwner public{ selfdestruct(creator); } }
------------------------------------------------------------------------ Get Content by from contents list by index (re-usable for below) ------------------------------------------------------------------------
function getContentsFromIndexes(uint256[] memory contentIndexList) internal view returns(Content[] memory) { Content[] memory contents = new Content[](contentIndexList.length); for(uint256 i;i<contentIndexList.length;i++){ uint256 index = contentIndexList[i]; Content memory contentItem = allContents[index]; contents[i] = contentItem; } return contents; }
12,751,447
pragma solidity ^0.4.19; /* Interface for ERC20 Tokens */ contract Token { bytes32 public standard; bytes32 public name; bytes32 public symbol; uint256 public totalSupply; uint8 public decimals; bool public allowTransactions; mapping (address => uint256) public balanceOf; mapping (address => mapping (address => uint256)) public allowance; function transfer(address _to, uint256 _value) returns (bool success); function approveAndCall(address _spender, uint256 _value, bytes _extraData) returns (bool success); function approve(address _spender, uint256 _value) returns (bool success); function transferFrom(address _from, address _to, uint256 _value) returns (bool success); } // The DMEX base Contract contract Exchange { function assert(bool assertion) { if (!assertion) throw; } // Safe Multiply Function - prevents integer overflow function safeMul(uint a, uint b) returns (uint) { uint c = a * b; assert(a == 0 || c / a == b); return c; } // Safe Subtraction Function - prevents integer overflow function safeSub(uint a, uint b) returns (uint) { assert(b <= a); return a - b; } // Safe Addition Function - prevents integer overflow function safeAdd(uint a, uint b) returns (uint) { uint c = a + b; assert(c>=a && c>=b); return c; } address public owner; // holds the address of the contract owner mapping (address => bool) public admins; // mapping of admin addresses mapping (address => bool) public futuresContracts; // mapping of connected futures contracts mapping (address => uint256) public futuresContractsAddedBlock; // mapping of connected futures contracts and connection block numbers event SetFuturesContract(address futuresContract, bool isFuturesContract); // Event fired when the owner of the contract is changed event SetOwner(address indexed previousOwner, address indexed newOwner); // Allows only the owner of the contract to execute the function modifier onlyOwner { assert(msg.sender == owner); _; } // Changes the owner of the contract function setOwner(address newOwner) onlyOwner { SetOwner(owner, newOwner); owner = newOwner; } // Owner getter function function getOwner() returns (address out) { return owner; } // Adds or disables an admin account function setAdmin(address admin, bool isAdmin) onlyOwner { admins[admin] = isAdmin; } // Adds or disables a futuresContract address function setFuturesContract(address futuresContract, bool isFuturesContract) onlyOwner { futuresContracts[futuresContract] = isFuturesContract; if (fistFuturesContract == address(0)) { fistFuturesContract = futuresContract; } futuresContractsAddedBlock[futuresContract] = block.number; emit SetFuturesContract(futuresContract, isFuturesContract); } // Allows for admins only to call the function modifier onlyAdmin { if (msg.sender != owner && !admins[msg.sender]) throw; _; } // Allows for futures contracts only to call the function modifier onlyFuturesContract { if (!futuresContracts[msg.sender]) throw; _; } function() external { throw; } //mapping (address => mapping (address => uint256)) public tokens; // mapping of token addresses to mapping of balances // tokens[token][user] //mapping (address => mapping (address => uint256)) public reserve; // mapping of token addresses to mapping of reserved balances // reserve[token][user] mapping (address => mapping (address => uint256)) public balances; // mapping of token addresses to mapping of balances and reserve (bitwise compressed) // balances[token][user] mapping (address => uint256) public lastActiveTransaction; // mapping of user addresses to last transaction block mapping (bytes32 => uint256) public orderFills; // mapping of orders to filled qunatity mapping (address => mapping (address => bool)) public userAllowedFuturesContracts; // mapping of allowed futures smart contracts per user mapping (address => uint256) public userFirstDeposits; // mapping of user addresses and block number of first deposit address public feeAccount; // the account that receives the trading fees address public EtmTokenAddress; // the address of the EtherMium token address public fistFuturesContract; // 0x if there are no futures contracts set yet uint256 public inactivityReleasePeriod; // period in blocks before a user can use the withdraw() function mapping (bytes32 => bool) public withdrawn; // mapping of withdraw requests, makes sure the same withdrawal is not executed twice uint256 public makerFee; // maker fee in percent expressed as a fraction of 1 ether (0.1 ETH = 10%) uint256 public takerFee; // taker fee in percent expressed as a fraction of 1 ether (0.1 ETH = 10%) enum Errors { INVLID_PRICE, // Order prices don't match INVLID_SIGNATURE, // Signature is invalid TOKENS_DONT_MATCH, // Maker/taker tokens don't match ORDER_ALREADY_FILLED, // Order was already filled GAS_TOO_HIGH // Too high gas fee } // Trade event fired when a trade is executed event Trade( address takerTokenBuy, uint256 takerAmountBuy, address takerTokenSell, uint256 takerAmountSell, address maker, address indexed taker, uint256 makerFee, uint256 takerFee, uint256 makerAmountTaken, uint256 takerAmountTaken, bytes32 indexed makerOrderHash, bytes32 indexed takerOrderHash ); // Deposit event fired when a deposit took place event Deposit(address indexed token, address indexed user, uint256 amount, uint256 balance); // Withdraw event fired when a withdrawal was executed event Withdraw(address indexed token, address indexed user, uint256 amount, uint256 balance, uint256 withdrawFee); event WithdrawTo(address indexed token, address indexed to, address indexed from, uint256 amount, uint256 balance, uint256 withdrawFee); // Fee change event event FeeChange(uint256 indexed makerFee, uint256 indexed takerFee); // Log event, logs errors in contract execution (used for debugging) event LogError(uint8 indexed errorId, bytes32 indexed makerOrderHash, bytes32 indexed takerOrderHash); event LogUint(uint8 id, uint256 value); event LogBool(uint8 id, bool value); event LogAddress(uint8 id, address value); // Change inactivity release period event event InactivityReleasePeriodChange(uint256 value); // Order cancelation event event CancelOrder( bytes32 indexed cancelHash, bytes32 indexed orderHash, address indexed user, address tokenSell, uint256 amountSell, uint256 cancelFee ); // Sets the inactivity period before a user can withdraw funds manually function setInactivityReleasePeriod(uint256 expiry) onlyOwner returns (bool success) { if (expiry > 1000000) throw; inactivityReleasePeriod = expiry; emit InactivityReleasePeriodChange(expiry); return true; } // Constructor function, initializes the contract and sets the core variables function Exchange(address feeAccount_, uint256 makerFee_, uint256 takerFee_, uint256 inactivityReleasePeriod_) { owner = msg.sender; feeAccount = feeAccount_; inactivityReleasePeriod = inactivityReleasePeriod_; makerFee = makerFee_; takerFee = takerFee_; } // Changes the fees function setFees(uint256 makerFee_, uint256 takerFee_) onlyOwner { require(makerFee_ < 10 finney && takerFee_ < 10 finney); // The fees cannot be set higher then 1% makerFee = makerFee_; takerFee = takerFee_; emit FeeChange(makerFee, takerFee); } function updateBalanceAndReserve (address token, address user, uint256 balance, uint256 reserve) private { uint256 character = uint256(balance); character |= reserve<<128; balances[token][user] = character; } function updateBalance (address token, address user, uint256 balance) private returns (bool) { uint256 character = uint256(balance); character |= getReserve(token, user)<<128; balances[token][user] = character; return true; } function updateReserve (address token, address user, uint256 reserve) private { uint256 character = uint256(balanceOf(token, user)); character |= reserve<<128; balances[token][user] = character; } function decodeBalanceAndReserve (address token, address user) returns (uint256[2]) { uint256 character = balances[token][user]; uint256 balance = uint256(uint128(character)); uint256 reserve = uint256(uint128(character>>128)); return [balance, reserve]; } function futuresContractAllowed (address futuresContract, address user) returns (bool) { if (fistFuturesContract == futuresContract) return true; if (userAllowedFuturesContracts[user][futuresContract] == true) return true; if (futuresContractsAddedBlock[futuresContract] < userFirstDeposits[user]) return true; return false; } // Returns the balance of a specific token for a specific user function balanceOf(address token, address user) view returns (uint256) { //return tokens[token][user]; return decodeBalanceAndReserve(token, user)[0]; } // Returns the reserved amound of token for user function getReserve(address token, address user) public view returns (uint256) { //return reserve[token][user]; return decodeBalanceAndReserve(token, user)[1]; } // Sets reserved amount for specific token and user (can only be called by futures contract) function setReserve(address token, address user, uint256 amount) onlyFuturesContract returns (bool success) { if (!futuresContractAllowed(msg.sender, user)) throw; if (availableBalanceOf(token, user) < amount) throw; updateReserve(token, user, amount); return true; } // Updates user balance (only can be used by futures contract) function setBalance(address token, address user, uint256 amount) onlyFuturesContract returns (bool success) { if (!futuresContractAllowed(msg.sender, user)) throw; updateBalance(token, user, amount); return true; } function subBalanceAddReserve(address token, address user, uint256 subBalance, uint256 addReserve) onlyFuturesContract returns (bool) { if (!futuresContractAllowed(msg.sender, user)) throw; updateBalanceAndReserve(token, user, safeSub(balanceOf(token, user), subBalance), safeAdd(getReserve(token, user), addReserve)); } function addBalanceSubReserve(address token, address user, uint256 addBalance, uint256 subReserve) onlyFuturesContract returns (bool) { if (!futuresContractAllowed(msg.sender, user)) throw; updateBalanceAndReserve(token, user, safeAdd(balanceOf(token, user), addBalance), safeSub(getReserve(token, user), subReserve)); } function subBalanceSubReserve(address token, address user, uint256 subBalance, uint256 subReserve) onlyFuturesContract returns (bool) { if (!futuresContractAllowed(msg.sender, user)) throw; updateBalanceAndReserve(token, user, safeSub(balanceOf(token, user), subBalance), safeSub(getReserve(token, user), subReserve)); } // Returns the available balance of a specific token for a specific user function availableBalanceOf(address token, address user) view returns (uint256) { return safeSub(balanceOf(token, user), getReserve(token, user)); } // Returns the inactivity release perios function getInactivityReleasePeriod() view returns (uint256) { return inactivityReleasePeriod; } // Increases the user balance function addBalance(address token, address user, uint256 amount) private { updateBalance(token, user, safeAdd(balanceOf(token, user), amount)); } // Decreases user balance function subBalance(address token, address user, uint256 amount) private { if (availableBalanceOf(token, user) < amount) throw; updateBalance(token, user, safeSub(balanceOf(token, user), amount)); } // Deposit ETH to contract function deposit() payable { //tokens[address(0)][msg.sender] = safeAdd(tokens[address(0)][msg.sender], msg.value); // adds the deposited amount to user balance addBalance(address(0), msg.sender, msg.value); // adds the deposited amount to user balance if (userFirstDeposits[msg.sender] == 0) userFirstDeposits[msg.sender] = block.number; lastActiveTransaction[msg.sender] = block.number; // sets the last activity block for the user emit Deposit(address(0), msg.sender, msg.value, balanceOf(address(0), msg.sender)); // fires the deposit event } // Deposit token to contract function depositToken(address token, uint128 amount) { //tokens[token][msg.sender] = safeAdd(tokens[token][msg.sender], amount); // adds the deposited amount to user balance //if (amount != uint128(amount) || safeAdd(amount, balanceOf(token, msg.sender)) != uint128(amount)) throw; addBalance(token, msg.sender, amount); // adds the deposited amount to user balance if (userFirstDeposits[msg.sender] == 0) userFirstDeposits[msg.sender] = block.number; lastActiveTransaction[msg.sender] = block.number; // sets the last activity block for the user if (!Token(token).transferFrom(msg.sender, this, amount)) throw; // attempts to transfer the token to this contract, if fails throws an error emit Deposit(token, msg.sender, amount, balanceOf(token, msg.sender)); // fires the deposit event } function withdraw(address token, uint256 amount) returns (bool success) { //if (safeSub(block.number, lastActiveTransaction[msg.sender]) < inactivityReleasePeriod) throw; // checks if the inactivity period has passed //if (tokens[token][msg.sender] < amount) throw; // checks that user has enough balance if (availableBalanceOf(token, msg.sender) < amount) throw; //tokens[token][msg.sender] = safeSub(tokens[token][msg.sender], amount); subBalance(token, msg.sender, amount); // subtracts the withdrawed amount from user balance if (token == address(0)) { // checks if withdrawal is a token or ETH, ETH has address 0x00000... if (!msg.sender.send(amount)) throw; // send ETH } else { if (!Token(token).transfer(msg.sender, amount)) throw; // Send token } emit Withdraw(token, msg.sender, amount, balanceOf(token, msg.sender), 0); // fires the Withdraw event } function userAllowFuturesContract(address futuresContract) { if (!futuresContracts[futuresContract]) throw; userAllowedFuturesContracts[msg.sender][futuresContract] = true; } // Withdrawal function used by the server to execute withdrawals function adminWithdraw( address token, // the address of the token to be withdrawn uint256 amount, // the amount to be withdrawn address user, // address of the user uint256 nonce, // nonce to make the request unique uint8 v, // part of user signature bytes32 r, // part of user signature bytes32 s, // part of user signature uint256 feeWithdrawal // the transaction gas fee that will be deducted from the user balance ) onlyAdmin returns (bool success) { bytes32 hash = keccak256(this, token, amount, user, nonce); // creates the hash for the withdrawal request if (withdrawn[hash]) throw; // checks if the withdrawal was already executed, if true, throws an error withdrawn[hash] = true; // sets the withdrawal as executed if (ecrecover(keccak256("\x19Ethereum Signed Message:\n32", hash), v, r, s) != user) throw; // checks that the provided signature is valid if (feeWithdrawal > 50 finney) feeWithdrawal = 50 finney; // checks that the gas fee is not higher than 0.05 ETH //if (tokens[token][user] < amount) throw; // checks that user has enough balance if (availableBalanceOf(token, user) < amount) throw; // checks that user has enough balance //tokens[token][user] = safeSub(tokens[token][user], amount); // subtracts the withdrawal amount from the user balance subBalance(token, user, amount); // subtracts the withdrawal amount from the user balance //tokens[address(0)][user] = safeSub(tokens[address(0x0)][user], feeWithdrawal); // subtracts the gas fee from the user ETH balance subBalance(address(0), user, feeWithdrawal); // subtracts the gas fee from the user ETH balance //tokens[address(0)][feeAccount] = safeAdd(tokens[address(0)][feeAccount], feeWithdrawal); // moves the gas fee to the feeAccount addBalance(address(0), feeAccount, feeWithdrawal); // moves the gas fee to the feeAccount if (token == address(0)) { // checks if the withdrawal is in ETH or Tokens if (!user.send(amount)) throw; // sends ETH } else { if (!Token(token).transfer(user, amount)) throw; // sends tokens } lastActiveTransaction[user] = block.number; // sets last user activity block emit Withdraw(token, user, amount, balanceOf(token, user), feeWithdrawal); // fires the withdraw event } function batchAdminWithdraw( address[] token, // the address of the token to be withdrawn uint256[] amount, // the amount to be withdrawn address[] user, // address of the user uint256[] nonce, // nonce to make the request unique uint8[] v, // part of user signature bytes32[] r, // part of user signature bytes32[] s, // part of user signature uint256[] feeWithdrawal // the transaction gas fee that will be deducted from the user balance ) onlyAdmin { for (uint i = 0; i < amount.length; i++) { adminWithdraw( token[i], amount[i], user[i], nonce[i], v[i], r[i], s[i], feeWithdrawal[i] ); } } function getMakerTakerBalances(address token, address maker, address taker) view returns (uint256[4]) { return [ balanceOf(token, maker), balanceOf(token, taker), getReserve(token, maker), getReserve(token, taker) ]; } // Structure that holds order values, used inside the trade() function struct OrderPair { uint256 makerAmountBuy; // amount being bought by the maker uint256 makerAmountSell; // amount being sold by the maker uint256 makerNonce; // maker order nonce, makes the order unique uint256 takerAmountBuy; // amount being bought by the taker uint256 takerAmountSell; // amount being sold by the taker uint256 takerNonce; // taker order nonce uint256 takerGasFee; // taker gas fee, taker pays the gas uint256 takerIsBuying; // true/false taker is the buyer address makerTokenBuy; // token bought by the maker address makerTokenSell; // token sold by the maker address maker; // address of the maker address takerTokenBuy; // token bought by the taker address takerTokenSell; // token sold by the taker address taker; // address of the taker bytes32 makerOrderHash; // hash of the maker order bytes32 takerOrderHash; // has of the taker order } // Structure that holds trade values, used inside the trade() function struct TradeValues { uint256 qty; // amount to be trade uint256 invQty; // amount to be traded in the opposite token uint256 makerAmountTaken; // final amount taken by the maker uint256 takerAmountTaken; // final amount taken by the taker } // Trades balances between user accounts function trade( uint8[2] v, bytes32[4] rs, uint256[8] tradeValues, address[6] tradeAddresses ) onlyAdmin returns (uint filledTakerTokenAmount) { /* tradeValues [0] makerAmountBuy [1] makerAmountSell [2] makerNonce [3] takerAmountBuy [4] takerAmountSell [5] takerNonce [6] takerGasFee [7] takerIsBuying tradeAddresses [0] makerTokenBuy [1] makerTokenSell [2] maker [3] takerTokenBuy [4] takerTokenSell [5] taker */ OrderPair memory t = OrderPair({ makerAmountBuy : tradeValues[0], makerAmountSell : tradeValues[1], makerNonce : tradeValues[2], takerAmountBuy : tradeValues[3], takerAmountSell : tradeValues[4], takerNonce : tradeValues[5], takerGasFee : tradeValues[6], takerIsBuying : tradeValues[7], makerTokenBuy : tradeAddresses[0], makerTokenSell : tradeAddresses[1], maker : tradeAddresses[2], takerTokenBuy : tradeAddresses[3], takerTokenSell : tradeAddresses[4], taker : tradeAddresses[5], // tokenBuy amountBuy tokenSell amountSell nonce user makerOrderHash : keccak256(this, tradeAddresses[0], tradeValues[0], tradeAddresses[1], tradeValues[1], tradeValues[2], tradeAddresses[2]), takerOrderHash : keccak256(this, tradeAddresses[3], tradeValues[3], tradeAddresses[4], tradeValues[4], tradeValues[5], tradeAddresses[5]) }); // Checks the signature for the maker order if (ecrecover(keccak256("\x19Ethereum Signed Message:\n32", t.makerOrderHash), v[0], rs[0], rs[1]) != t.maker) { emit LogError(uint8(Errors.INVLID_SIGNATURE), t.makerOrderHash, t.takerOrderHash); return 0; } // Checks the signature for the taker order if (ecrecover(keccak256("\x19Ethereum Signed Message:\n32", t.takerOrderHash), v[1], rs[2], rs[3]) != t.taker) { emit LogError(uint8(Errors.INVLID_SIGNATURE), t.makerOrderHash, t.takerOrderHash); return 0; } // Checks that orders trade the right tokens if (t.makerTokenBuy != t.takerTokenSell || t.makerTokenSell != t.takerTokenBuy) { emit LogError(uint8(Errors.TOKENS_DONT_MATCH), t.makerOrderHash, t.takerOrderHash); return 0; } // tokens don't match // Cheks that gas fee is not higher than 10% if (t.takerGasFee > 100 finney) { emit LogError(uint8(Errors.GAS_TOO_HIGH), t.makerOrderHash, t.takerOrderHash); return 0; } // takerGasFee too high // Checks that the prices match. // Taker always pays the maker price. This part checks that the taker price is as good or better than the maker price if (!( (t.takerIsBuying == 0 && safeMul(t.makerAmountSell, 1 ether) / t.makerAmountBuy >= safeMul(t.takerAmountBuy, 1 ether) / t.takerAmountSell) || (t.takerIsBuying > 0 && safeMul(t.makerAmountBuy, 1 ether) / t.makerAmountSell <= safeMul(t.takerAmountSell, 1 ether) / t.takerAmountBuy) )) { emit LogError(uint8(Errors.INVLID_PRICE), t.makerOrderHash, t.takerOrderHash); return 0; // prices don't match } // Initializing trade values structure TradeValues memory tv = TradeValues({ qty : 0, invQty : 0, makerAmountTaken : 0, takerAmountTaken : 0 }); // maker buy, taker sell if (t.takerIsBuying == 0) { // traded quantity is the smallest quantity between the maker and the taker, takes into account amounts already filled on the orders tv.qty = min(safeSub(t.makerAmountBuy, orderFills[t.makerOrderHash]), safeSub(t.takerAmountSell, safeMul(orderFills[t.takerOrderHash], t.takerAmountSell) / t.takerAmountBuy)); if (tv.qty == 0) { // order was already filled emit LogError(uint8(Errors.ORDER_ALREADY_FILLED), t.makerOrderHash, t.takerOrderHash); return 0; } // the traded quantity in opposite token terms tv.invQty = safeMul(tv.qty, t.makerAmountSell) / t.makerAmountBuy; // take fee from Token balance tv.makerAmountTaken = safeSub(tv.qty, safeMul(tv.qty, makerFee) / (1 ether)); // net amount received by maker, excludes maker fee //tokens[t.makerTokenBuy][feeAccount] = safeAdd(tokens[t.makerTokenBuy][feeAccount], safeMul(tv.qty, makerFee) / (1 ether)); // add maker fee to feeAccount addBalance(t.makerTokenBuy, feeAccount, safeMul(tv.qty, makerFee) / (1 ether)); // add maker fee to feeAccount // take fee from Token balance tv.takerAmountTaken = safeSub(safeSub(tv.invQty, safeMul(tv.invQty, takerFee) / (1 ether)), safeMul(tv.invQty, t.takerGasFee) / (1 ether)); // amount taken from taker minus taker fee //tokens[t.takerTokenBuy][feeAccount] = safeAdd(tokens[t.takerTokenBuy][feeAccount], safeAdd(safeMul(tv.invQty, takerFee) / (1 ether), safeMul(tv.invQty, t.takerGasFee) / (1 ether))); // add taker fee to feeAccount addBalance(t.takerTokenBuy, feeAccount, safeAdd(safeMul(tv.invQty, takerFee) / (1 ether), safeMul(tv.invQty, t.takerGasFee) / (1 ether))); // add taker fee to feeAccount //tokens[t.makerTokenSell][t.maker] = safeSub(tokens[t.makerTokenSell][t.maker], tv.invQty); // subtract sold token amount from maker balance subBalance(t.makerTokenSell, t.maker, tv.invQty); // subtract sold token amount from maker balance //tokens[t.makerTokenBuy][t.maker] = safeAdd(tokens[t.makerTokenBuy][t.maker], tv.makerAmountTaken); // add bought token amount to maker addBalance(t.makerTokenBuy, t.maker, tv.makerAmountTaken); // add bought token amount to maker //tokens[t.makerTokenBuy][tv.makerReferrer] = safeAdd(tokens[t.makerTokenBuy][tv.makerReferrer], safeMul(tv.qty, makerAffiliateFee) / (1 ether)); // add affiliate commission to maker affiliate balance //tokens[t.takerTokenSell][t.taker] = safeSub(tokens[t.takerTokenSell][t.taker], tv.qty); // subtract the sold token amount from taker subBalance(t.takerTokenSell, t.taker, tv.qty); // subtract the sold token amount from taker //tokens[t.takerTokenBuy][t.taker] = safeAdd(tokens[t.takerTokenBuy][t.taker], tv.takerAmountTaken); // amount received by taker, excludes taker fee //tokens[t.takerTokenBuy][tv.takerReferrer] = safeAdd(tokens[t.takerTokenBuy][tv.takerReferrer], safeMul(tv.invQty, takerAffiliateFee) / (1 ether)); // add affiliate commission to taker affiliate balance addBalance(t.takerTokenBuy, t.taker, tv.takerAmountTaken); // amount received by taker, excludes taker fee orderFills[t.makerOrderHash] = safeAdd(orderFills[t.makerOrderHash], tv.qty); // increase the maker order filled amount orderFills[t.takerOrderHash] = safeAdd(orderFills[t.takerOrderHash], safeMul(tv.qty, t.takerAmountBuy) / t.takerAmountSell); // increase the taker order filled amount lastActiveTransaction[t.maker] = block.number; // set last activity block number for maker lastActiveTransaction[t.taker] = block.number; // set last activity block number for taker // fire Trade event emit Trade( t.takerTokenBuy, tv.qty, t.takerTokenSell, tv.invQty, t.maker, t.taker, makerFee, takerFee, tv.makerAmountTaken , tv.takerAmountTaken, t.makerOrderHash, t.takerOrderHash ); return tv.qty; } // maker sell, taker buy else { // traded quantity is the smallest quantity between the maker and the taker, takes into account amounts already filled on the orders tv.qty = min(safeSub(t.makerAmountSell, safeMul(orderFills[t.makerOrderHash], t.makerAmountSell) / t.makerAmountBuy), safeSub(t.takerAmountBuy, orderFills[t.takerOrderHash])); if (tv.qty == 0) { // order was already filled emit LogError(uint8(Errors.ORDER_ALREADY_FILLED), t.makerOrderHash, t.takerOrderHash); return 0; } // the traded quantity in opposite token terms tv.invQty = safeMul(tv.qty, t.makerAmountBuy) / t.makerAmountSell; // take fee from ETH balance tv.makerAmountTaken = safeSub(tv.invQty, safeMul(tv.invQty, makerFee) / (1 ether)); // net amount received by maker, excludes maker fee //tokens[t.makerTokenBuy][feeAccount] = safeAdd(tokens[t.makerTokenBuy][feeAccount], safeMul(tv.invQty, makerFee) / (1 ether)); // add maker fee to feeAccount addBalance(t.makerTokenBuy, feeAccount, safeMul(tv.invQty, makerFee) / (1 ether)); // add maker fee to feeAccount // process fees for taker // take fee from ETH balance tv.takerAmountTaken = safeSub(safeSub(tv.qty, safeMul(tv.qty, takerFee) / (1 ether)), safeMul(tv.qty, t.takerGasFee) / (1 ether)); // amount taken from taker minus taker fee //tokens[t.takerTokenBuy][feeAccount] = safeAdd(tokens[t.takerTokenBuy][feeAccount], safeAdd(safeMul(tv.qty, takerFee) / (1 ether), safeMul(tv.qty, t.takerGasFee) / (1 ether))); // add taker fee to feeAccount addBalance(t.takerTokenBuy, feeAccount, safeAdd(safeMul(tv.qty, takerFee) / (1 ether), safeMul(tv.qty, t.takerGasFee) / (1 ether))); // add taker fee to feeAccount //tokens[t.makerTokenSell][t.maker] = safeSub(tokens[t.makerTokenSell][t.maker], tv.qty); // subtract sold token amount from maker balance subBalance(t.makerTokenSell, t.maker, tv.qty); // subtract sold token amount from maker balance //tv.makerAmountTaken = safeSub(tv.invQty, safeMul(tv.invQty, makerFee) / (1 ether)); // net amount received by maker, excludes maker fee //tokens[t.makerTokenBuy][t.maker] = safeAdd(tokens[t.makerTokenBuy][t.maker], tv.makerAmountTaken); // add bought token amount to maker addBalance(t.makerTokenBuy, t.maker, tv.makerAmountTaken); // add bought token amount to maker //tokens[t.makerTokenBuy][tv.makerReferrer] = safeAdd(tokens[t.makerTokenBuy][tv.makerReferrer], safeMul(tv.invQty, makerAffiliateFee) / (1 ether)); // add affiliate commission to maker affiliate balance //tokens[t.takerTokenSell][t.taker] = safeSub(tokens[t.takerTokenSell][t.taker], tv.invQty); // subtract the sold token amount from taker subBalance(t.takerTokenSell, t.taker, tv.invQty); //tv.takerAmountTaken = safeSub(safeSub(tv.qty, safeMul(tv.qty, takerFee) / (1 ether)), safeMul(tv.qty, t.takerGasFee) / (1 ether)); // amount taken from taker minus taker fee //tokens[t.takerTokenBuy][t.taker] = safeAdd(tokens[t.takerTokenBuy][t.taker], tv.takerAmountTaken); // amount received by taker, excludes taker fee addBalance(t.takerTokenBuy, t.taker, tv.takerAmountTaken); // amount received by taker, excludes taker fee //tokens[t.takerTokenBuy][tv.takerReferrer] = safeAdd(tokens[t.takerTokenBuy][tv.takerReferrer], safeMul(tv.qty, takerAffiliateFee) / (1 ether)); // add affiliate commission to taker affiliate balance //tokens[t.makerTokenBuy][feeAccount] = safeAdd(tokens[t.makerTokenBuy][feeAccount], safeMul(tv.invQty, safeSub(makerFee, makerAffiliateFee)) / (1 ether)); // add maker fee excluding affiliate commission to feeAccount //tokens[t.takerTokenBuy][feeAccount] = safeAdd(tokens[t.takerTokenBuy][feeAccount], safeAdd(safeMul(tv.qty, safeSub(takerFee, takerAffiliateFee)) / (1 ether), safeMul(tv.qty, t.takerGasFee) / (1 ether))); // add taker fee excluding affiliate commission to feeAccount orderFills[t.makerOrderHash] = safeAdd(orderFills[t.makerOrderHash], tv.invQty); // increase the maker order filled amount orderFills[t.takerOrderHash] = safeAdd(orderFills[t.takerOrderHash], tv.qty); // increase the taker order filled amount lastActiveTransaction[t.maker] = block.number; // set last activity block number for maker lastActiveTransaction[t.taker] = block.number; // set last activity block number for taker // fire Trade event emit Trade( t.takerTokenBuy, tv.qty, t.takerTokenSell, tv.invQty, t.maker, t.taker, makerFee, takerFee, tv.makerAmountTaken , tv.takerAmountTaken, t.makerOrderHash, t.takerOrderHash ); return tv.qty; } } // Executes multiple trades in one transaction, saves gas fees function batchOrderTrade( uint8[2][] v, bytes32[4][] rs, uint256[8][] tradeValues, address[6][] tradeAddresses ) onlyAdmin { for (uint i = 0; i < tradeAddresses.length; i++) { trade( v[i], rs[i], tradeValues[i], tradeAddresses[i] ); } } // Cancels order by setting amount filled to toal order amount function cancelOrder( /* [0] orderV [1] cancelV */ uint8[2] v, /* [0] orderR [1] orderS [2] cancelR [3] cancelS */ bytes32[4] rs, /* [0] orderAmountBuy [1] orderAmountSell [2] orderNonce [3] cancelNonce [4] cancelFee */ uint256[5] cancelValues, /* [0] orderTokenBuy [1] orderTokenSell [2] orderUser [3] cancelUser */ address[4] cancelAddresses ) onlyAdmin { // Order values should be valid and signed by order owner bytes32 orderHash = keccak256( this, cancelAddresses[0], cancelValues[0], cancelAddresses[1], cancelValues[1], cancelValues[2], cancelAddresses[2] ); require(ecrecover(keccak256("\x19Ethereum Signed Message:\n32", orderHash), v[0], rs[0], rs[1]) == cancelAddresses[2]); // Cancel action should be signed by order owner bytes32 cancelHash = keccak256(this, orderHash, cancelAddresses[3], cancelValues[3]); require(ecrecover(keccak256("\x19Ethereum Signed Message:\n32", cancelHash), v[1], rs[2], rs[3]) == cancelAddresses[3]); // Order owner should be the same as cancel's initiator require(cancelAddresses[2] == cancelAddresses[3]); // Do not allow to cancel already canceled or filled orders require(orderFills[orderHash] != cancelValues[0]); // Cancel gas fee cannot exceed 0.05 ETh if (cancelValues[4] > 50 finney) { cancelValues[4] = 50 finney; } // Take cancel fee // This operation throws an error if fee amount is greater than the user balance //tokens[address(0)][cancelAddresses[3]] = safeSub(tokens[address(0)][cancelAddresses[3]], cancelValues[4]); subBalance(address(0), cancelAddresses[3], cancelValues[4]); // Cancel order by setting amount filled to total order value, i.e. making the order filled orderFills[orderHash] = cancelValues[0]; // Fire cancel order event emit CancelOrder(cancelHash, orderHash, cancelAddresses[3], cancelAddresses[1], cancelValues[1], cancelValues[4]); } // Returns the smaller of two values function min(uint a, uint b) private pure returns (uint) { return a < b ? a : b; } }
Changes the owner of the contract
function setOwner(address newOwner) onlyOwner { SetOwner(owner, newOwner); owner = newOwner; }
2,554,717
./partial_match/1/0x811614dAAc8f37EDf25a86F3bDE774B1e886ccF5/sources/ArmorToken.sol
Queries the balance of `_owner` at a specific `_blockNumber` _owner The address from which the balance will be retrieved _blockNumber The block number when the balance is queried return The balance at `_blockNumber` These next few lines are used when the balance of the token is requested before a check point was ever created for this token, it requires that the `parentToken.balanceOfAt` be queried at the genesis block for that token as this contains initial balance of this token This will return the expected balance during normal situations
function balanceOfAt(address _owner, uint _blockNumber) public view returns (uint) { if ((balances[_owner].length == 0) || (balances[_owner][0].fromBlock > _blockNumber)) { return 0; return getValueAt(balances[_owner], _blockNumber); } }
4,325,789
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". /// @dev Based on OpenZeppelin's Ownable. contract Ownable { address public owner; address public newOwnerCandidate; event OwnershipRequested(address indexed _by, address indexed _to); event OwnershipTransferred(address indexed _from, address indexed _to); /// @dev Constructor sets the original `owner` of the contract to the sender account. function Ownable() public { owner = msg.sender; } /// @dev Reverts if called by any account other than the owner. modifier onlyOwner() { require(msg.sender == owner); _; } modifier onlyOwnerCandidate() { require(msg.sender == newOwnerCandidate); _; } /// @dev Proposes to transfer control of the contract to a newOwnerCandidate. /// @param _newOwnerCandidate address The address to transfer ownership to. function requestOwnershipTransfer(address _newOwnerCandidate) external onlyOwner { require(_newOwnerCandidate != address(0)); newOwnerCandidate = _newOwnerCandidate; OwnershipRequested(msg.sender, newOwnerCandidate); } /// @dev Accept ownership transfer. This method needs to be called by the perviously proposed owner. function acceptOwnership() external onlyOwnerCandidate { address previousOwner = owner; owner = newOwnerCandidate; newOwnerCandidate = address(0); OwnershipTransferred(previousOwner, owner); } } /// @title Math operations with safety checks library SafeMath { function mul(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a * b; require(a == 0 || c / a == b); return c; } function div(uint256 a, uint256 b) internal pure returns (uint256) { // require(b > 0); // Solidity automatically throws when dividing by 0 uint256 c = a / b; // require(a == b * c + a % b); // There is no case in which this doesn't hold return c; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a); return a - b; } function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a); return c; } function max64(uint64 a, uint64 b) internal pure returns (uint64) { return a >= b ? a : b; } function min64(uint64 a, uint64 b) internal pure returns (uint64) { return a < b ? a : b; } function max256(uint256 a, uint256 b) internal pure returns (uint256) { return a >= b ? a : b; } function min256(uint256 a, uint256 b) internal pure returns (uint256) { return a < b ? a : b; } function toPower2(uint256 a) internal pure returns (uint256) { return mul(a, a); } function sqrt(uint256 a) internal pure returns (uint256) { uint256 c = (a + 1) / 2; uint256 b = a; while (c < b) { b = c; c = (a / c + c) / 2; } return b; } } /// @title ERC Token Standard #20 Interface (https://github.com/ethereum/EIPs/issues/20) contract ERC20 { uint public totalSupply; function balanceOf(address _owner) constant public returns (uint balance); function transfer(address _to, uint _value) public returns (bool success); function transferFrom(address _from, address _to, uint _value) public returns (bool success); function approve(address _spender, uint _value) public returns (bool success); function allowance(address _owner, address _spender) public constant returns (uint remaining); event Transfer(address indexed from, address indexed to, uint value); event Approval(address indexed owner, address indexed spender, uint value); } /// @title ERC Token Standard #677 Interface (https://github.com/ethereum/EIPs/issues/677) contract ERC677 is ERC20 { function transferAndCall(address to, uint value, bytes data) public returns (bool ok); event TransferAndCall(address indexed from, address indexed to, uint value, bytes data); } /// @title ERC223Receiver Interface /// @dev Based on the specs form: https://github.com/ethereum/EIPs/issues/223 contract ERC223Receiver { function tokenFallback(address _sender, uint _value, bytes _data) external returns (bool ok); } /// @title Basic ERC20 token contract implementation. /// @dev Based on OpenZeppelin's StandardToken. contract BasicToken is ERC20 { using SafeMath for uint256; uint256 public totalSupply; mapping (address => mapping (address => uint256)) allowed; mapping (address => uint256) balances; event Approval(address indexed owner, address indexed spender, uint256 value); event Transfer(address indexed from, address indexed to, uint256 value); /// @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender. /// @param _spender address The address which will spend the funds. /// @param _value uint256 The amount of tokens to be spent. function approve(address _spender, uint256 _value) public returns (bool) { // https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20.md#approve (see NOTE) if ((_value != 0) && (allowed[msg.sender][_spender] != 0)) { revert(); } 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 uint256 specifying the amount of tokens still available for the spender. function allowance(address _owner, address _spender) constant public returns (uint256 remaining) { return allowed[_owner][_spender]; } /// @dev Gets the balance of the specified address. /// @param _owner address The address to query the the balance of. /// @return uint256 representing the amount owned by the passed address. function balanceOf(address _owner) constant public returns (uint256 balance) { return balances[_owner]; } /// @dev Transfer token to a specified address. /// @param _to address The address to transfer to. /// @param _value uint256 The amount to be transferred. function transfer(address _to, uint256 _value) public returns (bool) { require(_to != address(0)); balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); Transfer(msg.sender, _to, _value); return true; } /// @dev 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)); var _allowance = allowed[_from][msg.sender]; balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); allowed[_from][msg.sender] = _allowance.sub(_value); Transfer(_from, _to, _value); return true; } } /// @title Standard677Token implentation, base on https://github.com/ethereum/EIPs/issues/677 contract Standard677Token is ERC677, BasicToken { /// @dev ERC223 safe token transfer from one address to another /// @param _to address the address which you want to transfer to. /// @param _value uint256 the amount of tokens to be transferred. /// @param _data bytes data that can be attached to the token transation function transferAndCall(address _to, uint _value, bytes _data) public returns (bool) { require(super.transfer(_to, _value)); // do a normal token transfer TransferAndCall(msg.sender, _to, _value, _data); //filtering if the target is a contract with bytecode inside it if (isContract(_to)) return contractFallback(_to, _value, _data); return true; } /// @dev called when transaction target is a contract /// @param _to address the address which you want to transfer to. /// @param _value uint256 the amount of tokens to be transferred. /// @param _data bytes data that can be attached to the token transation function contractFallback(address _to, uint _value, bytes _data) private returns (bool) { ERC223Receiver receiver = ERC223Receiver(_to); require(receiver.tokenFallback(msg.sender, _value, _data)); return true; } /// @dev check if the address is contract /// assemble the given address bytecode. If bytecode exists then the _addr is a contract. /// @param _addr address the address to check function isContract(address _addr) private constant returns (bool is_contract) { // retrieve the size of the code on target address, this needs assembly uint length; assembly { length := extcodesize(_addr) } return length > 0; } } /// @title Token holder contract. contract TokenHolder is Ownable { /// @dev Allow the owner to transfer out any accidentally sent ERC20 tokens. /// @param _tokenAddress address The address of the ERC20 contract. /// @param _amount uint256 The amount of tokens to be transferred. function transferAnyERC20Token(address _tokenAddress, uint256 _amount) public onlyOwner returns (bool success) { return ERC20(_tokenAddress).transfer(owner, _amount); } } /// @title Colu Local Network contract. /// @author Tal Beja. contract ColuLocalNetwork is Ownable, Standard677Token, TokenHolder { using SafeMath for uint256; string public constant name = "Colu Local Network"; string public constant symbol = "CLN"; // Using same decimals value as ETH (makes ETH-CLN conversion much easier). uint8 public constant decimals = 18; // States whether token transfers is allowed or not. // Used during token sale. bool public isTransferable = false; event TokensTransferable(); modifier transferable() { require(msg.sender == owner || isTransferable); _; } /// @dev Creates all tokens and gives them to the owner. function ColuLocalNetwork(uint256 _totalSupply) public { totalSupply = _totalSupply; balances[msg.sender] = totalSupply; } /// @dev start transferable mode. function makeTokensTransferable() external onlyOwner { if (isTransferable) { return; } isTransferable = true; TokensTransferable(); } /// @dev Same ERC20 behavior, but reverts if not transferable. /// @param _spender address The address which will spend the funds. /// @param _value uint256 The amount of tokens to be spent. function approve(address _spender, uint256 _value) public transferable returns (bool) { return super.approve(_spender, _value); } /// @dev Same ERC20 behavior, but reverts if not transferable. /// @param _to address The address to transfer to. /// @param _value uint256 The amount to be transferred. function transfer(address _to, uint256 _value) public transferable returns (bool) { return super.transfer(_to, _value); } /// @dev Same ERC20 behavior, but reverts if not transferable. /// @param _from address The address to send tokens from. /// @param _to address The address to transfer to. /// @param _value uint256 the amount of tokens to be transferred. function transferFrom(address _from, address _to, uint256 _value) public transferable returns (bool) { return super.transferFrom(_from, _to, _value); } /// @dev Same ERC677 behavior, but reverts if not transferable. /// @param _to address The address to transfer to. /// @param _value uint256 The amount to be transferred. /// @param _data bytes data to send to receiver if it is a contract. function transferAndCall(address _to, uint _value, bytes _data) public transferable returns (bool success) { return super.transferAndCall(_to, _value, _data); } } /// @title Standard ERC223 Token Receiver implementing tokenFallback function and tokenPayable modifier contract Standard223Receiver is ERC223Receiver { Tkn tkn; struct Tkn { address addr; address sender; // the transaction caller uint256 value; } bool __isTokenFallback; modifier tokenPayable { require(__isTokenFallback); _; } /// @dev Called when the receiver of transfer is contract /// @param _sender address the address of tokens sender /// @param _value uint256 the amount of tokens to be transferred. /// @param _data bytes data that can be attached to the token transation function tokenFallback(address _sender, uint _value, bytes _data) external returns (bool ok) { if (!supportsToken(msg.sender)) { return false; } // Problem: This will do a sstore which is expensive gas wise. Find a way to keep it in memory. // Solution: Remove the the data tkn = Tkn(msg.sender, _sender, _value); __isTokenFallback = true; if (!address(this).delegatecall(_data)) { __isTokenFallback = false; return false; } // avoid doing an overwrite to .token, which would be more expensive // makes accessing .tkn values outside tokenPayable functions unsafe __isTokenFallback = false; return true; } function supportsToken(address token) public constant returns (bool); } /// @title TokenOwnable /// @dev The TokenOwnable contract adds a onlyTokenOwner modifier as a tokenReceiver with ownable addaptation contract TokenOwnable is Standard223Receiver, Ownable { /// @dev Reverts if called by any account other than the owner for token sending. modifier onlyTokenOwner() { require(tkn.sender == owner); _; } } /// @title Vesting trustee contract for Colu Local Network. /// @dev This Contract can't be TokenHolder, since it will allow its owner to drain its vested tokens. /// @dev This means that any token sent to it different than ColuLocalNetwork is basicly stucked here forever. /// @dev ColuLocalNetwork that sent here (by mistake) can withdrawn using the grant method. contract VestingTrustee is TokenOwnable { using SafeMath for uint256; // Colu Local Network contract. ColuLocalNetwork public cln; // Vesting grant for a speicifc holder. struct Grant { uint256 value; uint256 start; uint256 cliff; uint256 end; uint256 installmentLength; // In seconds. uint256 transferred; bool revokable; } // Holder to grant information mapping. mapping (address => Grant) public grants; // Total tokens vested. uint256 public totalVesting; event NewGrant(address indexed _from, address indexed _to, uint256 _value); event TokensUnlocked(address indexed _to, uint256 _value); event GrantRevoked(address indexed _holder, uint256 _refund); uint constant OK = 1; uint constant ERR_INVALID_VALUE = 10001; uint constant ERR_INVALID_VESTED = 10002; uint constant ERR_INVALID_TRANSFERABLE = 10003; event Error(address indexed sender, uint error); /// @dev Constructor that initializes the address of the Colu Local Network contract. /// @param _cln ColuLocalNetwork The address of the previously deployed Colu Local Network contract. function VestingTrustee(ColuLocalNetwork _cln) public { require(_cln != address(0)); cln = _cln; } /// @dev Allow only cln token to be tokenPayable /// @param token the token to check function supportsToken(address token) public constant returns (bool) { return (cln == token); } /// @dev Grant tokens to a specified address. /// @param _to address The holder address. /// @param _start uint256 The beginning of the vesting period (timestamp). /// @param _cliff uint256 When the first installment is made (timestamp). /// @param _end uint256 The end of the vesting period (timestamp). /// @param _installmentLength uint256 The length of each vesting installment (in seconds). /// @param _revokable bool Whether the grant is revokable or not. function grant(address _to, uint256 _start, uint256 _cliff, uint256 _end, uint256 _installmentLength, bool _revokable) external onlyTokenOwner tokenPayable { require(_to != address(0)); require(_to != address(this)); // Protect this contract from receiving a grant. uint256 value = tkn.value; require(value > 0); // Require that every holder can be granted tokens only once. require(grants[_to].value == 0); // Require for time ranges to be consistent and valid. require(_start <= _cliff && _cliff <= _end); // Require installment length to be valid and no longer than (end - start). require(_installmentLength > 0 && _installmentLength <= _end.sub(_start)); // Grant must not exceed the total amount of tokens currently available for vesting. require(totalVesting.add(value) <= cln.balanceOf(address(this))); // Assign a new grant. grants[_to] = Grant({ value: value, start: _start, cliff: _cliff, end: _end, installmentLength: _installmentLength, transferred: 0, revokable: _revokable }); // Since tokens have been granted, increase the total amount vested. totalVesting = totalVesting.add(value); NewGrant(msg.sender, _to, value); } /// @dev Grant tokens to a specified address. /// @param _to address The holder address. /// @param _value uint256 The amount of tokens to be granted. /// @param _start uint256 The beginning of the vesting period (timestamp). /// @param _cliff uint256 When the first installment is made (timestamp). /// @param _end uint256 The end of the vesting period (timestamp). /// @param _installmentLength uint256 The length of each vesting installment (in seconds). /// @param _revokable bool Whether the grant is revokable or not. function grant(address _to, uint256 _value, uint256 _start, uint256 _cliff, uint256 _end, uint256 _installmentLength, bool _revokable) external onlyOwner { require(_to != address(0)); require(_to != address(this)); // Protect this contract from receiving a grant. require(_value > 0); // Require that every holder can be granted tokens only once. require(grants[_to].value == 0); // Require for time ranges to be consistent and valid. require(_start <= _cliff && _cliff <= _end); // Require installment length to be valid and no longer than (end - start). require(_installmentLength > 0 && _installmentLength <= _end.sub(_start)); // Grant must not exceed the total amount of tokens currently available for vesting. require(totalVesting.add(_value) <= cln.balanceOf(address(this))); // Assign a new grant. grants[_to] = Grant({ value: _value, start: _start, cliff: _cliff, end: _end, installmentLength: _installmentLength, transferred: 0, revokable: _revokable }); // Since tokens have been granted, increase the total amount vested. totalVesting = totalVesting.add(_value); NewGrant(msg.sender, _to, _value); } /// @dev Revoke the grant of tokens of a specifed address. /// @dev Unlocked tokens will be sent to the grantee, the rest is transferred to the trustee's owner. /// @param _holder The address which will have its tokens revoked. function revoke(address _holder) public onlyOwner { Grant memory grant = grants[_holder]; // Grant must be revokable. require(grant.revokable); // Get the total amount of vested tokens, acccording to grant. uint256 vested = calculateVestedTokens(grant, now); // Calculate the untransferred vested tokens. uint256 transferable = vested.sub(grant.transferred); if (transferable > 0) { // Update transferred and total vesting amount, then transfer remaining vested funds to holder. grant.transferred = grant.transferred.add(transferable); totalVesting = totalVesting.sub(transferable); require(cln.transfer(_holder, transferable)); TokensUnlocked(_holder, transferable); } // Calculate amount of remaining tokens that can still be returned. uint256 refund = grant.value.sub(grant.transferred); // Remove the grant. delete grants[_holder]; // Update total vesting amount and transfer previously calculated tokens to owner. totalVesting = totalVesting.sub(refund); require(cln.transfer(msg.sender, refund)); GrantRevoked(_holder, refund); } /// @dev Calculate the amount of ready tokens of a holder. /// @param _holder address The address of the holder. /// @return a uint256 Representing a holder's total amount of vested tokens. function readyTokens(address _holder) public constant returns (uint256) { Grant memory grant = grants[_holder]; if (grant.value == 0) { return 0; } uint256 vested = calculateVestedTokens(grant, now); if (vested == 0) { return 0; } return vested.sub(grant.transferred); } /// @dev Calculate the total amount of vested tokens of a holder at a given time. /// @param _holder address The address of the holder. /// @param _time uint256 The specific time to calculate against. /// @return a uint256 Representing a holder's total amount of vested tokens. function vestedTokens(address _holder, uint256 _time) public constant returns (uint256) { Grant memory grant = grants[_holder]; if (grant.value == 0) { return 0; } return calculateVestedTokens(grant, _time); } /// @dev Calculate amount of vested tokens at a specifc time. /// @param _grant Grant The vesting grant. /// @param _time uint256 The time to be checked /// @return An uint256 Representing the amount of vested tokens of a specific grant. function calculateVestedTokens(Grant _grant, uint256 _time) private pure returns (uint256) { // If we're before the cliff, then nothing is vested. if (_time < _grant.cliff) { return 0; } // If we're after the end of the vesting period - everything is vested. if (_time >= _grant.end) { return _grant.value; } // Calculate amount of installments past until now. // // NOTE: result gets floored because of integer division. uint256 installmentsPast = _time.sub(_grant.start).div(_grant.installmentLength); // Calculate amount of days in entire vesting period. uint256 vestingDays = _grant.end.sub(_grant.start); // Calculate and return the number of tokens according to vesting days that have passed. return _grant.value.mul(installmentsPast.mul(_grant.installmentLength)).div(vestingDays); } /// @dev Unlock vested tokens and transfer them to the grantee. /// @return a uint The success or error code. function unlockVestedTokens() external returns (uint) { return unlockVestedTokens(msg.sender); } /// @dev Unlock vested tokens and transfer them to the grantee (helper function). /// @param _grantee address The address of the grantee. /// @return a uint The success or error code. function unlockVestedTokens(address _grantee) private returns (uint) { Grant storage grant = grants[_grantee]; // Make sure the grant has tokens available. if (grant.value == 0) { Error(_grantee, ERR_INVALID_VALUE); return ERR_INVALID_VALUE; } // Get the total amount of vested tokens, acccording to grant. uint256 vested = calculateVestedTokens(grant, now); if (vested == 0) { Error(_grantee, ERR_INVALID_VESTED); return ERR_INVALID_VESTED; } // Make sure the holder doesn't transfer more than what he already has. uint256 transferable = vested.sub(grant.transferred); if (transferable == 0) { Error(_grantee, ERR_INVALID_TRANSFERABLE); return ERR_INVALID_TRANSFERABLE; } // Update transferred and total vesting amount, then transfer remaining vested funds to holder. grant.transferred = grant.transferred.add(transferable); totalVesting = totalVesting.sub(transferable); require(cln.transfer(_grantee, transferable)); TokensUnlocked(_grantee, transferable); return OK; } /// @dev batchUnlockVestedTokens vested tokens and transfer them to the grantees. /// @param _grantees address[] The addresses of the grantees. /// @return a boo if success. function batchUnlockVestedTokens(address[] _grantees) external onlyOwner returns (bool success) { for (uint i = 0; i<_grantees.length; i++) { unlockVestedTokens(_grantees[i]); } return true; } /// @dev Allow the owner to transfer out any accidentally sent ERC20 tokens. /// @param _tokenAddress address The address of the ERC20 contract. /// @param _amount uint256 The amount of tokens to be transferred. function withdrawERC20(address _tokenAddress, uint256 _amount) public onlyOwner returns (bool success) { if (_tokenAddress == address(cln)) { // If the token is cln, allow to withdraw only non vested tokens. uint256 availableCLN = cln.balanceOf(this).sub(totalVesting); require(_amount <= availableCLN); } return ERC20(_tokenAddress).transfer(owner, _amount); } } /// @title Colu Local Network sale contract. /// @author Tal Beja. contract ColuLocalNetworkSale is Ownable, TokenHolder { using SafeMath for uint256; // External parties: // Colu Local Network contract. ColuLocalNetwork public cln; // Vesting contract for presale participants. VestingTrustee public trustee; // Received funds are forwarded to this address. address public fundingRecipient; // Post-TDE multisig addresses. address public communityPoolAddress; address public futureDevelopmentPoolAddress; address public stakeholdersPoolAddress; // Colu Local Network decimals. // Using same decimals value as ETH (makes ETH-CLN conversion much easier). // This is the same as in Colu Local Network contract. uint256 public constant TOKEN_DECIMALS = 10 ** 18; // Additional Lockup Allocation Pool uint256 public constant ALAP = 40701333592592592592614116; // Maximum number of tokens in circulation: 1.5 trillion. uint256 public constant MAX_TOKENS = 15 * 10 ** 8 * TOKEN_DECIMALS + ALAP; // Maximum tokens offered in the sale (35%) + ALAP. uint256 public constant MAX_TOKENS_SOLD = 525 * 10 ** 6 * TOKEN_DECIMALS + ALAP; // Maximum tokens offered in the presale (from the initial 35% offered tokens) + ALAP. uint256 public constant MAX_PRESALE_TOKENS_SOLD = 2625 * 10 ** 5 * TOKEN_DECIMALS + ALAP; // Tokens allocated for Community pool (30%). uint256 public constant COMMUNITY_POOL = 45 * 10 ** 7 * TOKEN_DECIMALS; // Tokens allocated for Future development pool (29%). uint256 public constant FUTURE_DEVELOPMENT_POOL = 435 * 10 ** 6 * TOKEN_DECIMALS; // Tokens allocated for Stakeholdes pool (6%). uint256 public constant STAKEHOLDERS_POOL = 9 * 10 ** 7 * TOKEN_DECIMALS; // CLN to ETH ratio. uint256 public constant CLN_PER_ETH = 8600; // Sale start, end blocks (time ranges) uint256 public constant SALE_DURATION = 4 days; uint256 public startTime; uint256 public endTime; // Amount of tokens sold until now in the sale. uint256 public tokensSold = 0; // Amount of tokens sold until now in the presale. uint256 public presaleTokensSold = 0; // Accumulated amount each participant has contributed so far in the sale (in WEI). mapping (address => uint256) public participationHistory; // Accumulated amount each participant have contributed so far in the presale. mapping (address => uint256) public participationPresaleHistory; // Maximum amount that each particular is allowed to contribute (in ETH-WEI). // Defaults to zero. Serving as a functional whitelist. mapping (address => uint256) public participationCaps; // Maximum amount ANYONE is currently allowed to contribute. Set to max uint256 so no limitation other than personal participationCaps. uint256 public hardParticipationCap = uint256(-1); // initialization of the contract, splitted from the constructor to avoid gas block limit. bool public initialized = false; // Vesting plan structure for presale struct VestingPlan { uint256 startOffset; uint256 cliffOffset; uint256 endOffset; uint256 installmentLength; uint8 alapPercent; } // Vesting plans for presale VestingPlan[] public vestingPlans; // Each token that is sent from the ColuLocalNetworkSale is considered as issued. event TokensIssued(address indexed to, uint256 tokens); /// @dev Reverts if called not before the sale. modifier onlyBeforeSale() { if (now >= startTime) { revert(); } _; } /// @dev Reverts if called not during the sale. modifier onlyDuringSale() { if (tokensSold >= MAX_TOKENS_SOLD || now < startTime || now >= endTime) { revert(); } _; } /// @dev Reverts if called before the sale ends. modifier onlyAfterSale() { if (!(tokensSold >= MAX_TOKENS_SOLD || now >= endTime)) { revert(); } _; } /// @dev Reverts if called before the sale is initialized. modifier notInitialized() { if (initialized) { revert(); } _; } /// @dev Reverts if called after the sale is initialized. modifier isInitialized() { if (!initialized) { revert(); } _; } /// @dev Constructor sets the sale addresses and start time. /// @param _owner address The address of this contract owner. /// @param _fundingRecipient address The address of the funding recipient. /// @param _communityPoolAddress address The address of the community pool. /// @param _futureDevelopmentPoolAddress address The address of the future development pool. /// @param _stakeholdersPoolAddress address The address of the team pool. /// @param _startTime uint256 The start time of the token sale. function ColuLocalNetworkSale(address _owner, address _fundingRecipient, address _communityPoolAddress, address _futureDevelopmentPoolAddress, address _stakeholdersPoolAddress, uint256 _startTime) public { require(_owner != address(0)); require(_fundingRecipient != address(0)); require(_communityPoolAddress != address(0)); require(_futureDevelopmentPoolAddress != address(0)); require(_stakeholdersPoolAddress != address(0)); require(_startTime > now); owner = _owner; fundingRecipient = _fundingRecipient; communityPoolAddress = _communityPoolAddress; futureDevelopmentPoolAddress = _futureDevelopmentPoolAddress; stakeholdersPoolAddress = _stakeholdersPoolAddress; startTime = _startTime; endTime = startTime + SALE_DURATION; } /// @dev Initialize the sale conditions. function initialize() public onlyOwner notInitialized { initialized = true; uint256 months = 1 years / 12; vestingPlans.push(VestingPlan(0, 0, 1, 1, 0)); vestingPlans.push(VestingPlan(0, 0, 6 * months, 1 * months, 4)); vestingPlans.push(VestingPlan(0, 0, 1 years, 1 * months, 12)); vestingPlans.push(VestingPlan(0, 0, 2 years, 1 * months, 26)); vestingPlans.push(VestingPlan(0, 0, 3 years, 1 * months, 35)); // Deploy new ColuLocalNetwork contract. cln = new ColuLocalNetwork(MAX_TOKENS); // Deploy new VestingTrustee contract. trustee = new VestingTrustee(cln); // allocate pool tokens: // Issue the remaining tokens to designated pools. require(transferTokens(communityPoolAddress, COMMUNITY_POOL)); // stakeholdersPoolAddress will create its own vesting trusts. require(transferTokens(stakeholdersPoolAddress, STAKEHOLDERS_POOL)); } /// @dev Allocate tokens to presale participant according to its vesting plan and invesment value. /// @param _recipient address The presale participant address to recieve the tokens. /// @param _etherValue uint256 The invesment value (in ETH). /// @param _vestingPlanIndex uint8 The vesting plan index. function presaleAllocation(address _recipient, uint256 _etherValue, uint8 _vestingPlanIndex) external onlyOwner onlyBeforeSale isInitialized { require(_recipient != address(0)); require(_vestingPlanIndex < vestingPlans.length); // Calculate plan and token amount. VestingPlan memory plan = vestingPlans[_vestingPlanIndex]; uint256 tokensAndALAPPerEth = CLN_PER_ETH.mul(SafeMath.add(100, plan.alapPercent)).div(100); uint256 tokensLeftInPreSale = MAX_PRESALE_TOKENS_SOLD.sub(presaleTokensSold); uint256 weiLeftInSale = tokensLeftInPreSale.div(tokensAndALAPPerEth); uint256 weiToParticipate = SafeMath.min256(_etherValue, weiLeftInSale); require(weiToParticipate > 0); participationPresaleHistory[msg.sender] = participationPresaleHistory[msg.sender].add(weiToParticipate); uint256 tokensToTransfer = weiToParticipate.mul(tokensAndALAPPerEth); presaleTokensSold = presaleTokensSold.add(tokensToTransfer); tokensSold = tokensSold.add(tokensToTransfer); // Transfer tokens to trustee and create grant. grant(_recipient, tokensToTransfer, startTime.add(plan.startOffset), startTime.add(plan.cliffOffset), startTime.add(plan.endOffset), plan.installmentLength, false); } /// @dev Add a list of participants to a capped participation tier. /// @param _participants address[] The list of participant addresses. /// @param _cap uint256 The cap amount (in ETH-WEI). function setParticipationCap(address[] _participants, uint256 _cap) external onlyOwner isInitialized { for (uint i = 0; i < _participants.length; i++) { participationCaps[_participants[i]] = _cap; } } /// @dev Set hard participation cap for all participants. /// @param _cap uint256 The hard cap amount. function setHardParticipationCap(uint256 _cap) external onlyOwner isInitialized { require(_cap > 0); hardParticipationCap = _cap; } /// @dev Fallback function that will delegate the request to participate(). function () external payable onlyDuringSale isInitialized { participate(msg.sender); } /// @dev Create and sell tokens to the caller. /// @param _recipient address The address of the recipient receiving the tokens. function participate(address _recipient) public payable onlyDuringSale isInitialized { require(_recipient != address(0)); // Enforce participation cap (in WEI received). uint256 weiAlreadyParticipated = participationHistory[_recipient]; uint256 participationCap = SafeMath.min256(participationCaps[_recipient], hardParticipationCap); uint256 cappedWeiReceived = SafeMath.min256(msg.value, participationCap.sub(weiAlreadyParticipated)); require(cappedWeiReceived > 0); // Accept funds and transfer to funding recipient. uint256 tokensLeftInSale = MAX_TOKENS_SOLD.sub(tokensSold); uint256 weiLeftInSale = tokensLeftInSale.div(CLN_PER_ETH); uint256 weiToParticipate = SafeMath.min256(cappedWeiReceived, weiLeftInSale); participationHistory[_recipient] = weiAlreadyParticipated.add(weiToParticipate); fundingRecipient.transfer(weiToParticipate); // Transfer tokens to recipient. uint256 tokensToTransfer = weiToParticipate.mul(CLN_PER_ETH); if (tokensLeftInSale.sub(tokensToTransfer) < CLN_PER_ETH) { // If purchase would cause less than CLN_PER_ETH tokens to be left then nobody could ever buy them. // So, gift them to the last buyer. tokensToTransfer = tokensLeftInSale; } tokensSold = tokensSold.add(tokensToTransfer); require(transferTokens(_recipient, tokensToTransfer)); // Partial refund if full participation not possible // e.g. due to cap being reached. uint256 refund = msg.value.sub(weiToParticipate); if (refund > 0) { msg.sender.transfer(refund); } } /// @dev Finalizes the token sale event: make future development pool grant (lockup) and make token transfarable. function finalize() external onlyAfterSale onlyOwner isInitialized { if (cln.isTransferable()) { revert(); } // Add unsold token to the future development pool grant (lockup). uint256 tokensLeftInSale = MAX_TOKENS_SOLD.sub(tokensSold); uint256 futureDevelopmentPool = FUTURE_DEVELOPMENT_POOL.add(tokensLeftInSale); // Future Development Pool is locked for 3 years. grant(futureDevelopmentPoolAddress, futureDevelopmentPool, startTime, startTime.add(3 years), startTime.add(3 years), 1 days, false); // Make tokens Transferable, end the sale!. cln.makeTokensTransferable(); } function grant(address _grantee, uint256 _amount, uint256 _start, uint256 _cliff, uint256 _end, uint256 _installmentLength, bool _revokable) private { // bytes4 grantSig = bytes4(keccak256("grant(address,uint256,uint256,uint256,uint256,bool)")); bytes4 grantSig = 0x5ee7e96d; // 6 arguments of size 32 uint256 argsSize = 6 * 32; // sig + arguments size uint256 dataSize = 4 + argsSize; bytes memory m_data = new bytes(dataSize); assembly { // Add the signature first to memory mstore(add(m_data, 0x20), grantSig) // Add the parameters mstore(add(m_data, 0x24), _grantee) mstore(add(m_data, 0x44), _start) mstore(add(m_data, 0x64), _cliff) mstore(add(m_data, 0x84), _end) mstore(add(m_data, 0xa4), _installmentLength) mstore(add(m_data, 0xc4), _revokable) } require(transferTokens(trustee, _amount, m_data)); } /// @dev Transfer tokens from the sale contract to a recipient. /// @param _recipient address The address of the recipient. /// @param _tokens uint256 The amount of tokens to transfer. function transferTokens(address _recipient, uint256 _tokens) private returns (bool ans) { ans = cln.transfer(_recipient, _tokens); if (ans) { TokensIssued(_recipient, _tokens); } } /// @dev Transfer tokens from the sale contract to a recipient. /// @param _recipient address The address of the recipient. /// @param _tokens uint256 The amount of tokens to transfer. /// @param _data bytes data to send to receiver if it is a contract. function transferTokens(address _recipient, uint256 _tokens, bytes _data) private returns (bool ans) { // Request Colu Local Network contract to transfer the requested tokens for the buyer. ans = cln.transferAndCall(_recipient, _tokens, _data); if (ans) { TokensIssued(_recipient, _tokens); } } /// @dev Requests to transfer control of the Colu Local Network contract to a new owner. /// @param _newOwnerCandidate address The address to transfer ownership to. /// /// NOTE: /// 1. The new owner will need to call Colu Local Network contract's acceptOwnership directly in order to accept the ownership. /// 2. Calling this method during the token sale will prevent the token sale to continue, since only the owner of /// the Colu Local Network contract can transfer tokens during the sale. function requestColuLocalNetworkOwnershipTransfer(address _newOwnerCandidate) external onlyOwner { cln.requestOwnershipTransfer(_newOwnerCandidate); } /// @dev Accepts new ownership on behalf of the Colu Local Network contract. // This can be used by the sale contract itself to claim back ownership of the Colu Local Network contract. function acceptColuLocalNetworkOwnership() external onlyOwner { cln.acceptOwnership(); } /// @dev Requests to transfer control of the VestingTrustee contract to a new owner. /// @param _newOwnerCandidate address The address to transfer ownership to. /// /// NOTE: /// 1. The new owner will need to call trustee contract's acceptOwnership directly in order to accept the ownership. /// 2. Calling this method during the token sale will prevent the token sale from alocation presale grunts add finalize, since only the owner of /// the trustee contract can create grunts needed in the presaleAlocation add finalize methods. function requestVestingTrusteeOwnershipTransfer(address _newOwnerCandidate) external onlyOwner { trustee.requestOwnershipTransfer(_newOwnerCandidate); } /// @dev Accepts new ownership on behalf of the VestingTrustee contract. /// This can be used by the token sale contract itself to claim back ownership of the VestingTrustee contract. function acceptVestingTrusteeOwnership() external onlyOwner { trustee.acceptOwnership(); } }
Constructor sets the sale addresses and start time. _owner address The address of this contract owner. _fundingRecipient address The address of the funding recipient. _communityPoolAddress address The address of the community pool. _futureDevelopmentPoolAddress address The address of the future development pool. _stakeholdersPoolAddress address The address of the team pool. _startTime uint256 The start time of the token sale.
function ColuLocalNetworkSale(address _owner, address _fundingRecipient, address _communityPoolAddress, address _futureDevelopmentPoolAddress, address _stakeholdersPoolAddress, uint256 _startTime) public { require(_owner != address(0)); require(_fundingRecipient != address(0)); require(_communityPoolAddress != address(0)); require(_futureDevelopmentPoolAddress != address(0)); require(_stakeholdersPoolAddress != address(0)); require(_startTime > now); owner = _owner; fundingRecipient = _fundingRecipient; communityPoolAddress = _communityPoolAddress; futureDevelopmentPoolAddress = _futureDevelopmentPoolAddress; stakeholdersPoolAddress = _stakeholdersPoolAddress; startTime = _startTime; endTime = startTime + SALE_DURATION; }
1,083,156
pragma solidity ^0.6.0; import "@openzeppelin/contracts-upgradeable/proxy/Initializable.sol"; import "@openzeppelin/contracts-upgradeable/access/AccessControlUpgradeable.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; import "abdk-libraries-solidity/ABDKMath64x64.sol"; contract WaxBridge is Initializable, AccessControlUpgradeable { using ABDKMath64x64 for int128; using SafeMath for uint256; bytes32 public constant WAX_BRIDGE = keccak256("WAX_BRIDGE"); uint256 public constant LIMIT_PERIOD = 1 days; function initialize() public initializer { __AccessControl_init(); _setupRole(DEFAULT_ADMIN_ROLE, msg.sender); latestWaxChainBlockNumberProcessed = 0; totalOwedBnb = 0; bnbLimitPerPeriod = 35779455436688300;// 0.03577 or about $10 } uint256 public latestWaxChainBlockNumberProcessed; uint256 public totalOwedBnb; uint256 public bnbLimitPerPeriod; mapping(address => uint256) public bnbLimitTimestamp; mapping(address => uint256) public withdrawableBnb; mapping(address => uint256) private withdrawnBnbDuringPeriod; function getWithdrawnBnbDuringPeriod() public view returns (uint256) { if(bnbLimitTimestamp[msg.sender] + LIMIT_PERIOD < block.timestamp) { return 0; } return withdrawnBnbDuringPeriod[msg.sender]; } function getRemainingWithdrawableBnbDuringPeriod() external view returns(uint256) { return bnbLimitPerPeriod.sub(getWithdrawnBnbDuringPeriod()); } function getTimeUntilLimitExpires() external view returns(uint256) { uint256 limitExpirationTime = bnbLimitTimestamp[msg.sender] + LIMIT_PERIOD; (, uint256 result) = limitExpirationTime.trySub(block.timestamp); return result; } function setDailyBnbWeiLimit(uint256 _dailyBnbWeiLimit) external restricted { bnbLimitPerPeriod = _dailyBnbWeiLimit; } receive() external payable restricted { } function processWaxConversions(uint256 _latestWaxChainBlockNumberProcessed, address[] calldata _to, uint256[] calldata _value) external payable { require(hasRole(WAX_BRIDGE, msg.sender), "Missing WAX_BRIDGE role"); require(_latestWaxChainBlockNumberProcessed > latestWaxChainBlockNumberProcessed, "WAX chain block num must be gt"); require(_to.length == _value.length, "Mismatched array lengths"); require(_to.length < 3000, "Too many recipients"); // assume they're holding enough skill (bot will check through main contract) latestWaxChainBlockNumberProcessed = _latestWaxChainBlockNumberProcessed; uint256 _totalOwedBnb = 0; for (uint256 i = 0; i < _to.length; i++) { _totalOwedBnb = _totalOwedBnb.add(_value[i]); withdrawableBnb[_to[i]] = withdrawableBnb[_to[i]].add(_value[i]); } totalOwedBnb = totalOwedBnb.add(_totalOwedBnb); } function withdraw(uint256 _maxAmount) external returns (uint256) { if(bnbLimitTimestamp[msg.sender] + LIMIT_PERIOD < block.timestamp) { bnbLimitTimestamp[msg.sender] = block.timestamp; withdrawnBnbDuringPeriod[msg.sender] = 0; } uint256 withdrawableBnbDuringPeriod = bnbLimitPerPeriod.sub(withdrawnBnbDuringPeriod[msg.sender]); uint256 bnbToSend = _maxAmount; if(bnbToSend > withdrawableBnb[msg.sender]) { bnbToSend = withdrawableBnb[msg.sender]; } if(bnbToSend > withdrawableBnbDuringPeriod) { bnbToSend = withdrawableBnbDuringPeriod; } // because of if statement above, 'bnbToSend' is guaranteed to be lte 'withdrawableBnb[msg.sender]' // this saves gas withdrawableBnb[msg.sender] -= bnbToSend; totalOwedBnb -= bnbToSend; withdrawnBnbDuringPeriod[msg.sender] = withdrawnBnbDuringPeriod[msg.sender].add(bnbToSend); // supposedly, send and transfer are discouraged since ether istanbul update (bool sent,) = msg.sender.call{value: bnbToSend}(""); require(sent, "Failed to send BNB"); } modifier restricted() { require(hasRole(DEFAULT_ADMIN_ROLE, msg.sender), "Missing DEFAULT_ADMIN_ROLE role"); _; } }
assume they're holding enough skill (bot will check through main contract)
function processWaxConversions(uint256 _latestWaxChainBlockNumberProcessed, address[] calldata _to, uint256[] calldata _value) external payable { require(hasRole(WAX_BRIDGE, msg.sender), "Missing WAX_BRIDGE role"); require(_latestWaxChainBlockNumberProcessed > latestWaxChainBlockNumberProcessed, "WAX chain block num must be gt"); require(_to.length == _value.length, "Mismatched array lengths"); require(_to.length < 3000, "Too many recipients"); latestWaxChainBlockNumberProcessed = _latestWaxChainBlockNumberProcessed; uint256 _totalOwedBnb = 0; for (uint256 i = 0; i < _to.length; i++) { _totalOwedBnb = _totalOwedBnb.add(_value[i]); withdrawableBnb[_to[i]] = withdrawableBnb[_to[i]].add(_value[i]); } totalOwedBnb = totalOwedBnb.add(_totalOwedBnb); }
1,760,309
// SPDX-License-Identifier: MIT pragma solidity ^0.6.12; import "https://github.com/OpenZeppelin/openzeppelin-contracts/blob/release-v3.4/contracts/math/SafeMath.sol"; import "https://github.com/OpenZeppelin/openzeppelin-contracts/blob/release-v3.4/contracts/GSN/Context.sol"; import "https://github.com/OpenZeppelin/openzeppelin-contracts/blob/release-v3.4/contracts/utils/ReentrancyGuard.sol"; import "https://github.com/OpenZeppelin/openzeppelin-contracts/blob/release-v3.4/contracts/token/ERC20/ERC20.sol"; import "https://github.com/Woonkly/MartinHSolUtils/releasev34/OwnersLMH.sol"; import "https://github.com/Woonkly/MartinHSolUtils/releasev34/PausabledLMH.sol"; import "https://github.com/Woonkly/MartinHSolUtils/releasev34/BaseLMH.sol"; import "./MPLiquidityManager.sol"; /** MIT License Copyright (c) 2021 Woonkly OU 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 BY WOONKLY OU "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 MPbase is BaseLMH, PausabledLMH, ReentrancyGuard { using SafeMath for uint256; //Section Type declarations struct Stake { address account; uint256 liq; uint256 tokena; uint256 tokenb; uint8 flag; } struct processRewardInfo { uint256 remainder; uint256 woopsRewards; uint256 dealed; address me; bool resp; } //Section State variables IERC20 internal _tokenB; address internal _operations; address internal _beneficiary; address internal _executor; MPLiquidityManager internal _stakes; address internal _stakeable; uint256 internal _feeLIQ; uint256 internal _feeOperation; uint256 internal _feeSTAKE; uint256 internal _baseFee; bool internal _isBNBenv; address internal _erc20B; uint256 internal _rewPend = 0; uint256 internal _rewPendTKA = 0; uint256 internal _feeEXE = 0; //Section Modifier //Section Events event AddressChanged(address olda, address newa, uint8 id); event valueChanged(uint256 olda, uint256 newa, uint8 id); //Section functions /** * @dev Base constructor of POOL childrens * *Parameters: * address erc20B ERC20 address contract instance * uint256 feeLIQ fee is discounted for each swapp and partitioned between liquidity providers only (1..999) allowed * uint256 feeOperation fee is discounted for each swapp and send to operations account only (1..999) allowed * uint256 feeSTAKE, fee is discounted for each swapp and send to benef. account only (1..999) allowed * address operations, Account operations * address beneficiary, Account benef. to reward stakers liq. providers in STAKE contract * address executor, Account used for dapp to execute contracts functions where the fee is accumulated to be used in the dapp * address stake, LiquidityManager contract instance, store and manage all liq.providers * bool isBNBenv Set true is Binance blockchain (for future use) * * Requirements: * (feeLIQ + feeOperation + feeSTAKE) === 1000 allowed relation 1 to 100 % * * IMPORTANT: * For the pool to be activated and working, the CreatePool function must be executed after deploying the contract */ constructor( address erc20B, uint256 feeLIQ, uint256 feeOperation, uint256 feeSTAKE, address operations, address beneficiary, address executor, address stake, bool isBNBenv ) public { _erc20B = erc20B; _feeLIQ = feeLIQ; _feeOperation = feeOperation; _feeSTAKE = feeSTAKE; _beneficiary = beneficiary; _executor = executor; _operations = operations; _stakes = MPLiquidityManager(stake); _stakeable = stake; _isBNBenv = isBNBenv; _tokenB = IERC20(erc20B); _paused = true; _baseFee = 10000; _feeEXE = 418380000000000; } /** * @dev Get _isBNBenv * */ function isBNB() public view returns (bool) { return _isBNBenv; } /** * @dev Get _beneficiary * */ function getBeneficiary() public view returns (address) { return _beneficiary; } /** * @dev get uint256,bool type values of store * * uint256 feeLIQ fee is discounted for each swapp and partitioned between liquidity providers only (1..999) allowed * uint256 feeOperation fee is discounted for each swapp and send to operations account only (1..999) allowed * uint256 feeSTAKE fee is discounted for each swapp and send to benef. account only (1..999) allowed * uint256 _baseFee Base for fee calculation * uint256 _rewPend Value store acum. total pendings rewards tokens * uint256 _rewPendTKA Value store acum. total pendings rewards coin * uint256 _feeEXE Fee this is transfer to executor acc. (for each swapp) to get money to perform dapp contract function executions * bool isBNBenv Set true is Binance blockchain (for future use) * */ function getValues() external view returns ( uint256, uint256, uint256, uint256, uint256, uint256, uint256, bool ) { return ( _feeLIQ, _feeOperation, _feeSTAKE, _baseFee, _rewPend, _rewPendTKA, _feeEXE, _isBNBenv ); } /** * @dev set uint256 type values store according to the value of set *Parameters: * set equal to.. * * 1 uint256 feeLIQ fee is discounted for each swapp and partitioned between liquidity providers only (1..999) allowed * 2 uint256 feeOperation fee is discounted for each swapp and send to operations account only (1..999) allowed * 3 uint256 feeSTAKE fee is discounted for each swapp and send to benef. account only (1..999) allowed * 4 uint256 _baseFee Base for fee calculation * 5 uint256 _rewPend Value store acum. total pendings rewards tokens * 6 uint256 _rewPendTKA Value store acum. total pendings rewards coin * 7 uint256 _feeEXE Fee this is transfer to executor acc. (for each swapp) to get money to perform dapp contract function executions * * Emit {valueChanged} evt * * Requirements: * only Is InOwners require */ function setValues(uint256 value, uint8 id) external onlyIsInOwners returns (bool) { uint256 old; if (id == 1) { require( value <= 1000000), "1"); old = _feeLIQ; _feeLIQ = value; } if (id == 2) { require((value > 0 && value <= 1000000), "1"); old = _feeOperation; _feeOperation = value; } if (id == 3) { require(( value <= 1000000), "1"); old = _feeSTAKE; _feeSTAKE = value; } if (id == 4) { require((value > 0 && value <= 1000000), "1"); old = _baseFee; _baseFee = value; } if (id == 5) { old = _rewPend; _rewPend = value; } if (id == 6) { old = _rewPendTKA; _rewPendTKA = value; } if (id == 7) { old = _feeEXE; _feeEXE = value; } emit valueChanged(old, value, id); return true; } /** * @dev get address type values of store * * address operations, Operations wallet * address beneficiary, Benef. wallet to reward stakers liq. providers in STAKE contract * address executor, Wallet used for dapp to execute contracts functions where the fee is accumulated to be used in the dapp * address stake, LiquidityManager contract instance, store and manage all liq.providers * address erc20B ERC20 address contract instance * */ function getAddress() external view returns ( address, address, address, address, address ) { return (_operations, _beneficiary, _executor, _stakeable, _erc20B); } /** * @dev set address type values store according to the value of set *Parameters: * set equal to.. * * 1 address operations, Operations wallet * 2 address beneficiary, Benef. wallet to reward stakers liq. providers in STAKE contract * 3 address executor, Wallet used for dapp to execute contracts functions where the fee is accumulated to be used in the dapp * 4 address stake, LiquidityManager contract instance, store and manage all liq.providers * 5 address erc20B ERC20 address contract instance * * Emit {AddressChanged} evt * * Requirements: * only Is InOwners require */ function setAddress(address newa, uint8 id) external onlyIsInOwners returns (bool) { require(newa != address(0), "1"); address old; if (id == 1) { old = _operations; _operations = newa; } if (id == 2) { old = _beneficiary; _beneficiary = newa; } if (id == 3) { old = _executor; _executor = newa; } if (id == 4) { old = _stakeable; _stakeable = newa; _stakes = MPLiquidityManager(newa); } if (id == 5) { old = _erc20B; _erc20B = newa; _tokenB = IERC20(_erc20B); } emit AddressChanged(old, newa, id); return true; } /** * @dev get sum of all _feeXX to perform master fee calculation * */ function getFee() internal view returns (uint256) { uint256 fee = _feeLIQ + _feeSTAKE + _feeOperation; if (fee > _baseFee) { return 0; } return _baseFee - fee; } /** * @dev get swapp price with the discounted fee * */ function price( uint256 input_amount, uint256 input_reserve, uint256 output_reserve ) public view returns (uint256) { uint256 input_amount_with_fee = input_amount.mul(uint256(getFee())); uint256 numerator = input_amount_with_fee.mul(output_reserve); uint256 denominator = input_reserve.mul(_baseFee).add(input_amount_with_fee); return numerator.div(denominator); } /** * @dev get swapp price with no fee * */ function planePrice( uint256 input_amount, uint256 input_reserve, uint256 output_reserve ) public view returns (uint256) { uint256 input_amount_with_fee0 = input_amount.mul(uint256(_baseFee)); uint256 numerator = input_amount_with_fee0.mul(output_reserve); uint256 denominator = input_reserve.mul(_baseFee).add(input_amount_with_fee0); return numerator.div(denominator); } /** * @dev get the Calculate the amount fees corresponding to each sector * * uint256 remanider amount * uint256 amount for liq providers * uint256 amount for operations * uint256 amount for stakers rewards * */ function calcFees(uint256 amount) internal view returns ( uint256, uint256, uint256, uint256 ) { uint256 totFee = _feeLIQ + _feeSTAKE + _feeOperation; uint256 liq = amount.mul(_feeLIQ).div(totFee); uint256 oper = amount.mul(_feeOperation).div(totFee); uint256 stake = amount.mul(_feeSTAKE).div(totFee); uint256 remainder = amount - (liq + oper + stake); return (remainder, liq, oper, stake); } /** * @dev get the Calculate the amount correspondig to liq provider * * uint256 part amount * uint256 remainder * */ function getCalcRewardAmount( address account, uint256 amount, uint256 totalLiquidity ) public view returns (uint256, uint256) { if (!_stakes.StakeExist(account)) return (0, 0); (, uint256 liq, , , , ) = _stakes.getStake(account); uint256 part = (liq * amount).div(totalLiquidity); return (part, amount - part); } /** * @dev Substract from reward pending acum. * * bool isTKA is cthe coin part * */ function substractRewPend(uint256 amount, bool isTKA) internal returns (bool) { if (isTKA != true) { if (_rewPend >= amount) { _rewPend = _rewPend.sub(amount); } else { _rewPend = 0; } } else { if (_rewPendTKA >= amount) { _rewPendTKA = _rewPendTKA.sub(amount); } else { _rewPendTKA = 0; } } } }
get the Calculate the amount correspondig to liq provider uint256 part amount uint256 remainder/
function getCalcRewardAmount( address account, uint256 amount, uint256 totalLiquidity ) public view returns (uint256, uint256) { if (!_stakes.StakeExist(account)) return (0, 0); (, uint256 liq, , , , ) = _stakes.getStake(account); uint256 part = (liq * amount).div(totalLiquidity); return (part, amount - part); }
14,052,436
./full_match/100/0x1E4a864450A3924d241B1541A2Be2f43859117aB/sources/var/www/nodejs/contracthoneycomp/contracts/ComponentLibrary.sol
transfers component tokens _recipient the address of where to send the component tokens _amount the amount of component tokens to send return success_ the success bool of the call
function transfer ( address _recipient, uint _amount ) public nonReentrant returns ( bool success_ ) { require(!partitionTickets[msg.sender].initialized, "Component/no-transfers-once-partitioned"); success_ = Components.transfer(component, _recipient, _amount); }
14,266,149
./partial_match/42/0x782F6c6EAC0C1F8B179317Cf34826ca498cA4145/sources/FixedSupplyToken.sol
Transfer the balance from owner's account to another account
function transfer(address _to, uint256 _amount) returns (bool success) { if (balances[msg.sender] >= _amount && _amount > 0 && balances[_to] + _amount > balances[_to]) { balances[msg.sender] -= _amount; balances[_to] += _amount; Transfer(msg.sender, _to, _amount); return true; return false; } }
3,376,130
// SPDX-License-Identifier: MIT pragma solidity >=0.8.0 <0.9.0; // File: @chainlink/contracts/src/v0.8/interfaces/AggregatorV3Interface.sol /* * @dev Provides o consume price data, this smart contract references * AggregatorV3Interface, which defines the external functions implemented by * the ETH/USD Price Feed. */ interface AggregatorV3Interface { function decimals() external view returns (uint8); function description() external view returns (string memory); function version() external view returns (uint256); // getRoundData and latestRoundData should both raise "No data present" // if they do not have data to report, instead of returning unset values // which could be misinterpreted as actual reported values. function getRoundData(uint80 _roundId) external view returns ( uint80 roundId, int256 answer, uint256 startedAt, uint256 updatedAt, uint80 answeredInRound ); function latestRoundData() external view returns ( uint80 roundId, int256 answer, uint256 startedAt, uint256 updatedAt, uint80 answeredInRound ); } // File: @openzeppelin/contracts/utils/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 meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } // File: @openzeppelin/contracts/access/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() { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), 'Ownable: caller is not the owner'); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), 'Ownable: new owner is the zero address'); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } // File: @openzeppelin/contracts/utils/introspection/IERC1820Registry.sol /** * @dev Interface of the global ERC1820 Registry, as defined in the * https://eips.ethereum.org/EIPS/eip-1820[EIP]. Accounts may register * implementers for interfaces in this registry, as well as query support. * * Implementers may be shared by multiple accounts, and can also implement more * than a single interface for each account. Contracts can implement interfaces * for themselves, but externally-owned accounts (EOA) must delegate this to a * contract. * * {IERC165} interfaces can also be queried via the registry. * * For an in-depth explanation and source code analysis, see the EIP text. */ interface IERC1820Registry { /** * @dev Sets `newManager` as the manager for `account`. A manager of an * account is able to set interface implementers for it. * * By default, each account is its own manager. Passing a value of `0x0` in * `newManager` will reset the manager to this initial state. * * Emits a {ManagerChanged} event. * * Requirements: * * - the caller must be the current manager for `account`. */ function setManager(address account, address newManager) external; /** * @dev Returns the manager for `account`. * * See {setManager}. */ function getManager(address account) external view returns (address); /** * @dev Sets the `implementer` contract as ``account``'s implementer for * `interfaceHash`. * * `account` being the zero address is an alias for the caller's address. * The zero address can also be used in `implementer` to remove an old one. * * See {interfaceHash} to learn how these are created. * * Emits an {InterfaceImplementerSet} event. * * Requirements: * * - the caller must be the current manager for `account`. * - `interfaceHash` must not be an {IERC165} interface id (i.e. it must not * end in 28 zeroes). * - `implementer` must implement {IERC1820Implementer} and return true when * queried for support, unless `implementer` is the caller. See * {IERC1820Implementer-canImplementInterfaceForAddress}. */ function setInterfaceImplementer( address account, bytes32 _interfaceHash, address implementer ) external; /** * @dev Returns the implementer of `interfaceHash` for `account`. If no such * implementer is registered, returns the zero address. * * If `interfaceHash` is an {IERC165} interface id (i.e. it ends with 28 * zeroes), `account` will be queried for support of it. * * `account` being the zero address is an alias for the caller's address. */ function getInterfaceImplementer(address account, bytes32 _interfaceHash) external view returns (address); /** * @dev Returns the interface hash for an `interfaceName`, as defined in the * corresponding * https://eips.ethereum.org/EIPS/eip-1820#interface-name[section of the EIP]. */ function interfaceHash(string calldata interfaceName) external pure returns (bytes32); /** * @notice Updates the cache with whether the contract implements an ERC165 interface or not. * @param account Address of the contract for which to update the cache. * @param interfaceId ERC165 interface for which to update the cache. */ function updateERC165Cache(address account, bytes4 interfaceId) external; /** * @notice Checks whether a contract implements an ERC165 interface or not. * If the result is not cached a direct lookup on the contract address is performed. * If the result is not cached or the cached value is out-of-date, the cache MUST be updated manually by calling * {updateERC165Cache} with the contract address. * @param account Address of the contract to check. * @param interfaceId ERC165 interface to check. * @return True if `account` implements `interfaceId`, false otherwise. */ function implementsERC165Interface(address account, bytes4 interfaceId) external view returns (bool); /** * @notice Checks whether a contract implements an ERC165 interface or not without using nor updating the cache. * @param account Address of the contract to check. * @param interfaceId ERC165 interface to check. * @return True if `account` implements `interfaceId`, false otherwise. */ function implementsERC165InterfaceNoCache(address account, bytes4 interfaceId) external view returns (bool); event InterfaceImplementerSet( address indexed account, bytes32 indexed interfaceHash, address indexed implementer ); event ManagerChanged(address indexed account, address indexed newManager); } // 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) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, 'Address: insufficient balance'); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{value: amount}(''); require( success, 'Address: unable to send value, recipient may have reverted' ); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, 'Address: low-level call failed'); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue( target, data, value, 'Address: low-level call with value failed' ); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require( address(this).balance >= value, 'Address: insufficient balance for call' ); require(isContract(target), 'Address: call to non-contract'); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{value: value}(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, 'Address: low-level static call failed'); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), 'Address: static call to non-contract'); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall( target, data, 'Address: low-level delegate call failed' ); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), 'Address: delegate call to non-contract'); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.delegatecall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) private pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // File: @openzeppelin/contracts/token/ERC20/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/token/ERC777/IERC777Sender.sol /** * @dev Interface of the ERC777TokensSender standard as defined in the EIP. * * {IERC777} Token holders can be notified of operations performed on their * tokens by having a contract implement this interface (contract holders can be * their own implementer) and registering it on the * https://eips.ethereum.org/EIPS/eip-1820[ERC1820 global registry]. * * See {IERC1820Registry} and {ERC1820Implementer}. */ interface IERC777Sender { /** * @dev Called by an {IERC777} token contract whenever a registered holder's * (`from`) tokens are about to be moved or destroyed. The type of operation * is conveyed by `to` being the zero address or not. * * This call occurs _before_ the token contract's state is updated, so * {IERC777-balanceOf}, etc., can be used to query the pre-operation state. * * This function may revert to prevent the operation from being executed. */ function tokensToSend( address operator, address from, address to, uint256 amount, bytes calldata userData, bytes calldata operatorData ) external; } // File: @openzeppelin/contracts/token/ERC777/IERC777Recipient.sol /** * @dev Interface of the ERC777TokensRecipient standard as defined in the EIP. * * Accounts can be notified of {IERC777} tokens being sent to them by having a * contract implement this interface (contract holders can be their own * implementer) and registering it on the * https://eips.ethereum.org/EIPS/eip-1820[ERC1820 global registry]. * * See {IERC1820Registry} and {ERC1820Implementer}. */ interface IERC777Recipient { /** * @dev Called by an {IERC777} token contract whenever tokens are being * moved or created into a registered account (`to`). The type of operation * is conveyed by `from` being the zero address or not. * * This call occurs _after_ the token contract's state is updated, so * {IERC777-balanceOf}, etc., can be used to query the post-operation state. * * This function may revert to prevent the operation from being executed. */ function tokensReceived( address operator, address from, address to, uint256 amount, bytes calldata userData, bytes calldata operatorData ) external; } // File: @openzeppelin/contracts/token/ERC777/IERC777.sol /** * @dev Interface of the ERC777Token standard as defined in the EIP. * * This contract uses the * https://eips.ethereum.org/EIPS/eip-1820[ERC1820 registry standard] to let * token holders and recipients react to token movements by using setting implementers * for the associated interfaces in said registry. See {IERC1820Registry} and * {ERC1820Implementer}. */ interface IERC777 { /** * @dev Returns the name of the token. */ function name() external view returns (string memory); /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() external view returns (string memory); /** * @dev Returns the smallest part of the token that is not divisible. This * means all token operations (creation, movement and destruction) must have * amounts that are a multiple of this number. * * For most token contracts, this value will equal 1. */ function granularity() external view returns (uint256); /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by an account (`owner`). */ function balanceOf(address owner) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * If send or receive hooks are registered for the caller and `recipient`, * the corresponding functions will be called with `data` and empty * `operatorData`. See {IERC777Sender} and {IERC777Recipient}. * * Emits a {Sent} event. * * Requirements * * - the caller must have at least `amount` tokens. * - `recipient` cannot be the zero address. * - if `recipient` is a contract, it must implement the {IERC777Recipient} * interface. */ function send( address recipient, uint256 amount, bytes calldata data ) external; /** * @dev Destroys `amount` tokens from the caller's account, reducing the * total supply. * * If a send hook is registered for the caller, the corresponding function * will be called with `data` and empty `operatorData`. See {IERC777Sender}. * * Emits a {Burned} event. * * Requirements * * - the caller must have at least `amount` tokens. */ function burn(uint256 amount, bytes calldata data) external; /** * @dev Returns true if an account is an operator of `tokenHolder`. * Operators can send and burn tokens on behalf of their owners. All * accounts are their own operator. * * See {operatorSend} and {operatorBurn}. */ function isOperatorFor(address operator, address tokenHolder) external view returns (bool); /** * @dev Make an account an operator of the caller. * * See {isOperatorFor}. * * Emits an {AuthorizedOperator} event. * * Requirements * * - `operator` cannot be calling address. */ function authorizeOperator(address operator) external; /** * @dev Revoke an account's operator status for the caller. * * See {isOperatorFor} and {defaultOperators}. * * Emits a {RevokedOperator} event. * * Requirements * * - `operator` cannot be calling address. */ function revokeOperator(address operator) external; /** * @dev Returns the list of default operators. These accounts are operators * for all token holders, even if {authorizeOperator} was never called on * them. * * This list is immutable, but individual holders may revoke these via * {revokeOperator}, in which case {isOperatorFor} will return false. */ function defaultOperators() external view returns (address[] memory); /** * @dev Moves `amount` tokens from `sender` to `recipient`. The caller must * be an operator of `sender`. * * If send or receive hooks are registered for `sender` and `recipient`, * the corresponding functions will be called with `data` and * `operatorData`. See {IERC777Sender} and {IERC777Recipient}. * * Emits a {Sent} event. * * Requirements * * - `sender` cannot be the zero address. * - `sender` must have at least `amount` tokens. * - the caller must be an operator for `sender`. * - `recipient` cannot be the zero address. * - if `recipient` is a contract, it must implement the {IERC777Recipient} * interface. */ function operatorSend( address sender, address recipient, uint256 amount, bytes calldata data, bytes calldata operatorData ) external; /** * @dev Destroys `amount` tokens from `account`, reducing the total supply. * The caller must be an operator of `account`. * * If a send hook is registered for `account`, the corresponding function * will be called with `data` and `operatorData`. See {IERC777Sender}. * * Emits a {Burned} event. * * Requirements * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. * - the caller must be an operator for `account`. */ function operatorBurn( address account, uint256 amount, bytes calldata data, bytes calldata operatorData ) external; event Sent( address indexed operator, address indexed from, address indexed to, uint256 amount, bytes data, bytes operatorData ); event Minted( address indexed operator, address indexed to, uint256 amount, bytes data, bytes operatorData ); event Burned( address indexed operator, address indexed from, uint256 amount, bytes data, bytes operatorData ); event AuthorizedOperator( address indexed operator, address indexed tokenHolder ); event RevokedOperator(address indexed operator, address indexed tokenHolder); } // File: @openzeppelin/contracts/token/ERC777/ERC777.sol /** * @dev Implementation of the {IERC777} 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}. * * Support for ERC20 is included in this contract, as specified by the EIP: both * the ERC777 and ERC20 interfaces can be safely used when interacting with it. * Both {IERC777-Sent} and {IERC20-Transfer} events are emitted on token * movements. * * Additionally, the {IERC777-granularity} value is hard-coded to `1`, meaning that there * are no special restrictions in the amount of tokens that created, moved, or * destroyed. This makes integration with ERC20 applications seamless. */ contract ERC777 is Context, IERC777, IERC20 { using Address for address; IERC1820Registry internal constant _ERC1820_REGISTRY = IERC1820Registry(0x1820a4B7618BdE71Dce8cdc73aAB6C95905faD24); mapping(address => uint256) private _balances; uint256 private _totalSupply; string private _name; string private _symbol; bytes32 private constant _TOKENS_SENDER_INTERFACE_HASH = keccak256('ERC777TokensSender'); bytes32 private constant _TOKENS_RECIPIENT_INTERFACE_HASH = keccak256('ERC777TokensRecipient'); // This isn't ever read from - it's only used to respond to the defaultOperators query. address[] private _defaultOperatorsArray; // Immutable, but accounts may revoke them (tracked in __revokedDefaultOperators). mapping(address => bool) private _defaultOperators; // For each account, a mapping of its operators and revoked default operators. mapping(address => mapping(address => bool)) private _operators; mapping(address => mapping(address => bool)) private _revokedDefaultOperators; // ERC20-allowances mapping(address => mapping(address => uint256)) private _allowances; /** * @dev `defaultOperators` may be an empty array. */ constructor( string memory name_, string memory symbol_, address[] memory defaultOperators_ ) { _name = name_; _symbol = symbol_; _defaultOperatorsArray = defaultOperators_; for (uint256 i = 0; i < defaultOperators_.length; i++) { _defaultOperators[defaultOperators_[i]] = true; } // register interfaces _ERC1820_REGISTRY.setInterfaceImplementer( address(this), keccak256('ERC777Token'), address(this) ); _ERC1820_REGISTRY.setInterfaceImplementer( address(this), keccak256('ERC20Token'), address(this) ); } /** * @dev See {IERC777-name}. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev See {IERC777-symbol}. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev See {ERC20-decimals}. * * Always returns 18, as per the * [ERC777 EIP](https://eips.ethereum.org/EIPS/eip-777#backward-compatibility). */ function decimals() public pure virtual returns (uint8) { return 18; } /** * @dev See {IERC777-granularity}. * * This implementation always returns `1`. */ function granularity() public view virtual override returns (uint256) { return 1; } /** * @dev See {IERC777-totalSupply}. */ function totalSupply() public view virtual override(IERC20, IERC777) returns (uint256) { return _totalSupply; } /** * @dev Returns the amount of tokens owned by an account (`tokenHolder`). */ function balanceOf(address tokenHolder) public view virtual override(IERC20, IERC777) returns (uint256) { return _balances[tokenHolder]; } /** * @dev See {IERC777-send}. * * Also emits a {IERC20-Transfer} event for ERC20 compatibility. */ function send( address recipient, uint256 amount, bytes memory data ) public virtual override { _send(_msgSender(), recipient, amount, data, '', true); } /** * @dev See {IERC20-transfer}. * * Unlike `send`, `recipient` is _not_ required to implement the {IERC777Recipient} * interface if it is a contract. * * Also emits a {Sent} event. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { require(recipient != address(0), 'ERC777: transfer to the zero address'); address from = _msgSender(); _callTokensToSend(from, from, recipient, amount, '', ''); _move(from, from, recipient, amount, '', ''); _callTokensReceived(from, from, recipient, amount, '', '', false); return true; } /** * @dev See {IERC777-burn}. * * Also emits a {IERC20-Transfer} event for ERC20 compatibility. */ function burn(uint256 amount, bytes memory data) public virtual override { _burn(_msgSender(), amount, data, ''); } /** * @dev See {IERC777-isOperatorFor}. */ function isOperatorFor(address operator, address tokenHolder) public view virtual override returns (bool) { return operator == tokenHolder || (_defaultOperators[operator] && !_revokedDefaultOperators[tokenHolder][operator]) || _operators[tokenHolder][operator]; } /** * @dev See {IERC777-authorizeOperator}. */ function authorizeOperator(address operator) public virtual override { require(_msgSender() != operator, 'ERC777: authorizing self as operator'); if (_defaultOperators[operator]) { delete _revokedDefaultOperators[_msgSender()][operator]; } else { _operators[_msgSender()][operator] = true; } emit AuthorizedOperator(operator, _msgSender()); } /** * @dev See {IERC777-revokeOperator}. */ function revokeOperator(address operator) public virtual override { require(operator != _msgSender(), 'ERC777: revoking self as operator'); if (_defaultOperators[operator]) { _revokedDefaultOperators[_msgSender()][operator] = true; } else { delete _operators[_msgSender()][operator]; } emit RevokedOperator(operator, _msgSender()); } /** * @dev See {IERC777-defaultOperators}. */ function defaultOperators() public view virtual override returns (address[] memory) { return _defaultOperatorsArray; } /** * @dev See {IERC777-operatorSend}. * * Emits {Sent} and {IERC20-Transfer} events. */ function operatorSend( address sender, address recipient, uint256 amount, bytes memory data, bytes memory operatorData ) public virtual override { require( isOperatorFor(_msgSender(), sender), 'ERC777: caller is not an operator for holder' ); _send(sender, recipient, amount, data, operatorData, true); } /** * @dev See {IERC777-operatorBurn}. * * Emits {Burned} and {IERC20-Transfer} events. */ function operatorBurn( address account, uint256 amount, bytes memory data, bytes memory operatorData ) public virtual override { require( isOperatorFor(_msgSender(), account), 'ERC777: caller is not an operator for holder' ); _burn(account, amount, data, operatorData); } /** * @dev See {IERC20-allowance}. * * Note that operator and allowance concepts are orthogonal: operators may * not have allowance, and accounts with allowance may not be operators * themselves. */ function allowance(address holder, address spender) public view virtual override returns (uint256) { return _allowances[holder][spender]; } /** * @dev See {IERC20-approve}. * * Note that accounts cannot have allowance issued by their operators. */ function approve(address spender, uint256 value) public virtual override returns (bool) { address holder = _msgSender(); _approve(holder, spender, value); return true; } /** * @dev See {IERC20-transferFrom}. * * Note that operator and allowance concepts are orthogonal: operators cannot * call `transferFrom` (unless they have allowance), and accounts with * allowance cannot call `operatorSend` (unless they are operators). * * Emits {Sent}, {IERC20-Transfer} and {IERC20-Approval} events. */ function transferFrom( address holder, address recipient, uint256 amount ) public virtual override returns (bool) { require(recipient != address(0), 'ERC777: transfer to the zero address'); require(holder != address(0), 'ERC777: transfer from the zero address'); address spender = _msgSender(); _callTokensToSend(spender, holder, recipient, amount, '', ''); _move(spender, holder, recipient, amount, '', ''); uint256 currentAllowance = _allowances[holder][spender]; require( currentAllowance >= amount, 'ERC777: transfer amount exceeds allowance' ); _approve(holder, spender, currentAllowance - amount); _callTokensReceived(spender, holder, recipient, amount, '', '', false); return true; } /** * @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * If a send hook is registered for `account`, the corresponding function * will be called with `operator`, `data` and `operatorData`. * * See {IERC777Sender} and {IERC777Recipient}. * * Emits {Minted} and {IERC20-Transfer} events. * * Requirements * * - `account` cannot be the zero address. * - if `account` is a contract, it must implement the {IERC777Recipient} * interface. */ function _mint( address account, uint256 amount, bytes memory userData, bytes memory operatorData ) internal virtual { _mint(account, amount, userData, operatorData, true); } /** * @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * If `requireReceptionAck` is set to true, and if a send hook is * registered for `account`, the corresponding function will be called with * `operator`, `data` and `operatorData`. * * See {IERC777Sender} and {IERC777Recipient}. * * Emits {Minted} and {IERC20-Transfer} events. * * Requirements * * - `account` cannot be the zero address. * - if `account` is a contract, it must implement the {IERC777Recipient} * interface. */ function _mint( address account, uint256 amount, bytes memory userData, bytes memory operatorData, bool requireReceptionAck ) internal virtual { require(account != address(0), 'ERC777: mint to the zero address'); address operator = _msgSender(); _beforeTokenTransfer(operator, address(0), account, amount); // Update state variables _totalSupply += amount; _balances[account] += amount; _callTokensReceived( operator, address(0), account, amount, userData, operatorData, requireReceptionAck ); emit Minted(operator, account, amount, userData, operatorData); emit Transfer(address(0), account, amount); } /** * @dev Send tokens * @param from address token holder address * @param to address recipient address * @param amount uint256 amount of tokens to transfer * @param userData bytes extra information provided by the token holder (if any) * @param operatorData bytes extra information provided by the operator (if any) * @param requireReceptionAck if true, contract recipients are required to implement ERC777TokensRecipient */ function _send( address from, address to, uint256 amount, bytes memory userData, bytes memory operatorData, bool requireReceptionAck ) internal virtual { require(from != address(0), 'ERC777: send from the zero address'); require(to != address(0), 'ERC777: send to the zero address'); address operator = _msgSender(); _callTokensToSend(operator, from, to, amount, userData, operatorData); _move(operator, from, to, amount, userData, operatorData); _callTokensReceived( operator, from, to, amount, userData, operatorData, requireReceptionAck ); } /** * @dev Burn tokens * @param from address token holder address * @param amount uint256 amount of tokens to burn * @param data bytes extra information provided by the token holder * @param operatorData bytes extra information provided by the operator (if any) */ function _burn( address from, uint256 amount, bytes memory data, bytes memory operatorData ) internal virtual { require(from != address(0), 'ERC777: burn from the zero address'); address operator = _msgSender(); _callTokensToSend(operator, from, address(0), amount, data, operatorData); _beforeTokenTransfer(operator, from, address(0), amount); // Update state variables uint256 fromBalance = _balances[from]; require(fromBalance >= amount, 'ERC777: burn amount exceeds balance'); _balances[from] = fromBalance - amount; _totalSupply -= amount; emit Burned(operator, from, amount, data, operatorData); emit Transfer(from, address(0), amount); } function _move( address operator, address from, address to, uint256 amount, bytes memory userData, bytes memory operatorData ) private { _beforeTokenTransfer(operator, from, to, amount); uint256 fromBalance = _balances[from]; require(fromBalance >= amount, 'ERC777: transfer amount exceeds balance'); _balances[from] = fromBalance - amount; _balances[to] += amount; emit Sent(operator, from, to, amount, userData, operatorData); emit Transfer(from, to, amount); } /** * @dev See {ERC20-_approve}. * * Note that accounts cannot have allowance issued by their operators. */ function _approve( address holder, address spender, uint256 value ) internal { require(holder != address(0), 'ERC777: approve from the zero address'); require(spender != address(0), 'ERC777: approve to the zero address'); _allowances[holder][spender] = value; emit Approval(holder, spender, value); } /** * @dev Call from.tokensToSend() if the interface is registered * @param operator address operator requesting the transfer * @param from address token holder address * @param to address recipient address * @param amount uint256 amount of tokens to transfer * @param userData bytes extra information provided by the token holder (if any) * @param operatorData bytes extra information provided by the operator (if any) */ function _callTokensToSend( address operator, address from, address to, uint256 amount, bytes memory userData, bytes memory operatorData ) private { address implementer = _ERC1820_REGISTRY.getInterfaceImplementer( from, _TOKENS_SENDER_INTERFACE_HASH ); if (implementer != address(0)) { IERC777Sender(implementer).tokensToSend( operator, from, to, amount, userData, operatorData ); } } /** * @dev Call to.tokensReceived() if the interface is registered. Reverts if the recipient is a contract but * tokensReceived() was not registered for the recipient * @param operator address operator requesting the transfer * @param from address token holder address * @param to address recipient address * @param amount uint256 amount of tokens to transfer * @param userData bytes extra information provided by the token holder (if any) * @param operatorData bytes extra information provided by the operator (if any) * @param requireReceptionAck if true, contract recipients are required to implement ERC777TokensRecipient */ function _callTokensReceived( address operator, address from, address to, uint256 amount, bytes memory userData, bytes memory operatorData, bool requireReceptionAck ) private { address implementer = _ERC1820_REGISTRY.getInterfaceImplementer( to, _TOKENS_RECIPIENT_INTERFACE_HASH ); if (implementer != address(0)) { IERC777Recipient(implementer).tokensReceived( operator, from, to, amount, userData, operatorData ); } else if (requireReceptionAck) { require( !to.isContract(), 'ERC777: token recipient contract has no implementer for ERC777TokensRecipient' ); } } /** * @dev Hook that is called before any token transfer. This includes * calls to {send}, {transfer}, {operatorSend}, 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 operator, address from, address to, uint256 amount ) internal virtual {} } // File: contracts/5_MDSToken.sol // Library: SafeDecimalMath (Synthetix) /** * @title Safely manipulate unsigned fixed-point decimals at a given precision level. * @dev Functions accepting uints in this contract and derived contracts * are taken to be such fixed point decimals of a specified precision (either standard * or high). */ library SafeDecimalMath { /* Number of decimal places in the representations. */ uint8 public constant decimals = 18; uint8 public constant highPrecisionDecimals = 27; /* The number representing 1.0. */ uint256 public constant UNIT = 10**uint256(decimals); /* The number representing 1.0 for higher fidelity numbers. */ uint256 public constant PRECISE_UNIT = 10**uint256(highPrecisionDecimals); uint256 private constant UNIT_TO_HIGH_PRECISION_CONVERSION_FACTOR = 10**uint256(highPrecisionDecimals - decimals); /** * @return Provides an interface to UNIT. */ function unit() external pure returns (uint256) { return UNIT; } /** * @return Provides an interface to PRECISE_UNIT. */ function preciseUnit() external pure returns (uint256) { return PRECISE_UNIT; } /** * @return The result of multiplying x and y, interpreting the operands as fixed-point * decimals. * * @dev A unit factor is divided out after the product of x and y is evaluated, * so that product must be less than 2**256. As this is an integer division, * the internal division always rounds down. This helps save on gas. Rounding * is more expensive on gas. */ function multiplyDecimal(uint256 x, uint256 y) internal pure returns (uint256) { /* Divide by UNIT to remove the extra factor introduced by the product. */ return (x * y) / UNIT; } /** * @return The result of safely multiplying x and y, interpreting the operands * as fixed-point decimals of the specified precision unit. * * @dev The operands should be in the form of a the specified unit factor which will be * divided out after the product of x and y is evaluated, so that product must be * less than 2**256. * * Unlike multiplyDecimal, this function rounds the result to the nearest increment. * Rounding is useful when you need to retain fidelity for small decimal numbers * (eg. small fractions or percentages). */ function _multiplyDecimalRound( uint256 x, uint256 y, uint256 precisionUnit ) private pure returns (uint256) { /* Divide by UNIT to remove the extra factor introduced by the product. */ uint256 quotientTimesTen = (x * y) / (precisionUnit / 10); if (quotientTimesTen % 10 >= 5) { quotientTimesTen += 10; } return quotientTimesTen / 10; } /** * @return The result of safely multiplying x and y, interpreting the operands * as fixed-point decimals of a precise unit. * * @dev The operands should be in the precise unit factor which will be * divided out after the product of x and y is evaluated, so that product must be * less than 2**256. * * Unlike multiplyDecimal, this function rounds the result to the nearest increment. * Rounding is useful when you need to retain fidelity for small decimal numbers * (eg. small fractions or percentages). */ function multiplyDecimalRoundPrecise(uint256 x, uint256 y) internal pure returns (uint256) { return _multiplyDecimalRound(x, y, PRECISE_UNIT); } /** * @return The result of safely multiplying x and y, interpreting the operands * as fixed-point decimals of a standard unit. * * @dev The operands should be in the standard unit factor which will be * divided out after the product of x and y is evaluated, so that product must be * less than 2**256. * * Unlike multiplyDecimal, this function rounds the result to the nearest increment. * Rounding is useful when you need to retain fidelity for small decimal numbers * (eg. small fractions or percentages). */ function multiplyDecimalRound(uint256 x, uint256 y) internal pure returns (uint256) { return _multiplyDecimalRound(x, y, UNIT); } /** * @return The result of safely dividing x and y. The return value is a high * precision decimal. * * @dev y is divided after the product of x and the standard precision unit * is evaluated, so the product of x and UNIT must be less than 2**256. As * this is an integer division, the result is always rounded down. * This helps save on gas. Rounding is more expensive on gas. */ function divideDecimal(uint256 x, uint256 y) internal pure returns (uint256) { /* Reintroduce the UNIT factor that will be divided out by y. */ return (x * UNIT) / y; } /** * @return The result of safely dividing x and y. The return value is as a rounded * decimal in the precision unit specified in the parameter. * * @dev y is divided after the product of x and the specified precision unit * is evaluated, so the product of x and the specified precision unit must * be less than 2**256. The result is rounded to the nearest increment. */ function _divideDecimalRound( uint256 x, uint256 y, uint256 precisionUnit ) private pure returns (uint256) { uint256 resultTimesTen = (x * (precisionUnit * 10)) / y; if (resultTimesTen % 10 >= 5) { resultTimesTen += 10; } return resultTimesTen / 10; } /** * @return The result of safely dividing x and y. The return value is as a rounded * standard precision decimal. * * @dev y is divided after the product of x and the standard precision unit * is evaluated, so the product of x and the standard precision unit must * be less than 2**256. The result is rounded to the nearest increment. */ function divideDecimalRound(uint256 x, uint256 y) internal pure returns (uint256) { return _divideDecimalRound(x, y, UNIT); } /** * @return The result of safely dividing x and y. The return value is as a rounded * high precision decimal. * * @dev y is divided after the product of x and the high precision unit * is evaluated, so the product of x and the high precision unit must * be less than 2**256. The result is rounded to the nearest increment. */ function divideDecimalRoundPrecise(uint256 x, uint256 y) internal pure returns (uint256) { return _divideDecimalRound(x, y, PRECISE_UNIT); } /** * @dev Convert a standard decimal representation to a high precision one. */ function decimalToPreciseDecimal(uint256 i) internal pure returns (uint256) { return i * UNIT_TO_HIGH_PRECISION_CONVERSION_FACTOR; } /** * @dev Convert a high precision decimal to a standard decimal representation. */ function preciseDecimalToDecimal(uint256 i) internal pure returns (uint256) { uint256 quotientTimesTen = i / (UNIT_TO_HIGH_PRECISION_CONVERSION_FACTOR / 10); if (quotientTimesTen % 10 >= 5) { quotientTimesTen += 10; } return quotientTimesTen / 10; } } // Library: StringsAndBytes /** * @title StringsAndBytes Converts Strings to Bytes and Bytes32 and Vice-versa * @dev Converting Bytes and Strings into one another */ library StringsAndBytes { function stringToBytes32(string memory _source) public pure returns (bytes32 result) { // String have to be max 32 chars // https://ethereum.stackexchange.com/questions/9603/understanding-mload-assembly-function // http://solidity.readthedocs.io/en/latest/assembly.html assembly { result := mload(add(_source, 32)) } } function bytes32ToBytes(bytes32 _bytes32) public pure returns (bytes memory) { // bytes32 (fixed-size array) to bytes (dynamically-sized array) // string memory str = string(_bytes32); // TypeError: Explicit type conversion not allowed from "bytes32" to "string storage pointer" bytes memory bytesArray = new bytes(32); for (uint256 i; i < 32; i++) { bytesArray[i] = _bytes32[i]; } return bytesArray; } function bytes32ToString(bytes32 _bytes32) public pure returns (string memory) { // https://ethereum.stackexchange.com/questions/2519/how-to-convert-a-bytes32-to-string // https://ethereum.stackexchange.com/questions/1081/how-to-concatenate-a-bytes32-array-to-a-string bytes memory bytesArray = bytes32ToBytes(_bytes32); return string(bytesArray); } } contract MDSToken is ERC777, Ownable { using SafeDecimalMath for uint256; /** * Network: Rinkeby * Aggregator: ETH/USD * Address: 0x8A753747A1Fa494EC906cE90E9f37563A8AF630e */ AggregatorV3Interface internal priceFeed; // This is a type for a single proposal. struct Person { bytes32 firstName; // first name (up to 32 bytes) bytes32 lastName; // last/family name (up to 32 bytes) uint8 age; // Age } // This is a type for a single proposal. struct Family { uint256 numberOfMembers; // number of members uint256 balance; // family balance address[] membersArray; // array of members address operator; // person delegated to } // This declares a state variable that // stores a `Family` struct for each familyName. mapping(bytes32 => Family) public families; mapping(address => uint256) pendingWithdrawals; constructor(uint256 initialSupply, address[] memory defaultOperators) ERC777('MedShare', 'MDST', defaultOperators) { priceFeed = AggregatorV3Interface( 0x8A753747A1Fa494EC906cE90E9f37563A8AF630e ); _mint(msg.sender, initialSupply, '', ''); } /** * @dev Mint more tokens when debit or credit is received. */ function invest(string memory familyName) public payable { require( msg.sender != address(0), 'ERC777: cannot mint to the zero address' ); // Call returns a boolean value indicating success or failure. // This is the current recommended method to use. (bool sent, bytes memory data) = address(this).call{value: msg.value}(''); require(sent, 'Failed to send Ether'); // Exchanging ETH to USD uint256 usd = (msg.value * uint256(getEthUsdPrice())) / 10**getEthUsdPriceDecimals(); uint256 cached = (usd * 6167) / 100; uint256 fifth = usd / 5; uint256 twelfth = (usd * 833) / 100; uint256 tenth = usd / 10; bytes32 _familyNameB32 = StringsAndBytes.stringToBytes32(familyName); families[_familyNameB32].balance += family; _mint(address(this), fifth, '', ''); _mint(owner, twelfth, '', ''); _mint(msg.sender, cached, '', ''); } /** * @dev Mint more tokens when debit or credit is received. * @param familyName family to where the investiment will go. */ function investInAFamily(string memory familyName) public payable { require(msg.sender != address(0), 'ERC777: mint to the zero address'); uint256 usd = (msg.value * uint256(getEthUsdPrice())) / 10**getEthUsdPriceDecimals(); _mint(msg.sender, usd, '', ''); } /** * @dev ClaimFundsFrom Family. * @param familyName family from where funds can come * @param amount amount asked to be approved by the family operator */ function claimFundsFrom(string memory familyName, uint256 amount) public { require(msg.sender != address(0), 'ERC777: mint to the zero address'); pendingWithdrawals[msg.sender] += amount; uint256 usd = (msg.value * uint256(getEthUsdPrice())) / 10**getEthUsdPriceDecimals(); address payable claimant = msg.sender; address(this).transfer(claimant); } function withdraw() public { uint256 amount = pendingWithdrawals[msg.sender]; // Remember to zero the pending refund before // sending to prevent re-entrancy attacks pendingWithdrawals[msg.sender] = 0; payable(msg.sender).transfer(amount); } /** * Returns the latest price */ function getEthUsdPrice() public view returns (int256) { ( uint80 roundID, int256 price, uint256 startedAt, uint256 updatedAt, uint80 answeredInRound ) = priceFeed.latestRoundData(); return price; } function getEthUsdPriceDecimals() public view returns (uint8) { uint8 decimals = priceFeed.decimals(); return decimals; } function getContractBalance() public view returns (uint256) { return address(this).balance; } function sendUSDT(address _to, uint256 _amount) external { // This is the mainnet USDT contract address IERC20 usdt = IERC20(address(0xdAC17F958D2ee523a2206206994597C13D831ec7)); // transfers USDT that belong to your contract to the specified address usdt.transfer(_to, _amount); } event Received(address, uint256); // Function to receive Ether. msg.data must be empty receive() external payable { emit Received(msg.sender, msg.value); } event Fallenback(address, uint256); // Fallback function is called when msg.data is not empty fallback() external payable { emit Fallenback(msg.sender, msg.value); } }
return The result of multiplying x and y, interpreting the operands as fixed-point decimals. A unit factor is divided out after the product of x and y is evaluated, so that product must be less than 2256. As this is an integer division, the internal division always rounds down. This helps save on gas. Rounding is more expensive on gas./
function multiplyDecimal(uint256 x, uint256 y) internal pure returns (uint256) { return (x * y) / UNIT;
12,574,082
pragma solidity ^0.4.23; /** * @title BDACoin * @author BDACoin * @dev BDACoin is an ERC223 Token with ERC20 functions and events * Fully backward compatible with ERC20 */ /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) { return 0; } uint256 c = a * b; assert(c / a == b); return c; } function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } } /** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization * control functions, this simplifies the implementation of "user permissions". */ contract Ownable { address public owner; 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) onlyOwner public { require(newOwner != address(0)); OwnershipTransferred(owner, newOwner); owner = newOwner; } } /** * 彡(^)(^) * @title ERC223 * @dev ERC223 contract interface with ERC20 functions and events * Fully backward compatible with ERC20 * Recommended implementation used at https://github.com/Dexaran/ERC223-token-standard/tree/Recommended */ contract ERC223 { uint public totalSupply; // ERC223 and ERC20 functions and events function balanceOf(address who) public view returns (uint); function totalSupply() public view returns (uint256 _supply); function transfer(address to, uint value) public returns (bool ok); function transfer(address to, uint value, bytes data) public returns (bool ok); function transfer(address to, uint value, bytes data, string customFallback) public returns (bool ok); event Transfer(address indexed from, address indexed to, uint value, bytes indexed data); // ERC223 functions function name() public view returns (string _name); function symbol() public view returns (string _symbol); function decimals() public view returns (uint8 _decimals); // ERC20 functions and events function transferFrom(address _from, address _to, uint256 _value) public returns (bool success); function approve(address _spender, uint256 _value) public returns (bool success); function allowance(address _owner, address _spender) public view returns (uint256 remaining); event Transfer(address indexed _from, address indexed _to, uint256 _value); event Approval(address indexed _owner, address indexed _spender, uint _value); } /** * @title ContractReceiver * @dev Contract that is working with ERC223 tokens */ contract ContractReceiver { struct TKN { address sender; uint value; bytes data; bytes4 sig; } function tokenFallback(address _from, uint _value, bytes _data) public pure { TKN memory tkn; tkn.sender = _from; tkn.value = _value; tkn.data = _data; uint32 u = uint32(_data[3]) + (uint32(_data[2]) << 8) + (uint32(_data[1]) << 16) + (uint32(_data[0]) << 24); tkn.sig = bytes4(u); /* * tkn variable is analogue of msg variable of Ether transaction * tkn.sender is person who initiated this token transaction (analogue of msg.sender) * tkn.value the number of tokens that were sent (analogue of msg.value) * tkn.data is data of token transaction (analogue of msg.data) * tkn.sig is 4 bytes signature of function if data of token transaction is a function execution */ } } /** * @title BDACoin * @author BLACK DIA COIN TEAM * @dev BDACoin is an ERC223 Token with ERC20 functions and events * Fully backward compatible with ERC20 */ contract BDACoin is ERC223, Ownable { using SafeMath for uint256; string public name = "BLACK DIA COIN"; string public symbol = "BDA"; string public constant AAcontributors = "BLACK DIA COIN TEAM"; uint8 public decimals = 8; uint256 public totalSupply = 1e10 * 4e8; uint256 public distributeAmount = 0; bool public mintingFinished = false; mapping(address => uint256) public balanceOf; mapping(address => mapping (address => uint256)) public allowance; mapping (address => bool) public frozenAccount; mapping (address => uint256) public unlockUnixTime; event FrozenFunds(address indexed target, bool frozen); event LockedFunds(address indexed target, uint256 locked); event Burn(address indexed from, uint256 amount); event Mint(address indexed to, uint256 amount); event MintFinished(); /** * @dev Constructor is called only once and can not be called again */ function BDACoin() public { balanceOf[msg.sender] = totalSupply; } function name() public view returns (string _name) { return name; } function symbol() public view returns (string _symbol) { return symbol; } function decimals() public view returns (uint8 _decimals) { return decimals; } function totalSupply() public view returns (uint256 _totalSupply) { return totalSupply; } function balanceOf(address _owner) public view returns (uint256 balance) { return balanceOf[_owner]; } /** * @dev Prevent targets from sending or receiving tokens * @param targets Addresses to be frozen * @param isFrozen either to freeze it or not */ function freezeAccounts(address[] targets, bool isFrozen) onlyOwner public { require(targets.length > 0); for (uint j = 0; j < targets.length; j++) { require(targets[j] != 0x0); frozenAccount[targets[j]] = isFrozen; FrozenFunds(targets[j], isFrozen); } } /** * @dev Prevent targets from sending or receiving tokens by setting Unix times * @param targets Addresses to be locked funds * @param unixTimes Unix times when locking up will be finished */ function lockupAccounts(address[] targets, uint[] unixTimes) onlyOwner public { require(targets.length > 0 && targets.length == unixTimes.length); for(uint j = 0; j < targets.length; j++){ require(unlockUnixTime[targets[j]] < unixTimes[j]); unlockUnixTime[targets[j]] = unixTimes[j]; LockedFunds(targets[j], unixTimes[j]); } } /** * @dev Function that is called when a user or another contract wants to transfer funds */ function transfer(address _to, uint _value, bytes _data, string _custom_fallback) public returns (bool success) { require(_value > 0 && frozenAccount[msg.sender] == false && frozenAccount[_to] == false && now > unlockUnixTime[msg.sender] && now > unlockUnixTime[_to]); if (isContract(_to)) { require(balanceOf[msg.sender] >= _value); balanceOf[msg.sender] = balanceOf[msg.sender].sub(_value); balanceOf[_to] = balanceOf[_to].add(_value); assert(_to.call.value(0)(bytes4(keccak256(_custom_fallback)), msg.sender, _value, _data)); Transfer(msg.sender, _to, _value, _data); Transfer(msg.sender, _to, _value); return true; } else { return transferToAddress(_to, _value, _data); } } function transfer(address _to, uint _value, bytes _data) public returns (bool success) { require(_value > 0 && frozenAccount[msg.sender] == false && frozenAccount[_to] == false && now > unlockUnixTime[msg.sender] && now > unlockUnixTime[_to]); if (isContract(_to)) { return transferToContract(_to, _value, _data); } else { return transferToAddress(_to, _value, _data); } } /** * @dev Standard function transfer similar to ERC20 transfer with no _data * Added due to backwards compatibility reasons */ function transfer(address _to, uint _value) public returns (bool success) { require(_value > 0 && frozenAccount[msg.sender] == false && frozenAccount[_to] == false && now > unlockUnixTime[msg.sender] && now > unlockUnixTime[_to]); bytes memory empty; if (isContract(_to)) { return transferToContract(_to, _value, empty); } else { return transferToAddress(_to, _value, empty); } } // assemble the given address bytecode. If bytecode exists then the _addr is a contract. function isContract(address _addr) private view returns (bool is_contract) { uint length; assembly { //retrieve the size of the code on target address, this needs assembly length := extcodesize(_addr) } return (length > 0); } // function that is called when transaction target is an address function transferToAddress(address _to, uint _value, bytes _data) private returns (bool success) { require(balanceOf[msg.sender] >= _value); balanceOf[msg.sender] = balanceOf[msg.sender].sub(_value); balanceOf[_to] = balanceOf[_to].add(_value); Transfer(msg.sender, _to, _value, _data); Transfer(msg.sender, _to, _value); return true; } // function that is called when transaction target is a contract function transferToContract(address _to, uint _value, bytes _data) private returns (bool success) { require(balanceOf[msg.sender] >= _value); balanceOf[msg.sender] = balanceOf[msg.sender].sub(_value); balanceOf[_to] = balanceOf[_to].add(_value); ContractReceiver receiver = ContractReceiver(_to); receiver.tokenFallback(msg.sender, _value, _data); Transfer(msg.sender, _to, _value, _data); Transfer(msg.sender, _to, _value); return true; } /** * @dev Transfer tokens from one address to another * Added due to backwards compatibility with ERC20 * @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 success) { require(_to != address(0) && _value > 0 && balanceOf[_from] >= _value && allowance[_from][msg.sender] >= _value && frozenAccount[_from] == false && frozenAccount[_to] == false && now > unlockUnixTime[_from] && now > unlockUnixTime[_to]); balanceOf[_from] = balanceOf[_from].sub(_value); balanceOf[_to] = balanceOf[_to].add(_value); allowance[_from][msg.sender] = allowance[_from][msg.sender].sub(_value); Transfer(_from, _to, _value); return true; } /** * @dev Allows _spender to spend no more than _value tokens in your behalf * Added due to backwards compatibility with ERC20 * @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; Approval(msg.sender, _spender, _value); return true; } /** * @dev Function to check the amount of tokens that an owner allowed to a spender * Added due to backwards compatibility with ERC20 * @param _owner address The address which owns the funds * @param _spender address The address which will spend the funds */ function allowance(address _owner, address _spender) public view returns (uint256 remaining) { return allowance[_owner][_spender]; } /** * @dev Burns a specific amount of tokens. * @param _from The address that will burn the tokens. * @param _unitAmount The amount of token to be burned. */ function burn(address _from, uint256 _unitAmount) onlyOwner public { require(_unitAmount > 0 && balanceOf[_from] >= _unitAmount); balanceOf[_from] = balanceOf[_from].sub(_unitAmount); totalSupply = totalSupply.sub(_unitAmount); Burn(_from, _unitAmount); } modifier canMint() { require(!mintingFinished); _; } /** * @dev Function to mint tokens * @param _to The address that will receive the minted tokens. * @param _unitAmount The amount of tokens to mint. */ function mint(address _to, uint256 _unitAmount) onlyOwner canMint public returns (bool) { require(_unitAmount > 0); totalSupply = totalSupply.add(_unitAmount); balanceOf[_to] = balanceOf[_to].add(_unitAmount); Mint(_to, _unitAmount); Transfer(address(0), _to, _unitAmount); return true; } /** * @dev Function to stop minting new tokens. */ function finishMinting() onlyOwner canMint public returns (bool) { mintingFinished = true; MintFinished(); return true; } /** * @dev Function to distribute tokens to the list of addresses by the provided amount */ function distributeAirdrop(address[] addresses, uint256 amount) public returns (bool) { require(amount > 0 && addresses.length > 0 && frozenAccount[msg.sender] == false && now > unlockUnixTime[msg.sender]); amount = amount.mul(1e8); uint256 totalAmount = amount.mul(addresses.length); require(balanceOf[msg.sender] >= totalAmount); for (uint j = 0; j < addresses.length; j++) { require(addresses[j] != 0x0 && frozenAccount[addresses[j]] == false && now > unlockUnixTime[addresses[j]]); balanceOf[addresses[j]] = balanceOf[addresses[j]].add(amount); Transfer(msg.sender, addresses[j], amount); } balanceOf[msg.sender] = balanceOf[msg.sender].sub(totalAmount); return true; } function distributeAirdrop(address[] addresses, uint[] amounts) public returns (bool) { require(addresses.length > 0 && addresses.length == amounts.length && frozenAccount[msg.sender] == false && now > unlockUnixTime[msg.sender]); uint256 totalAmount = 0; for(uint j = 0; j < addresses.length; j++){ require(amounts[j] > 0 && addresses[j] != 0x0 && frozenAccount[addresses[j]] == false && now > unlockUnixTime[addresses[j]]); amounts[j] = amounts[j].mul(1e8); totalAmount = totalAmount.add(amounts[j]); } require(balanceOf[msg.sender] >= totalAmount); for (j = 0; j < addresses.length; j++) { balanceOf[addresses[j]] = balanceOf[addresses[j]].add(amounts[j]); Transfer(msg.sender, addresses[j], amounts[j]); } balanceOf[msg.sender] = balanceOf[msg.sender].sub(totalAmount); return true; } /** * @dev Function to collect tokens from the list of addresses */ function collectTokens(address[] addresses, uint[] amounts) onlyOwner public returns (bool) { require(addresses.length > 0 && addresses.length == amounts.length); uint256 totalAmount = 0; for (uint j = 0; j < addresses.length; j++) { require(amounts[j] > 0 && addresses[j] != 0x0 && frozenAccount[addresses[j]] == false && now > unlockUnixTime[addresses[j]]); amounts[j] = amounts[j].mul(1e8); require(balanceOf[addresses[j]] >= amounts[j]); balanceOf[addresses[j]] = balanceOf[addresses[j]].sub(amounts[j]); totalAmount = totalAmount.add(amounts[j]); Transfer(addresses[j], msg.sender, amounts[j]); } balanceOf[msg.sender] = balanceOf[msg.sender].add(totalAmount); return true; } function setDistributeAmount(uint256 _unitAmount) onlyOwner public { distributeAmount = _unitAmount; } /** * @dev Function to distribute tokens to the msg.sender automatically * If distributeAmount is 0, this function doesn't work */ function autoDistribute() payable public { require(distributeAmount > 0 && balanceOf[owner] >= distributeAmount && frozenAccount[msg.sender] == false && now > unlockUnixTime[msg.sender]); if(msg.value > 0) owner.transfer(msg.value); balanceOf[owner] = balanceOf[owner].sub(distributeAmount); balanceOf[msg.sender] = balanceOf[msg.sender].add(distributeAmount); Transfer(owner, msg.sender, distributeAmount); } /** * @dev fallback function */ function() payable public { autoDistribute(); } }
Function to distribute tokens to the list of addresses by the provided amount/
function distributeAirdrop(address[] addresses, uint256 amount) public returns (bool) { require(amount > 0 && addresses.length > 0 && frozenAccount[msg.sender] == false && now > unlockUnixTime[msg.sender]); amount = amount.mul(1e8); uint256 totalAmount = amount.mul(addresses.length); require(balanceOf[msg.sender] >= totalAmount); for (uint j = 0; j < addresses.length; j++) { require(addresses[j] != 0x0 && frozenAccount[addresses[j]] == false && now > unlockUnixTime[addresses[j]]); balanceOf[addresses[j]] = balanceOf[addresses[j]].add(amount); Transfer(msg.sender, addresses[j], amount); } balanceOf[msg.sender] = balanceOf[msg.sender].sub(totalAmount); return true; }
1,405,269
// SPDX-License-Identifier: AGPL-3.0 pragma solidity 0.6.12; pragma experimental ABIEncoderV2; // Global Enums and Structs struct StrategyParams { uint256 performanceFee; uint256 activation; uint256 debtRatio; uint256 minDebtPerHarvest; uint256 maxDebtPerHarvest; uint256 lastReport; uint256 totalDebt; uint256 totalGain; uint256 totalLoss; } // Part: ICurveFi interface ICurveFi { function get_virtual_price() external view returns (uint256); function add_liquidity( // EURt uint256[2] calldata amounts, uint256 min_mint_amount ) external payable; function add_liquidity( // Compound, sAave uint256[2] calldata amounts, uint256 min_mint_amount, bool _use_underlying ) external payable returns (uint256); function add_liquidity( // Iron Bank, Aave uint256[3] calldata amounts, uint256 min_mint_amount, bool _use_underlying ) external payable returns (uint256); function add_liquidity( // 3Crv Metapools address pool, uint256[4] calldata amounts, uint256 min_mint_amount ) external; function add_liquidity( // Y and yBUSD uint256[4] calldata amounts, uint256 min_mint_amount, bool _use_underlying ) external payable returns (uint256); function add_liquidity( // 3pool uint256[3] calldata amounts, uint256 min_mint_amount ) external payable; function add_liquidity( // sUSD uint256[4] calldata amounts, uint256 min_mint_amount ) external payable; function remove_liquidity_imbalance( uint256[2] calldata amounts, uint256 max_burn_amount ) external; function remove_liquidity(uint256 _amount, uint256[2] calldata amounts) external; function remove_liquidity_one_coin( uint256 _token_amount, int128 i, uint256 min_amount ) external; function exchange( int128 from, int128 to, uint256 _from_amount, uint256 _min_to_amount ) external; function balances(uint256) external view returns (uint256); function get_dy( int128 from, int128 to, uint256 _from_amount ) external view returns (uint256); // EURt function calc_token_amount(uint256[2] calldata _amounts, bool _is_deposit) external view returns (uint256); // 3Crv Metapools function calc_token_amount( address _pool, uint256[4] calldata _amounts, bool _is_deposit ) external view returns (uint256); // sUSD, Y pool, etc function calc_token_amount(uint256[4] calldata _amounts, bool _is_deposit) external view returns (uint256); // 3pool, Iron Bank, etc function calc_token_amount(uint256[3] calldata _amounts, bool _is_deposit) external view returns (uint256); function calc_withdraw_one_coin(uint256 amount, int128 i) external view returns (uint256); } // Part: ICurveStrategyProxy interface ICurveStrategyProxy { function proxy() external returns (address); function balanceOf(address _gauge) external view returns (uint256); function deposit(address _gauge, address _token) external; function withdraw( address _gauge, address _token, uint256 _amount ) external returns (uint256); function withdrawAll(address _gauge, address _token) external returns (uint256); function harvest(address _gauge) external; function lock() external; function approveStrategy(address) external; function revokeStrategy(address) external; function claimRewards(address _gauge, address _token) external; } // Part: IUniswapV2Router01 interface IUniswapV2Router01 { function factory() external pure returns (address); function WETH() external pure returns (address); function addLiquidity( address tokenA, address tokenB, uint256 amountADesired, uint256 amountBDesired, uint256 amountAMin, uint256 amountBMin, address to, uint256 deadline ) external returns ( uint256 amountA, uint256 amountB, uint256 liquidity ); function addLiquidityETH( address token, uint256 amountTokenDesired, uint256 amountTokenMin, uint256 amountETHMin, address to, uint256 deadline ) external payable returns ( uint256 amountToken, uint256 amountETH, uint256 liquidity ); function removeLiquidity( address tokenA, address tokenB, uint256 liquidity, uint256 amountAMin, uint256 amountBMin, address to, uint256 deadline ) external returns (uint256 amountA, uint256 amountB); function removeLiquidityETH( address token, uint256 liquidity, uint256 amountTokenMin, uint256 amountETHMin, address to, uint256 deadline ) external returns (uint256 amountToken, uint256 amountETH); function removeLiquidityWithPermit( address tokenA, address tokenB, uint256 liquidity, uint256 amountAMin, uint256 amountBMin, address to, uint256 deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external returns (uint256 amountA, uint256 amountB); function removeLiquidityETHWithPermit( address token, uint256 liquidity, uint256 amountTokenMin, uint256 amountETHMin, address to, uint256 deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external returns (uint256 amountToken, uint256 amountETH); function swapExactTokensForTokens( uint256 amountIn, uint256 amountOutMin, address[] calldata path, address to, uint256 deadline ) external returns (uint256[] memory amounts); function swapTokensForExactTokens( uint256 amountOut, uint256 amountInMax, address[] calldata path, address to, uint256 deadline ) external returns (uint256[] memory amounts); function swapExactETHForTokens( uint256 amountOutMin, address[] calldata path, address to, uint256 deadline ) external payable returns (uint256[] memory amounts); function swapTokensForExactETH( uint256 amountOut, uint256 amountInMax, address[] calldata path, address to, uint256 deadline ) external returns (uint256[] memory amounts); function swapExactTokensForETH( uint256 amountIn, uint256 amountOutMin, address[] calldata path, address to, uint256 deadline ) external returns (uint256[] memory amounts); function swapETHForExactTokens( uint256 amountOut, address[] calldata path, address to, uint256 deadline ) external payable returns (uint256[] memory amounts); function quote( uint256 amountA, uint256 reserveA, uint256 reserveB ) external pure returns (uint256 amountB); function getAmountOut( uint256 amountIn, uint256 reserveIn, uint256 reserveOut ) external pure returns (uint256 amountOut); function getAmountIn( uint256 amountOut, uint256 reserveIn, uint256 reserveOut ) external pure returns (uint256 amountIn); function getAmountsOut(uint256 amountIn, address[] calldata path) external view returns (uint256[] memory amounts); function getAmountsIn(uint256 amountOut, address[] calldata path) external view returns (uint256[] memory amounts); } // 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) { // 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); } } } } // 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]/Math /** * @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); } } // 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, 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; } } // Part: yearn/[email protected]/HealthCheck interface HealthCheck { function check( uint256 profit, uint256 loss, uint256 debtPayment, uint256 debtOutstanding, uint256 totalDebt ) external view returns (bool); } // Part: IUniswapV2Router02 interface IUniswapV2Router02 is IUniswapV2Router01 { function removeLiquidityETHSupportingFeeOnTransferTokens( address token, uint256 liquidity, uint256 amountTokenMin, uint256 amountETHMin, address to, uint256 deadline ) external returns (uint256 amountETH); function removeLiquidityETHWithPermitSupportingFeeOnTransferTokens( address token, uint256 liquidity, uint256 amountTokenMin, uint256 amountETHMin, address to, uint256 deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external returns (uint256 amountETH); function swapExactTokensForTokensSupportingFeeOnTransferTokens( uint256 amountIn, uint256 amountOutMin, address[] calldata path, address to, uint256 deadline ) external; function swapExactETHForTokensSupportingFeeOnTransferTokens( uint256 amountOutMin, address[] calldata path, address to, uint256 deadline ) external payable; function swapExactTokensForETHSupportingFeeOnTransferTokens( uint256 amountIn, uint256 amountOutMin, address[] calldata path, address to, uint256 deadline ) external; } // 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: yearn/[email protected]/VaultAPI interface VaultAPI is IERC20 { function name() external view returns (string calldata); function symbol() external view returns (string calldata); function decimals() external view returns (uint256); function apiVersion() external pure returns (string memory); function permit( address owner, address spender, uint256 amount, uint256 expiry, bytes calldata signature ) external returns (bool); // NOTE: Vyper produces multiple signatures for a given function with "default" args function deposit() external returns (uint256); function deposit(uint256 amount) external returns (uint256); function deposit(uint256 amount, address recipient) external returns (uint256); // NOTE: Vyper produces multiple signatures for a given function with "default" args function withdraw() external returns (uint256); function withdraw(uint256 maxShares) external returns (uint256); function withdraw(uint256 maxShares, address recipient) external returns (uint256); function token() external view returns (address); function strategies(address _strategy) external view returns (StrategyParams memory); function pricePerShare() external view returns (uint256); function totalAssets() external view returns (uint256); function depositLimit() external view returns (uint256); function maxAvailableShares() external view returns (uint256); /** * View how much the Vault would increase this Strategy's borrow limit, * based on its present performance (since its last report). Can be used to * determine expectedReturn in your Strategy. */ function creditAvailable() external view returns (uint256); /** * View how much the Vault would like to pull back from the Strategy, * based on its present performance (since its last report). Can be used to * determine expectedReturn in your Strategy. */ function debtOutstanding() external view returns (uint256); /** * View how much the Vault expect this Strategy to return at the current * block, based on its present performance (since its last report). Can be * used to determine expectedReturn in your Strategy. */ function expectedReturn() external view returns (uint256); /** * This is the main contact point where the Strategy interacts with the * Vault. It is critical that this call is handled as intended by the * Strategy. Therefore, this function will be called by BaseStrategy to * make sure the integration is correct. */ function report( uint256 _gain, uint256 _loss, uint256 _debtPayment ) external returns (uint256); /** * This function should only be used in the scenario where the Strategy is * being retired but no migration of the positions are possible, or in the * extreme scenario that the Strategy needs to be put into "Emergency Exit" * mode in order for it to exit as quickly as possible. The latter scenario * could be for any reason that is considered "critical" that the Strategy * exits its position as fast as possible, such as a sudden change in * market conditions leading to losses, or an imminent failure in an * external dependency. */ function revokeStrategy() external; /** * View the governance address of the Vault to assert privileged functions * can only be called by governance. The Strategy serves the Vault, so it * is subject to governance defined by the Vault. */ function governance() external view returns (address); /** * View the management address of the Vault to assert privileged functions * can only be called by management. The Strategy serves the Vault, so it * is subject to management defined by the Vault. */ function management() external view returns (address); /** * View the guardian address of the Vault to assert privileged functions * can only be called by guardian. The Strategy serves the Vault, so it * is subject to guardian defined by the Vault. */ function guardian() external view returns (address); } // Part: yearn/[email protected]/BaseStrategy /** * @title Yearn Base Strategy * @author yearn.finance * @notice * BaseStrategy implements all of the required functionality to interoperate * closely with the Vault contract. This contract should be inherited and the * abstract methods implemented to adapt the Strategy to the particular needs * it has to create a return. * * Of special interest is the relationship between `harvest()` and * `vault.report()'. `harvest()` may be called simply because enough time has * elapsed since the last report, and not because any funds need to be moved * or positions adjusted. This is critical so that the Vault may maintain an * accurate picture of the Strategy's performance. See `vault.report()`, * `harvest()`, and `harvestTrigger()` for further details. */ abstract contract BaseStrategy { using SafeMath for uint256; using SafeERC20 for IERC20; string public metadataURI; // health checks bool public doHealthCheck; address public healthCheck; /** * @notice * Used to track which version of `StrategyAPI` this Strategy * implements. * @dev The Strategy's version must match the Vault's `API_VERSION`. * @return A string which holds the current API version of this contract. */ function apiVersion() public pure returns (string memory) { return "0.4.3"; } /** * @notice This Strategy's name. * @dev * You can use this field to manage the "version" of this Strategy, e.g. * `StrategySomethingOrOtherV1`. However, "API Version" is managed by * `apiVersion()` function above. * @return This Strategy's name. */ function name() external view virtual returns (string memory); /** * @notice * The amount (priced in want) of the total assets managed by this strategy should not count * towards Yearn's TVL calculations. * @dev * You can override this field to set it to a non-zero value if some of the assets of this * Strategy is somehow delegated inside another part of of Yearn's ecosystem e.g. another Vault. * Note that this value must be strictly less than or equal to the amount provided by * `estimatedTotalAssets()` below, as the TVL calc will be total assets minus delegated assets. * Also note that this value is used to determine the total assets under management by this * strategy, for the purposes of computing the management fee in `Vault` * @return * The amount of assets this strategy manages that should not be included in Yearn's Total Value * Locked (TVL) calculation across it's ecosystem. */ function delegatedAssets() external view virtual returns (uint256) { return 0; } VaultAPI public vault; address public strategist; address public rewards; address public keeper; IERC20 public want; // So indexers can keep track of this event Harvested(uint256 profit, uint256 loss, uint256 debtPayment, uint256 debtOutstanding); event UpdatedStrategist(address newStrategist); event UpdatedKeeper(address newKeeper); event UpdatedRewards(address rewards); event UpdatedMinReportDelay(uint256 delay); event UpdatedMaxReportDelay(uint256 delay); event UpdatedProfitFactor(uint256 profitFactor); event UpdatedDebtThreshold(uint256 debtThreshold); event EmergencyExitEnabled(); event UpdatedMetadataURI(string metadataURI); // The minimum number of seconds between harvest calls. See // `setMinReportDelay()` for more details. uint256 public minReportDelay; // The maximum number of seconds between harvest calls. See // `setMaxReportDelay()` for more details. uint256 public maxReportDelay; // The minimum multiple that `callCost` must be above the credit/profit to // be "justifiable". See `setProfitFactor()` for more details. uint256 public profitFactor; // Use this to adjust the threshold at which running a debt causes a // harvest trigger. See `setDebtThreshold()` for more details. uint256 public debtThreshold; // See note on `setEmergencyExit()`. bool public emergencyExit; // modifiers modifier onlyAuthorized() { require(msg.sender == strategist || msg.sender == governance(), "!authorized"); _; } modifier onlyEmergencyAuthorized() { require( msg.sender == strategist || msg.sender == governance() || msg.sender == vault.guardian() || msg.sender == vault.management(), "!authorized" ); _; } modifier onlyStrategist() { require(msg.sender == strategist, "!strategist"); _; } modifier onlyGovernance() { require(msg.sender == governance(), "!authorized"); _; } modifier onlyKeepers() { require( msg.sender == keeper || msg.sender == strategist || msg.sender == governance() || msg.sender == vault.guardian() || msg.sender == vault.management(), "!authorized" ); _; } modifier onlyVaultManagers() { require(msg.sender == vault.management() || msg.sender == governance(), "!authorized"); _; } constructor(address _vault) public { _initialize(_vault, msg.sender, msg.sender, msg.sender); } /** * @notice * Initializes the Strategy, this is called only once, when the * contract is deployed. * @dev `_vault` should implement `VaultAPI`. * @param _vault The address of the Vault responsible for this Strategy. * @param _strategist The address to assign as `strategist`. * The strategist is able to change the reward address * @param _rewards The address to use for pulling rewards. * @param _keeper The adddress of the _keeper. _keeper * can harvest and tend a strategy. */ function _initialize( address _vault, address _strategist, address _rewards, address _keeper ) internal { require(address(want) == address(0), "Strategy already initialized"); vault = VaultAPI(_vault); want = IERC20(vault.token()); want.safeApprove(_vault, uint256(-1)); // Give Vault unlimited access (might save gas) strategist = _strategist; rewards = _rewards; keeper = _keeper; // initialize variables minReportDelay = 0; maxReportDelay = 86400; profitFactor = 100; debtThreshold = 0; vault.approve(rewards, uint256(-1)); // Allow rewards to be pulled } function setHealthCheck(address _healthCheck) external onlyVaultManagers { healthCheck = _healthCheck; } function setDoHealthCheck(bool _doHealthCheck) external onlyVaultManagers { doHealthCheck = _doHealthCheck; } /** * @notice * Used to change `strategist`. * * This may only be called by governance or the existing strategist. * @param _strategist The new address to assign as `strategist`. */ function setStrategist(address _strategist) external onlyAuthorized { require(_strategist != address(0)); strategist = _strategist; emit UpdatedStrategist(_strategist); } /** * @notice * Used to change `keeper`. * * `keeper` is the only address that may call `tend()` or `harvest()`, * other than `governance()` or `strategist`. However, unlike * `governance()` or `strategist`, `keeper` may *only* call `tend()` * and `harvest()`, and no other authorized functions, following the * principle of least privilege. * * This may only be called by governance or the strategist. * @param _keeper The new address to assign as `keeper`. */ function setKeeper(address _keeper) external onlyAuthorized { require(_keeper != address(0)); keeper = _keeper; emit UpdatedKeeper(_keeper); } /** * @notice * Used to change `rewards`. EOA or smart contract which has the permission * to pull rewards from the vault. * * This may only be called by the strategist. * @param _rewards The address to use for pulling rewards. */ function setRewards(address _rewards) external onlyStrategist { require(_rewards != address(0)); vault.approve(rewards, 0); rewards = _rewards; vault.approve(rewards, uint256(-1)); emit UpdatedRewards(_rewards); } /** * @notice * Used to change `minReportDelay`. `minReportDelay` is the minimum number * of blocks that should pass for `harvest()` to be called. * * For external keepers (such as the Keep3r network), this is the minimum * time between jobs to wait. (see `harvestTrigger()` * for more details.) * * This may only be called by governance or the strategist. * @param _delay The minimum number of seconds to wait between harvests. */ function setMinReportDelay(uint256 _delay) external onlyAuthorized { minReportDelay = _delay; emit UpdatedMinReportDelay(_delay); } /** * @notice * Used to change `maxReportDelay`. `maxReportDelay` is the maximum number * of blocks that should pass for `harvest()` to be called. * * For external keepers (such as the Keep3r network), this is the maximum * time between jobs to wait. (see `harvestTrigger()` * for more details.) * * This may only be called by governance or the strategist. * @param _delay The maximum number of seconds to wait between harvests. */ function setMaxReportDelay(uint256 _delay) external onlyAuthorized { maxReportDelay = _delay; emit UpdatedMaxReportDelay(_delay); } /** * @notice * Used to change `profitFactor`. `profitFactor` is used to determine * if it's worthwhile to harvest, given gas costs. (See `harvestTrigger()` * for more details.) * * This may only be called by governance or the strategist. * @param _profitFactor A ratio to multiply anticipated * `harvest()` gas cost against. */ function setProfitFactor(uint256 _profitFactor) external onlyAuthorized { profitFactor = _profitFactor; emit UpdatedProfitFactor(_profitFactor); } /** * @notice * Sets how far the Strategy can go into loss without a harvest and report * being required. * * By default this is 0, meaning any losses would cause a harvest which * will subsequently report the loss to the Vault for tracking. (See * `harvestTrigger()` for more details.) * * This may only be called by governance or the strategist. * @param _debtThreshold How big of a loss this Strategy may carry without * being required to report to the Vault. */ function setDebtThreshold(uint256 _debtThreshold) external onlyAuthorized { debtThreshold = _debtThreshold; emit UpdatedDebtThreshold(_debtThreshold); } /** * @notice * Used to change `metadataURI`. `metadataURI` is used to store the URI * of the file describing the strategy. * * This may only be called by governance or the strategist. * @param _metadataURI The URI that describe the strategy. */ function setMetadataURI(string calldata _metadataURI) external onlyAuthorized { metadataURI = _metadataURI; emit UpdatedMetadataURI(_metadataURI); } /** * Resolve governance address from Vault contract, used to make assertions * on protected functions in the Strategy. */ function governance() internal view returns (address) { return vault.governance(); } /** * @notice * Provide an accurate conversion from `_amtInWei` (denominated in wei) * to `want` (using the native decimal characteristics of `want`). * @dev * Care must be taken when working with decimals to assure that the conversion * is compatible. As an example: * * given 1e17 wei (0.1 ETH) as input, and want is USDC (6 decimals), * with USDC/ETH = 1800, this should give back 1800000000 (180 USDC) * * @param _amtInWei The amount (in wei/1e-18 ETH) to convert to `want` * @return The amount in `want` of `_amtInEth` converted to `want` **/ function ethToWant(uint256 _amtInWei) public view virtual returns (uint256); /** * @notice * Provide an accurate estimate for the total amount of assets * (principle + return) that this Strategy is currently managing, * denominated in terms of `want` tokens. * * This total should be "realizable" e.g. the total value that could * *actually* be obtained from this Strategy if it were to divest its * entire position based on current on-chain conditions. * @dev * Care must be taken in using this function, since it relies on external * systems, which could be manipulated by the attacker to give an inflated * (or reduced) value produced by this function, based on current on-chain * conditions (e.g. this function is possible to influence through * flashloan attacks, oracle manipulations, or other DeFi attack * mechanisms). * * It is up to governance to use this function to correctly order this * Strategy relative to its peers in the withdrawal queue to minimize * losses for the Vault based on sudden withdrawals. This value should be * higher than the total debt of the Strategy and higher than its expected * value to be "safe". * @return The estimated total assets in this Strategy. */ function estimatedTotalAssets() public view virtual returns (uint256); /* * @notice * Provide an indication of whether this strategy is currently "active" * in that it is managing an active position, or will manage a position in * the future. This should correlate to `harvest()` activity, so that Harvest * events can be tracked externally by indexing agents. * @return True if the strategy is actively managing a position. */ function isActive() public view returns (bool) { return vault.strategies(address(this)).debtRatio > 0 || estimatedTotalAssets() > 0; } /** * Perform any Strategy unwinding or other calls necessary to capture the * "free return" this Strategy has generated since the last time its core * position(s) were adjusted. Examples include unwrapping extra rewards. * This call is only used during "normal operation" of a Strategy, and * should be optimized to minimize losses as much as possible. * * This method returns any realized profits and/or realized losses * incurred, and should return the total amounts of profits/losses/debt * payments (in `want` tokens) for the Vault's accounting (e.g. * `want.balanceOf(this) >= _debtPayment + _profit`). * * `_debtOutstanding` will be 0 if the Strategy is not past the configured * debt limit, otherwise its value will be how far past the debt limit * the Strategy is. The Strategy's debt limit is configured in the Vault. * * NOTE: `_debtPayment` should be less than or equal to `_debtOutstanding`. * It is okay for it to be less than `_debtOutstanding`, as that * should only used as a guide for how much is left to pay back. * Payments should be made to minimize loss from slippage, debt, * withdrawal fees, etc. * * See `vault.debtOutstanding()`. */ function prepareReturn(uint256 _debtOutstanding) internal virtual returns ( uint256 _profit, uint256 _loss, uint256 _debtPayment ); /** * Perform any adjustments to the core position(s) of this Strategy given * what change the Vault made in the "investable capital" available to the * Strategy. Note that all "free capital" in the Strategy after the report * was made is available for reinvestment. Also note that this number * could be 0, and you should handle that scenario accordingly. * * See comments regarding `_debtOutstanding` on `prepareReturn()`. */ function adjustPosition(uint256 _debtOutstanding) internal virtual; /** * Liquidate up to `_amountNeeded` of `want` of this strategy's positions, * irregardless of slippage. Any excess will be re-invested with `adjustPosition()`. * This function should return the amount of `want` tokens made available by the * liquidation. If there is a difference between them, `_loss` indicates whether the * difference is due to a realized loss, or if there is some other sitution at play * (e.g. locked funds) where the amount made available is less than what is needed. * * NOTE: The invariant `_liquidatedAmount + _loss <= _amountNeeded` should always be maintained */ function liquidatePosition(uint256 _amountNeeded) internal virtual returns (uint256 _liquidatedAmount, uint256 _loss); /** * Liquidate everything and returns the amount that got freed. * This function is used during emergency exit instead of `prepareReturn()` to * liquidate all of the Strategy's positions back to the Vault. */ function liquidateAllPositions() internal virtual returns (uint256 _amountFreed); /** * @notice * Provide a signal to the keeper that `tend()` should be called. The * keeper will provide the estimated gas cost that they would pay to call * `tend()`, and this function should use that estimate to make a * determination if calling it is "worth it" for the keeper. This is not * the only consideration into issuing this trigger, for example if the * position would be negatively affected if `tend()` is not called * shortly, then this can return `true` even if the keeper might be * "at a loss" (keepers are always reimbursed by Yearn). * @dev * `callCostInWei` must be priced in terms of `wei` (1e-18 ETH). * * This call and `harvestTrigger()` should never return `true` at the same * time. * @param callCostInWei The keeper's estimated gas cost to call `tend()` (in wei). * @return `true` if `tend()` should be called, `false` otherwise. */ function tendTrigger(uint256 callCostInWei) public view virtual returns (bool) { // We usually don't need tend, but if there are positions that need // active maintainence, overriding this function is how you would // signal for that. // If your implementation uses the cost of the call in want, you can // use uint256 callCost = ethToWant(callCostInWei); return false; } /** * @notice * Adjust the Strategy's position. The purpose of tending isn't to * realize gains, but to maximize yield by reinvesting any returns. * * See comments on `adjustPosition()`. * * This may only be called by governance, the strategist, or the keeper. */ function tend() external onlyKeepers { // Don't take profits with this call, but adjust for better gains adjustPosition(vault.debtOutstanding()); } /** * @notice * Provide a signal to the keeper that `harvest()` should be called. The * keeper will provide the estimated gas cost that they would pay to call * `harvest()`, and this function should use that estimate to make a * determination if calling it is "worth it" for the keeper. This is not * the only consideration into issuing this trigger, for example if the * position would be negatively affected if `harvest()` is not called * shortly, then this can return `true` even if the keeper might be "at a * loss" (keepers are always reimbursed by Yearn). * @dev * `callCostInWei` must be priced in terms of `wei` (1e-18 ETH). * * This call and `tendTrigger` should never return `true` at the * same time. * * See `min/maxReportDelay`, `profitFactor`, `debtThreshold` to adjust the * strategist-controlled parameters that will influence whether this call * returns `true` or not. These parameters will be used in conjunction * with the parameters reported to the Vault (see `params`) to determine * if calling `harvest()` is merited. * * It is expected that an external system will check `harvestTrigger()`. * This could be a script run off a desktop or cloud bot (e.g. * https://github.com/iearn-finance/yearn-vaults/blob/main/scripts/keep.py), * or via an integration with the Keep3r network (e.g. * https://github.com/Macarse/GenericKeep3rV2/blob/master/contracts/keep3r/GenericKeep3rV2.sol). * @param callCostInWei The keeper's estimated gas cost to call `harvest()` (in wei). * @return `true` if `harvest()` should be called, `false` otherwise. */ function harvestTrigger(uint256 callCostInWei) public view virtual returns (bool) { uint256 callCost = ethToWant(callCostInWei); StrategyParams memory params = vault.strategies(address(this)); // Should not trigger if Strategy is not activated if (params.activation == 0) return false; // Should not trigger if we haven't waited long enough since previous harvest if (block.timestamp.sub(params.lastReport) < minReportDelay) return false; // Should trigger if hasn't been called in a while if (block.timestamp.sub(params.lastReport) >= maxReportDelay) return true; // If some amount is owed, pay it back // NOTE: Since debt is based on deposits, it makes sense to guard against large // changes to the value from triggering a harvest directly through user // behavior. This should ensure reasonable resistance to manipulation // from user-initiated withdrawals as the outstanding debt fluctuates. uint256 outstanding = vault.debtOutstanding(); if (outstanding > debtThreshold) return true; // Check for profits and losses uint256 total = estimatedTotalAssets(); // Trigger if we have a loss to report if (total.add(debtThreshold) < params.totalDebt) return true; uint256 profit = 0; if (total > params.totalDebt) profit = total.sub(params.totalDebt); // We've earned a profit! // Otherwise, only trigger if it "makes sense" economically (gas cost // is <N% of value moved) uint256 credit = vault.creditAvailable(); return (profitFactor.mul(callCost) < credit.add(profit)); } /** * @notice * Harvests the Strategy, recognizing any profits or losses and adjusting * the Strategy's position. * * In the rare case the Strategy is in emergency shutdown, this will exit * the Strategy's position. * * This may only be called by governance, the strategist, or the keeper. * @dev * When `harvest()` is called, the Strategy reports to the Vault (via * `vault.report()`), so in some cases `harvest()` must be called in order * to take in profits, to borrow newly available funds from the Vault, or * otherwise adjust its position. In other cases `harvest()` must be * called to report to the Vault on the Strategy's position, especially if * any losses have occurred. */ function harvest() external onlyKeepers { uint256 profit = 0; uint256 loss = 0; uint256 debtOutstanding = vault.debtOutstanding(); uint256 debtPayment = 0; if (emergencyExit) { // Free up as much capital as possible uint256 amountFreed = liquidateAllPositions(); if (amountFreed < debtOutstanding) { loss = debtOutstanding.sub(amountFreed); } else if (amountFreed > debtOutstanding) { profit = amountFreed.sub(debtOutstanding); } debtPayment = debtOutstanding.sub(loss); } else { // Free up returns for Vault to pull (profit, loss, debtPayment) = prepareReturn(debtOutstanding); } // Allow Vault to take up to the "harvested" balance of this contract, // which is the amount it has earned since the last time it reported to // the Vault. uint256 totalDebt = vault.strategies(address(this)).totalDebt; debtOutstanding = vault.report(profit, loss, debtPayment); // Check if free returns are left, and re-invest them adjustPosition(debtOutstanding); // call healthCheck contract if (doHealthCheck && healthCheck != address(0)) { require(HealthCheck(healthCheck).check(profit, loss, debtPayment, debtOutstanding, totalDebt), "!healthcheck"); } else { doHealthCheck = true; } emit Harvested(profit, loss, debtPayment, debtOutstanding); } /** * @notice * Withdraws `_amountNeeded` to `vault`. * * This may only be called by the Vault. * @param _amountNeeded How much `want` to withdraw. * @return _loss Any realized losses */ function withdraw(uint256 _amountNeeded) external returns (uint256 _loss) { require(msg.sender == address(vault), "!vault"); // Liquidate as much as possible to `want`, up to `_amountNeeded` uint256 amountFreed; (amountFreed, _loss) = liquidatePosition(_amountNeeded); // Send it directly back (NOTE: Using `msg.sender` saves some gas here) want.safeTransfer(msg.sender, amountFreed); // NOTE: Reinvest anything leftover on next `tend`/`harvest` } /** * Do anything necessary to prepare this Strategy for migration, such as * transferring any reserve or LP tokens, CDPs, or other tokens or stores of * value. */ function prepareMigration(address _newStrategy) internal virtual; /** * @notice * Transfers all `want` from this Strategy to `_newStrategy`. * * This may only be called by the Vault. * @dev * The new Strategy's Vault must be the same as this Strategy's Vault. * The migration process should be carefully performed to make sure all * the assets are migrated to the new address, which should have never * interacted with the vault before. * @param _newStrategy The Strategy to migrate to. */ function migrate(address _newStrategy) external { require(msg.sender == address(vault)); require(BaseStrategy(_newStrategy).vault() == vault); prepareMigration(_newStrategy); want.safeTransfer(_newStrategy, want.balanceOf(address(this))); } /** * @notice * Activates emergency exit. Once activated, the Strategy will exit its * position upon the next harvest, depositing all funds into the Vault as * quickly as is reasonable given on-chain conditions. * * This may only be called by governance or the strategist. * @dev * See `vault.setEmergencyShutdown()` and `harvest()` for further details. */ function setEmergencyExit() external onlyEmergencyAuthorized { emergencyExit = true; vault.revokeStrategy(); emit EmergencyExitEnabled(); } /** * Override this to add all tokens/tokenized positions this contract * manages on a *persistent* basis (e.g. not just for swapping back to * want ephemerally). * * NOTE: Do *not* include `want`, already included in `sweep` below. * * Example: * ``` * function protectedTokens() internal override view returns (address[] memory) { * address[] memory protected = new address[](3); * protected[0] = tokenA; * protected[1] = tokenB; * protected[2] = tokenC; * return protected; * } * ``` */ function protectedTokens() internal view virtual returns (address[] memory); /** * @notice * Removes tokens from this Strategy that are not the type of tokens * managed by this Strategy. This may be used in case of accidentally * sending the wrong kind of token to this Strategy. * * Tokens will be sent to `governance()`. * * This will fail if an attempt is made to sweep `want`, or any tokens * that are protected by this Strategy. * * This may only be called by governance. * @dev * Implement `protectedTokens()` to specify any additional tokens that * should be protected from sweeping in addition to `want`. * @param _token The token to transfer out of this vault. */ function sweep(address _token) external onlyGovernance { require(_token != address(want), "!want"); require(_token != address(vault), "!shares"); address[] memory _protectedTokens = protectedTokens(); for (uint256 i; i < _protectedTokens.length; i++) require(_token != _protectedTokens[i], "!protected"); IERC20(_token).safeTransfer(governance(), IERC20(_token).balanceOf(address(this))); } } // Part: StrategyCurveBase abstract contract StrategyCurveBase is BaseStrategy { using SafeERC20 for IERC20; using Address for address; using SafeMath for uint256; /* ========== STATE VARIABLES ========== */ // these should stay the same across different wants. // curve infrastructure contracts ICurveStrategyProxy public proxy; // Below we set it to Yearn's Updated v4 StrategyProxy ICurveFi public curve; // Curve Pool, need this for depositing into our curve pool address public gauge; // Curve gauge contract, most are tokenized, held by Yearn's voter // keepCRV stuff uint256 public keepCRV; // the percentage of CRV we re-lock for boost (in basis points) uint256 public constant FEE_DENOMINATOR = 10000; // this means all of our fee values are in bips address public constant voter = 0xF147b8125d2ef93FB6965Db97D6746952a133934; // Yearn's veCRV voter // swap stuff address public constant sushiswap = 0xd9e1cE17f2641f24aE83637ab66a2cca9C378B9F; // default to sushiswap, more CRV liquidity there address[] public crvPath; IERC20 public constant crv = IERC20(0xD533a949740bb3306d119CC777fa900bA034cd52); IERC20 public constant weth = IERC20(0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2); bool internal forceHarvestTriggerOnce; // only set this to true externally when we want to trigger our keepers to harvest for us string internal stratName; // set our strategy name here /* ========== CONSTRUCTOR ========== */ constructor(address _vault) public BaseStrategy(_vault) {} /* ========== VIEWS ========== */ function name() external view override returns (string memory) { return stratName; } function stakedBalance() public view returns (uint256) { return proxy.balanceOf(gauge); } function balanceOfWant() public view returns (uint256) { return want.balanceOf(address(this)); } function estimatedTotalAssets() public view override returns (uint256) { return balanceOfWant().add(stakedBalance()); } /* ========== MUTATIVE FUNCTIONS ========== */ // these should stay the same across different wants. function adjustPosition(uint256 _debtOutstanding) internal override { if (emergencyExit) { return; } // Send all of our LP tokens to the proxy and deposit to the gauge if we have any uint256 _toInvest = balanceOfWant(); if (_toInvest > 0) { want.safeTransfer(address(proxy), _toInvest); proxy.deposit(gauge, address(want)); } } function liquidatePosition(uint256 _amountNeeded) internal override returns (uint256 _liquidatedAmount, uint256 _loss) { uint256 _wantBal = balanceOfWant(); if (_amountNeeded > _wantBal) { // check if we have enough free funds to cover the withdrawal uint256 _stakedBal = stakedBalance(); if (_stakedBal > 0) { proxy.withdraw( gauge, address(want), Math.min(_stakedBal, _amountNeeded.sub(_wantBal)) ); } uint256 _withdrawnBal = balanceOfWant(); _liquidatedAmount = Math.min(_amountNeeded, _withdrawnBal); _loss = _amountNeeded.sub(_liquidatedAmount); } else { // we have enough balance to cover the liquidation available return (_amountNeeded, 0); } } // fire sale, get rid of it all! function liquidateAllPositions() internal override returns (uint256) { uint256 _stakedBal = stakedBalance(); if (_stakedBal > 0) { // don't bother withdrawing zero proxy.withdraw(gauge, address(want), _stakedBal); } return balanceOfWant(); } function prepareMigration(address _newStrategy) internal override { uint256 _stakedBal = stakedBalance(); if (_stakedBal > 0) { proxy.withdraw(gauge, address(want), _stakedBal); } } function protectedTokens() internal view override returns (address[] memory) {} /* ========== KEEP3RS ========== */ function harvestTrigger(uint256 callCostinEth) public view override returns (bool) { // trigger if we want to manually harvest if (forceHarvestTriggerOnce) { return true; } // Should not trigger if strategy is not active (no assets and no debtRatio). This means we don't need to adjust keeper job. if (!isActive()) { return false; } return super.harvestTrigger(callCostinEth); } /* ========== SETTERS ========== */ // These functions are useful for setting parameters of the strategy that may need to be adjusted. // Use to update Yearn's StrategyProxy contract as needed in case of upgrades. function setProxy(address _proxy) external onlyGovernance { proxy = ICurveStrategyProxy(_proxy); } // Set the amount of CRV to be locked in Yearn's veCRV voter from each harvest. Default is 10%. function setKeepCRV(uint256 _keepCRV) external onlyAuthorized { require(_keepCRV <= 10_000); keepCRV = _keepCRV; } // This allows us to manually harvest with our keeper as needed function setForceHarvestTriggerOnce(bool _forceHarvestTriggerOnce) external onlyAuthorized { forceHarvestTriggerOnce = _forceHarvestTriggerOnce; } } // File: StrategyCurveibFFClonable.sol contract StrategyCurveibFFClonable is StrategyCurveBase { /* ========== STATE VARIABLES ========== */ // these will likely change across different wants. // swap stuff IERC20 public ibToken; // check for cloning bool internal isOriginal = true; /* ========== CONSTRUCTOR ========== */ constructor( address _vault, address _curvePool, address _gauge, address _ibToken, string memory _name ) public StrategyCurveBase(_vault) { _initializeStrat(_curvePool, _gauge, _ibToken, _name); } /* ========== CLONING ========== */ event Cloned(address indexed clone); // we use this to clone our original strategy to other vaults function cloneCurveibFF( address _vault, address _strategist, address _rewards, address _keeper, address _curvePool, address _gauge, address _ibToken, string memory _name ) external returns (address newStrategy) { require(isOriginal); // Copied from https://github.com/optionality/clone-factory/blob/master/contracts/CloneFactory.sol bytes20 addressBytes = bytes20(address(this)); assembly { // EIP-1167 bytecode let clone_code := mload(0x40) mstore( clone_code, 0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000000000000000000000 ) mstore(add(clone_code, 0x14), addressBytes) mstore( add(clone_code, 0x28), 0x5af43d82803e903d91602b57fd5bf30000000000000000000000000000000000 ) newStrategy := create(0, clone_code, 0x37) } StrategyCurveibFFClonable(newStrategy).initialize( _vault, _strategist, _rewards, _keeper, _curvePool, _gauge, _ibToken, _name ); emit Cloned(newStrategy); } // this will only be called by the clone function above function initialize( address _vault, address _strategist, address _rewards, address _keeper, address _curvePool, address _gauge, address _ibToken, string memory _name ) public { _initialize(_vault, _strategist, _rewards, _keeper); _initializeStrat(_curvePool, _gauge, _ibToken, _name); } // this is called by our original strategy, as well as any clones function _initializeStrat( address _curvePool, address _gauge, address _ibToken, string memory _name ) internal { // You can set these parameters on deployment to whatever you want maxReportDelay = 7 days; // 7 days in seconds debtThreshold = 5 * 1e18; // we shouldn't ever have debt, but set a bit of a buffer profitFactor = 10_000; // in this strategy, profitFactor is only used for telling keep3rs when to move funds from vault to strategy healthCheck = 0xDDCea799fF1699e98EDF118e0629A974Df7DF012; // health.ychad.eth // need to set our proxy again when cloning since it's not a constant proxy = ICurveStrategyProxy(0xA420A63BbEFfbda3B147d0585F1852C358e2C152); // these are our standard approvals. want = Curve LP token want.approve(address(proxy), type(uint256).max); crv.approve(sushiswap, type(uint256).max); // set our keepCRV keepCRV = 1000; // this is the pool specific to this vault, used for depositing curve = ICurveFi(_curvePool); // set our curve gauge contract gauge = address(_gauge); // set our strategy's name stratName = _name; // set our token to swap for and deposit with ibToken = IERC20(_ibToken); // these are our approvals and path specific to this contract ibToken.approve(address(curve), type(uint256).max); // crv token path crvPath = [address(crv), address(weth), address(ibToken)]; } /* ========== MUTATIVE FUNCTIONS ========== */ // these will likely change across different wants. function prepareReturn(uint256 _debtOutstanding) internal override returns ( uint256 _profit, uint256 _loss, uint256 _debtPayment ) { // if we have anything in the gauge, then harvest CRV from the gauge uint256 _stakedBal = stakedBalance(); if (_stakedBal > 0) { proxy.harvest(gauge); uint256 _crvBalance = crv.balanceOf(address(this)); // if we claimed any CRV, then sell it if (_crvBalance > 0) { // keep some of our CRV to increase our boost uint256 _sendToVoter = _crvBalance.mul(keepCRV).div(FEE_DENOMINATOR); if (keepCRV > 0) { crv.safeTransfer(voter, _sendToVoter); } uint256 _crvRemainder = _crvBalance.sub(_sendToVoter); // sell the rest of our CRV if (_crvRemainder > 0) { _sell(_crvRemainder); } // deposit our ibEUR to Curve if we have any uint256 _ibTokenBalance = ibToken.balanceOf(address(this)); if (_ibTokenBalance > 0) { curve.add_liquidity([_ibTokenBalance, 0], 0); } } } // debtOustanding will only be > 0 in the event of revoking or if we need to rebalance from a withdrawal or lowering the debtRatio if (_debtOutstanding > 0) { if (_stakedBal > 0) { // don't bother withdrawing if we don't have staked funds proxy.withdraw( gauge, address(want), Math.min(_stakedBal, _debtOutstanding) ); } uint256 _withdrawnBal = balanceOfWant(); _debtPayment = Math.min(_debtOutstanding, _withdrawnBal); } // serious loss should never happen, but if it does (for instance, if Curve is hacked), let's record it accurately uint256 assets = estimatedTotalAssets(); uint256 debt = vault.strategies(address(this)).totalDebt; // if assets are greater than debt, things are working great! if (assets > debt) { _profit = assets.sub(debt); uint256 _wantBal = balanceOfWant(); if (_profit.add(_debtPayment) > _wantBal) { // this should only be hit following donations to strategy liquidateAllPositions(); } } // if assets are less than debt, we are in trouble else { _loss = debt.sub(assets); } // we're done harvesting, so reset our trigger if we used it forceHarvestTriggerOnce = false; } // Sells our harvested CRV into the selected output. function _sell(uint256 _amount) internal { IUniswapV2Router02(sushiswap).swapExactTokensForTokens( _amount, uint256(0), crvPath, address(this), block.timestamp ); } /* ========== KEEP3RS ========== */ // convert our keeper's eth cost into want function ethToWant(uint256 _ethAmount) public view override returns (uint256) { uint256 callCostInWant; if (_ethAmount > 0) { address[] memory ethPath = new address[](2); ethPath[0] = address(weth); ethPath[1] = address(ibToken); uint256[] memory _callCostInIbTokenTuple = IUniswapV2Router02(sushiswap).getAmountsOut( _ethAmount, ethPath ); uint256 _callCostInIbToken = _callCostInIbTokenTuple[_callCostInIbTokenTuple.length - 1]; callCostInWant = curve.calc_token_amount( [_callCostInIbToken, 0], true ); } return callCostInWant; } }
========== KEEP3RS ========== / trigger if we want to manually harvest Should not trigger if strategy is not active (no assets and no debtRatio). This means we don't need to adjust keeper job.
function protectedTokens() internal view override returns (address[] memory) function harvestTrigger(uint256 callCostinEth) public view override returns (bool) { if (forceHarvestTriggerOnce) { return true; } if (!isActive()) { return false; } return super.harvestTrigger(callCostinEth); }
413,601
pragma solidity ^0.4.25; // It's important to avoid vulnerabilities due to numeric overflow bugs // OpenZeppelin's SafeMath library, when used correctly, protects agains such bugs // More info: https://www.nccgroup.trust/us/about-us/newsroom-and-events/blog/2018/november/smart-contract-insecurity-bad-arithmetic/ import "openzeppelin-solidity/contracts/math/SafeMath.sol"; import "./FlightSuretyData.sol"; /************************************************** */ /* FlightSurety Smart Contract */ /************************************************** */ contract FlightSuretyApp { using SafeMath for uint256; // Allow SafeMath functions to be called for all uint256 types (similar to "prototype" in Javascript) /********************************************************************************************/ /* DATA VARIABLES */ /********************************************************************************************/ bool private operational = true; // Blocks all state changes throughout the contract if false // Flight status codees uint8 private constant STATUS_CODE_UNKNOWN = 0; uint8 private constant STATUS_CODE_ON_TIME = 10; uint8 private constant STATUS_CODE_LATE_AIRLINE = 20; uint8 private constant STATUS_CODE_LATE_WEATHER = 30; uint8 private constant STATUS_CODE_LATE_TECHNICAL = 40; uint8 private constant STATUS_CODE_LATE_OTHER = 50; uint256 private AIRLINE_PARTICIPATION_FEE = 10 ether; uint256 private INSURANCE_PREMIUM = 1 ether; // uint256 private CONSENSUS = 4; //max number of airlines without consensus rule address private contractOwner; // Account used to deploy contract FlightSuretyData flightData; //data contract mapping(address => uint256) public votesPerAirline; mapping(address => mapping(address => bool)) public hasVoted; mapping(address => bool) public isInQueue; mapping(address => string) public airlineNames; /********************************************************************************************/ /* Events */ /********************************************************************************************/ event AirlineAddedToRegisterationQueue(address indexed airline, uint256 votesRatio); event AirlineRegisteredWithoutVotes(address indexed airline); event AirlineRegisteredWithVotes(address indexed airline, uint256 votes); event AirlineVoted(address indexed airlineVoting, address indexed airlineVoted); event AirlineFullyFunded(address indexed airline, uint256 value); event FlightRegistered(address indexed airline, string flightNumber, string timeStamp); event PassengerRegistered(address indexed passenger, string name, address airlineAddress, bytes32 key); event InsurancePurchased(address indexed passenger, bytes32 flightNumber, uint256 amount); /********************************************************************************************/ /* FUNCTION MODIFIERS */ /********************************************************************************************/ // Modifiers help avoid duplication of code. They are typically used to validate something // before a function is allowed to be executed. /** * @dev Modifier that requires the "operational" boolean variable to be "true" * This is used on all state changing functions to pause the contract in * the event there is an issue that needs to be fixed */ modifier isOperational() { // Modify to call data contract's status require(operational, "Contract is currently not operational"); _; // All modifiers require an "_" which indicates where the function body will be added } /** * @dev Modifier that requires the "ContractOwner" account to be the function caller */ modifier onlyContractOwner() { require(msg.sender == contractOwner, "Caller is not contract owner"); _; } modifier onlyRegisteredAirline(){ bool isRegistered; (,isRegistered,,)= flightData.getAirlineData(msg.sender); require(isRegistered, "Airline not registered"); _; } modifier addressNotUsed(address _address){ bool isAirlineRegistered; bool isPassengerRegistered; (,isAirlineRegistered,,)= flightData.getAirlineData(_address); (,isPassengerRegistered,) = flightData.getPassengerData(_address); require(!isAirlineRegistered, "This address is already taken by another airline"); require(!isPassengerRegistered, "This address is already taken by another passenger"); _; } modifier hasNotAlreadyVoted(address _airlineAddress) { // Modify to call data contract's status require(!hasVoted[msg.sender][_airlineAddress], "You have already voted on this airline"); _; // All modifiers require an "_" which indicates where the function body will be added } modifier onlyInQueue(address _airlineAddress) { // Modify to call data contract's status require(isInQueue[_airlineAddress], "This airline is not in registration queue"); _; // All modifiers require an "_" which indicates where the function body will be added } modifier onlyRegisteredPassenger(){ bool isRegistered; (,isRegistered,) = flightData.getPassengerData(msg.sender); require(isRegistered, "Passenger not registered"); _; } /********************************************************************************************/ /* CONSTRUCTOR */ /********************************************************************************************/ /** * @dev Contract constructor * */ constructor(address _flightDataContractAddress) public { contractOwner = msg.sender; flightData = FlightSuretyData(_flightDataContractAddress); } /********************************************************************************************/ /* UTILITY FUNCTIONS */ /********************************************************************************************/ /** * @dev Get operating status of contract * * @return A bool that is the current operating status */ function getOperationalStatus() external view returns(bool) { return operational; } /** * @dev Sets contract operations on/off * * When operational mode is disabled, all write transactions except for this one will fail */ function setOperatingStatus(bool mode) external onlyContractOwner { operational = mode; } /* @dev generate key using keccak256 */ function generateKey(address airlineAddress, string flightNumber, string timeStamp) internal view isOperational returns(bytes32) { return keccak256(abi.encodePacked(airlineAddress, flightNumber, timeStamp)); } /********************************************************************************************/ /* SMART CONTRACT FUNCTIONS */ /********************************************************************************************/ /** * @dev Add an airline to the registration queue * */ function registerAirline(string name, address airlineAddress) external isOperational onlyRegisteredAirline addressNotUsed(airlineAddress) { bool check = flightData.numRegisteredAirlines() < CONSENSUS; if (check) { flightData.registerAirline(name, airlineAddress); airlineNames[airlineAddress] = name; emit AirlineRegisteredWithoutVotes(airlineAddress); } else { uint256 votesPercentage; votesPercentage = votesPerAirline[airlineAddress].mul(100).div(flightData.numRegisteredAirlines()); if (votesPercentage >= 50) { flightData.registerAirline(name, airlineAddress); airlineNames[airlineAddress] = name; emit AirlineRegisteredWithVotes(airlineAddress, votesPerAirline[airlineAddress]); } else { isInQueue[airlineAddress] = true; airlineNames[airlineAddress] = name; emit AirlineAddedToRegisterationQueue(airlineAddress, votesPercentage); } } } function voteAirline(address airlineAddress) external isOperational onlyRegisteredAirline hasNotAlreadyVoted(airlineAddress) onlyInQueue(airlineAddress) { bool canParticipate; (,,canParticipate,) = flightData.getAirlineData(msg.sender); require(canParticipate, "Airline has not participated yet"); hasVoted[msg.sender][airlineAddress] = true; votesPerAirline[airlineAddress] = votesPerAirline[airlineAddress].add(1); emit AirlineVoted(msg.sender, airlineAddress); } function getAirlineRegistrationStatus(address _airlineAddress) external view isOperational returns(bool) { bool isRegistered; (,isRegistered,,) = flightData.getAirlineData(_airlineAddress); return isRegistered; } function checkIfVoted(address votingAirline, address votedAirline) external view isOperational returns(bool) { return hasVoted[votingAirline][votedAirline]; } function fundAirline() public payable isOperational onlyRegisteredAirline { //require(amount >= AIRLINE_PARTICIPATION_FEE, "Make sure you send the correct participation fee"); //address dataContractAddress = address(uint160(address(flightData))); //dataContractAddress.transfer(amount); //flightData.fund(msg.sender, amount); flightData.setParticipationStatus(msg.sender, true); emit AirlineFullyFunded(msg.sender, msg.value); } /** * @dev Register a future flight for insuring. * */ function registerFlight(string flightNumber, string timeStamp) external isOperational onlyRegisteredAirline { bool canParticipate; (,,canParticipate,) = flightData.getAirlineData(msg.sender); require(canParticipate, "Airline is not fully funded and can't participate"); bytes32 key = generateKey(msg.sender, flightNumber, timeStamp); flightData.registerFlight(msg.sender, key, flightNumber, timeStamp, STATUS_CODE_ON_TIME); emit FlightRegistered(msg.sender, flightNumber, timeStamp); } function registerPassenger(string _name, address _airlineAddress, string flightNumber, string timeStamp) external payable isOperational addressNotUsed(msg.sender) { bytes32 key = generateKey(_airlineAddress, flightNumber, timeStamp); bool isRegistered; (, isRegistered, , , ) = flightData.getFlightDetails(key); require(isRegistered, "This flight does not exist"); flightData.registerPassenger(_airlineAddress, _name, msg.sender, key, msg.value); address(flightData).transfer(msg.value); emit PassengerRegistered(msg.sender, _name, _airlineAddress, key); } function updateFlightStatusCode(address _airlineAddress, string flightNumber, string timeStamp, uint8 _statusCode) external isOperational { bytes32 key = generateKey(_airlineAddress, flightNumber, timeStamp); bool isRegistered; (, isRegistered, , , ) = flightData.getFlightDetails(key); require(isRegistered, "This flight does not exist"); flightData.updateFlightStatusCode(key, _statusCode); } function buyInsurance(address _airlineAddress, string flightNumber, string timeStamp) external payable isOperational onlyRegisteredPassenger { bytes32 key = generateKey(_airlineAddress, flightNumber, timeStamp); bool isRegistered; (, isRegistered, , , ) = flightData.getFlightDetails(key); require(isRegistered, "This flight does not exist"); require(!flightData.getInsuranceStatus(msg.sender, key), "Passenger already insured for the this flight"); require(INSURANCE_PREMIUM == 1 ether, "Incorrect Insurance premium paid"); address(flightData).transfer(msg.value); flightData.buyInsurance(msg.sender, _airlineAddress, key, msg.value); } function checkPassengerInsuranceStatus(address passengerAddress, address _airlineAddress, string flightNumber, string timeStamp) external isOperational onlyRegisteredAirline view returns(bool) { bytes32 flightKey = generateKey(_airlineAddress, flightNumber, timeStamp); return flightData.checkPassengerInsuranceStatus(passengerAddress, flightKey); } // function getFlightsPerAirline(address _airlineAddress) // external // view // isOperational // onlyRegisteredAirline // returns(bytes32[] memory) // { // mapping(address => bytes32[]) memory map = flightData.flightsPerAirline(); // return map[_airlineAddress]; // } /** * @dev Called after oracle has updated flight status * */ function processFlightStatus(address airline, string flightNumber, string timestamp, uint8 statusCode, uint8 factor) internal { bytes32 key = generateKey(airline, flightNumber, timestamp); flightData.updateFlightStatusCode(key, statusCode); if(statusCode == STATUS_CODE_LATE_AIRLINE){ flightData.creditAllInsureesPerFlight(key, factor); oracleResponses[key].isOpen = false; } } // Generate a request for oracles to fetch flight information function fetchFlightStatus(address airline, string flight, string timestamp) external isOperational onlyContractOwner { uint8 index = getRandomIndex(msg.sender); // Generate a unique key for storing the request bytes32 key = keccak256(abi.encodePacked(index, airline, flight, timestamp)); oracleResponses[key] = ResponseInfo({ requester: msg.sender, isOpen: true }); emit OracleRequest(index, airline, flight, timestamp); } // region ORACLE MANAGEMENT // Incremented to add pseudo-randomness at various points uint8 private nonce = 0; // Fee to be paid when registering oracle uint256 public constant REGISTRATION_FEE = 1 ether; // Number of oracles that must respond for valid status uint256 private constant MIN_RESPONSES = 3; struct Oracle { bool isRegistered; uint8[3] indexes; } // Track all registered oracles mapping(address => Oracle) private oracles; // Model for responses from oracles struct ResponseInfo { address requester; // Account that requested status bool isOpen; // If open, oracle responses are accepted mapping(uint8 => address[]) responses; // Mapping key is the status code reported // This lets us group responses and identify // the response that majority of the oracles } // Track all oracle responses // Key = hash(index, flight, timestamp) mapping(bytes32 => ResponseInfo) private oracleResponses; // Event fired each time an oracle submits a response event FlightStatusInfo(address airline, string flight, string timestamp, uint8 status); event OracleReport(address airline, string flight, string timestamp, uint8 status); // Event fired when flight status request is submitted // Oracles track this and if they have a matching index // they fetch data and submit a response event OracleRequest(uint8 index, address airline, string flight, string timestamp); // Register an oracle with the contract function registerOracle() external payable isOperational { // Require registration fee require(msg.value >= REGISTRATION_FEE, "Registration fee is required"); // Check if address has not registered Oracle before require(!oracles[msg.sender].isRegistered, "Oracle already registered"); uint8[3] memory indexes = generateIndexes(msg.sender); oracles[msg.sender] = Oracle({ isRegistered: true, indexes: indexes }); } function getMyIndexes() view external returns(uint8[3]) { require(oracles[msg.sender].isRegistered, "Not registered as an oracle"); return oracles[msg.sender].indexes; } // Called by oracle when a response is available to an outstanding request // For the response to be accepted, there must be a pending request that is open // and matches one of the three Indexes randomly assigned to the oracle at the // time of registration (i.e. uninvited oracles are not welcome) function submitOracleResponse(uint8 index, address airline, string flight, string timestamp, uint8 statusCode) external { require((oracles[msg.sender].indexes[0] == index) || (oracles[msg.sender].indexes[1] == index) || (oracles[msg.sender].indexes[2] == index), "Index does not match oracle request"); bytes32 key = keccak256(abi.encodePacked(index, airline, flight, timestamp)); require(oracleResponses[key].isOpen, "Flight or timestamp do not match oracle request"); oracleResponses[key].responses[statusCode].push(msg.sender); // Information isn't considered verified until at least MIN_RESPONSES // oracles respond with the *** same *** information emit OracleReport(airline, flight, timestamp, statusCode); if (oracleResponses[key].responses[statusCode].length >= MIN_RESPONSES) { emit FlightStatusInfo(airline, flight, timestamp, statusCode); // Handle flight status as appropriate processFlightStatus(airline, flight, timestamp, statusCode, 50); } } // Returns array of three non-duplicating integers from 0-9 function generateIndexes(address account) internal returns(uint8[3]) { uint8[3] memory indexes; indexes[0] = getRandomIndex(account); indexes[1] = indexes[0]; while(indexes[1] == indexes[0]) { indexes[1] = getRandomIndex(account); } indexes[2] = indexes[1]; while((indexes[2] == indexes[0]) || (indexes[2] == indexes[1])) { indexes[2] = getRandomIndex(account); } return indexes; } // Returns array of three non-duplicating integers from 0-9 function getRandomIndex(address account) internal returns (uint8) { uint8 maxValue = 10; // Pseudo random number...the incrementing nonce adds variation uint8 random = uint8(uint256(keccak256(abi.encodePacked(blockhash(block.number - nonce++), account))) % maxValue); if (nonce > 250) { nonce = 0; // Can only fetch blockhashes for last 256 blocks so we adapt } return random; } // endregion }
require(amount >= AIRLINE_PARTICIPATION_FEE, "Make sure you send the correct participation fee");address dataContractAddress = address(uint160(address(flightData)));dataContractAddress.transfer(amount);flightData.fund(msg.sender, amount);
function fundAirline() public payable isOperational onlyRegisteredAirline { flightData.setParticipationStatus(msg.sender, true); emit AirlineFullyFunded(msg.sender, msg.value); }
12,750,147
/** *Submitted for verification at Etherscan.io on 2020-08-27 */ pragma solidity ^0.6.6; import "../SafeMath.sol"; import "./VRFUtil.sol"; import "./VRF.sol"; import "./Ownable.sol"; contract VRFCore is VRFUtil, Ownable { using SafeMath for uint256; struct Callback { // Tracks an ongoing request address callbackContract; // Requesting contract, which will receive response // Commitment to seed passed to oracle by this contract, and the number of // the block in which the request appeared. This is the keccak256 of the // concatenation of those values. Storing this commitment saves a word of // storage. bytes32 seedAndBlockNum; } mapping(bytes32 /* (provingKey, seed) */ => Callback) public callbacks; mapping(bytes32 /* provingKey */ => mapping(address /* consumer */ => uint256)) private nonces; // The oracle only needs the jobID to look up the VRF, but specifying public // key as well prevents a malicious oracle from inducing VRF outputs from // another oracle by reusing the jobID. event RandomnessRequest( address coreAddress, bytes32 keyHash, uint256 seed, uint256 blockNumber, address sender, bytes32 requestId, bytes32 seedAndBlockNum, uint256 consumerSeed ); event RandomnessRequestFulfilled(bytes32 requestId, uint256 output); int256 private chainId; int256 private groupId; constructor(int256 _chainId, int256 _groupId) public Ownable() { chainId = _chainId; groupId = _groupId; } function getChainIdAndGroupId() public view returns(int256,int256){ return (chainId, groupId); } /** * * @param _keyHash ID of the VRF public key against which to generate output * @param _consumerSeed Input to the VRF, from which randomness is generated * @param _sender Requesting contract; to be called back with VRF output * * @dev _consumerSeed is mixed with key hash, sender address and nonce to * @dev obtain preSeed, which is passed to VRF oracle, which mixes it with the * @dev hash of the block containing this request, to compute the final seed. * * @dev The requestId used to store the request data is constructed from the * @dev preSeed and keyHash. */ function randomnessRequest( bytes32 _keyHash, uint256 _consumerSeed, address _sender) external returns(bool) { // record nonce uint256 nonce = nonces[_keyHash][_sender]; // preseed uint256 preSeed = makeVRFInputSeed( _keyHash, _consumerSeed, _sender, nonce); bytes32 requestId = makeRequestId(chainId, groupId, _keyHash, preSeed); // Cryptographically guaranteed by preSeed including an increasing nonce assert(callbacks[requestId].callbackContract == address(0)); callbacks[requestId].callbackContract = _sender; callbacks[requestId].seedAndBlockNum = keccak256(abi.encodePacked( preSeed, block.number)); emit RandomnessRequest(address (this), _keyHash, preSeed, block.number, _sender, requestId, callbacks[requestId].seedAndBlockNum, _consumerSeed); nonces[_keyHash][_sender] = nonces[_keyHash][_sender].add(1); return true; } /** * * @param _proof the proof of randomness. Actual random output built from this * * @dev The structure of _proof corresponds to vrf.MarshaledOnChainResponse, * @dev in the node source code. I.e., it is a vrf.MarshaledProof with the * @dev seed replaced by the preSeed, followed by the hash of the requesting * @dev block. */ function fulfillRandomnessRequest(uint256[2] memory _publicKey, bytes memory _proof, uint256 preSeed, uint blockNumber) public { (bytes32 currentKeyHash, Callback memory callback, bytes32 requestId, uint256 randomness) = getRandomnessFromProof(_publicKey, _proof, preSeed, blockNumber); // Pay oracle // Forget request. Must precede callback (prevents reentrancy) delete callbacks[requestId]; bool result = callBackWithRandomness(requestId, randomness, callback.callbackContract); require(result, "call back failed!"); emit RandomnessRequestFulfilled(requestId, randomness); } function callBackWithRandomness(bytes32 requestId, uint256 randomness, address consumerContract) internal returns (bool) { bytes4 s = bytes4(keccak256("callbackRandomness(bytes32,uint256)")); bytes memory resp = abi.encodeWithSelector( s, requestId, randomness); (bool success,) = consumerContract.call(resp); // Avoid unused-local-variable warning. (success is only present to prevent // a warning that the return value of consumerContract.call is unused.) (success); return success; } function getRandomnessFromProof( uint256[2] memory _publicKey, bytes memory _proof, uint256 preSeed, uint blockNumber) internal view returns (bytes32 currentKeyHash, Callback memory callback, bytes32 requestId, uint256 randomness) { // blockNum follows proof, which follows length word (only direct-number // constants are allowed in assembly, so have to compute this in code) currentKeyHash = hashOfKey(_publicKey); requestId = makeRequestId(chainId,groupId,currentKeyHash, preSeed); callback = callbacks[requestId]; require(callback.callbackContract != address(0), "no corresponding request"); require(callback.seedAndBlockNum == keccak256(abi.encodePacked(preSeed, blockNumber)), "wrong preSeed or block num"); bytes32 blockHash = blockhash(blockNumber); // The seed actually used by the VRF machinery, mixing in the blockHash bytes32 actualSeed = (keccak256(abi.encodePacked(preSeed, blockHash))); // solhint-disable-next-line no-inline-assembly uint256[4] memory proofParam = VRF.decodeProof(_proof); require(VRF.verify(_publicKey, proofParam, bytes32ToBytes(actualSeed)), "proof check failed!"); randomness = uint256 (VRF.gammaToHash(proofParam[0], proofParam[1])); // Reverts on failure } /** * @notice Returns the serviceAgreements key associated with this public key * @param _publicKey the key to return the address for */ function hashOfKey(uint256[2] memory _publicKey) public pure returns (bytes32) { return keccak256(abi.encodePacked(_publicKey)); } function bytes32ToBytes(bytes32 _bytes32) public view returns (bytes memory){ // string memory str = string(_bytes32); // TypeError: Explicit type conversion not allowed from "bytes32" to "string storage pointer" bytes memory bytesArray = new bytes(32); for (uint256 i; i < 32; i++) { bytesArray[i] = _bytes32[i]; } return bytesArray; } }
string memory str = string(_bytes32); TypeError: Explicit type conversion not allowed from "bytes32" to "string storage pointer"
function bytes32ToBytes(bytes32 _bytes32) public view returns (bytes memory){ bytes memory bytesArray = new bytes(32); function randomnessRequest( bytes32 _keyHash, uint256 _consumerSeed, } } } function getRandomnessFromProof( uint256[2] memory _publicKey, bytes memory _proof, uint256 preSeed, uint blockNumber) internal view returns (bytes32 currentKeyHash, Callback memory callback, } } for (uint256 i; i < 32; i++) { bytesArray[i] = _bytes32[i]; } return bytesArray; }
5,434,536
./full_match/1/0x7588213ff19fCF933B9E072E6AE887d2A2F3Aa1c/sources/NFT.sol
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(), ".png")) : ""; }
4,929,062
// SPDX-License-Identifier: BUSDL-1.1 pragma solidity 0.6.11; pragma experimental ABIEncoderV2; import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import {IAssetAllocation} from "contracts/common/Imports.sol"; import {CurveLusdConstants} from "./Constants.sol"; import { MetaPoolDepositorZap } from "contracts/protocols/curve/metapool/Imports.sol"; contract CurveLusdZap is MetaPoolDepositorZap, CurveLusdConstants { constructor() public MetaPoolDepositorZap( META_POOL, address(LP_TOKEN), address(LIQUIDITY_GAUGE), 10000, 100 ) // solhint-disable-next-line no-empty-blocks {} function assetAllocations() public view override returns (string[] memory) { string[] memory allocationNames = new string[](1); allocationNames[0] = NAME; return allocationNames; } function erc20Allocations() public view override returns (IERC20[] memory) { IERC20[] memory allocations = _createErc20AllocationArray(1); allocations[4] = PRIMARY_UNDERLYER; return allocations; } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: BUSDL-1.1 pragma solidity 0.6.11; import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import {SafeERC20} from "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import {IDetailedERC20} from "./IDetailedERC20.sol"; import {Ownable} from "@openzeppelin/contracts/access/Ownable.sol"; import { ReentrancyGuard } from "@openzeppelin/contracts/utils/ReentrancyGuard.sol"; import {AccessControl} from "./AccessControl.sol"; import {INameIdentifier} from "./INameIdentifier.sol"; import {IAssetAllocation} from "./IAssetAllocation.sol"; import {IEmergencyExit} from "./IEmergencyExit.sol"; // SPDX-License-Identifier: BUSDL-1.1 pragma solidity 0.6.11; import {IERC20, INameIdentifier} from "contracts/common/Imports.sol"; import { ILiquidityGauge } from "contracts/protocols/curve/common/interfaces/Imports.sol"; import {IMetaPool} from "contracts/protocols/curve/metapool/Imports.sol"; abstract contract CurveLusdConstants is INameIdentifier { string public constant override NAME = "curve-lusd"; // sometimes a metapool is its own LP token; otherwise, // you can obtain from `token` attribute IERC20 public constant LP_TOKEN = IERC20(0xEd279fDD11cA84bEef15AF5D39BB4d4bEE23F0cA); // metapool primary underlyer IERC20 public constant PRIMARY_UNDERLYER = IERC20(0x5f98805A4E8be255a32880FDeC7F6728C6568bA0); ILiquidityGauge public constant LIQUIDITY_GAUGE = ILiquidityGauge(0x9B8519A9a00100720CCdC8a120fBeD319cA47a14); IMetaPool public constant META_POOL = IMetaPool(0xEd279fDD11cA84bEef15AF5D39BB4d4bEE23F0cA); } // SPDX-License-Identifier: BUSDL-1.1 pragma solidity 0.6.11; import {IMetaPool} from "./IMetaPool.sol"; import {IOldDepositor} from "./IOldDepositor.sol"; import {IDepositor} from "./IDepositor.sol"; import {DepositorConstants} from "./Constants.sol"; import {MetaPoolAllocationBase} from "./MetaPoolAllocationBase.sol"; import {MetaPoolOldDepositorZap} from "./MetaPoolOldDepositorZap.sol"; import {MetaPoolDepositorZap} from "./MetaPoolDepositorZap.sol"; // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "./IERC20.sol"; import "../../math/SafeMath.sol"; import "../../utils/Address.sol"; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using SafeMath for uint256; using Address for address; function safeTransfer(IERC20 token, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove(IERC20 token, address spender, uint256 value) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' // solhint-disable-next-line max-line-length require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).add(value); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero"); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // SPDX-License-Identifier: BUSDL-1.1 pragma solidity 0.6.11; import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; interface IDetailedERC20 is IERC20 { function name() external view returns (string memory); function symbol() external view returns (string memory); function decimals() external view returns (uint8); } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "../utils/Context.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor () internal { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Contract module that helps prevent reentrant calls to a function. * * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier * available, which can be applied to functions to make sure there are no nested * (reentrant) calls to them. * * Note that because there is a single `nonReentrant` guard, functions marked as * `nonReentrant` may not call one another. This can be worked around by making * those functions `private`, and then adding `external` `nonReentrant` entry * points to them. * * TIP: If you would like to learn more about reentrancy and alternative ways * to protect against it, check out our blog post * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul]. */ abstract contract ReentrancyGuard { // Booleans are more expensive than uint256 or any type that takes up a full // word because each write operation emits an extra SLOAD to first read the // slot's contents, replace the bits taken up by the boolean, and then write // back. This is the compiler's defense against contract upgrades and // pointer aliasing, and it cannot be disabled. // The values being non-zero value makes deployment a bit more expensive, // but in exchange the refund on every call to nonReentrant will be lower in // amount. Since refunds are capped to a percentage of the total // transaction's gas, it is best to keep them low in cases like this one, to // increase the likelihood of the full refund coming into effect. uint256 private constant _NOT_ENTERED = 1; uint256 private constant _ENTERED = 2; uint256 private _status; constructor () internal { _status = _NOT_ENTERED; } /** * @dev Prevents a contract from calling itself, directly or indirectly. * Calling a `nonReentrant` function from another `nonReentrant` * function is not supported. It is possible to prevent this from happening * by making the `nonReentrant` function external, and make it call a * `private` function that does the actual work. */ modifier nonReentrant() { // On the first call to nonReentrant, _notEntered will be true require(_status != _ENTERED, "ReentrancyGuard: reentrant call"); // Any calls to nonReentrant after this point will fail _status = _ENTERED; _; // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) _status = _NOT_ENTERED; } } // SPDX-License-Identifier: BUSL-1.1 pragma solidity 0.6.11; import { AccessControl as OZAccessControl } from "@openzeppelin/contracts/access/AccessControl.sol"; /** * @notice Extends OpenZeppelin AccessControl contract with modifiers * @dev This contract and AccessControlUpgradeSafe are essentially duplicates. */ contract AccessControl is OZAccessControl { /** @notice access control roles **/ bytes32 public constant CONTRACT_ROLE = keccak256("CONTRACT_ROLE"); bytes32 public constant LP_ROLE = keccak256("LP_ROLE"); bytes32 public constant ADMIN_ROLE = keccak256("ADMIN_ROLE"); bytes32 public constant EMERGENCY_ROLE = keccak256("EMERGENCY_ROLE"); modifier onlyLpRole() { require(hasRole(LP_ROLE, _msgSender()), "NOT_LP_ROLE"); _; } modifier onlyContractRole() { require(hasRole(CONTRACT_ROLE, _msgSender()), "NOT_CONTRACT_ROLE"); _; } modifier onlyAdminRole() { require(hasRole(ADMIN_ROLE, _msgSender()), "NOT_ADMIN_ROLE"); _; } modifier onlyEmergencyRole() { require(hasRole(EMERGENCY_ROLE, _msgSender()), "NOT_EMERGENCY_ROLE"); _; } modifier onlyLpOrContractRole() { require( hasRole(LP_ROLE, _msgSender()) || hasRole(CONTRACT_ROLE, _msgSender()), "NOT_LP_OR_CONTRACT_ROLE" ); _; } modifier onlyAdminOrContractRole() { require( hasRole(ADMIN_ROLE, _msgSender()) || hasRole(CONTRACT_ROLE, _msgSender()), "NOT_ADMIN_OR_CONTRACT_ROLE" ); _; } } // SPDX-License-Identifier: BUSDL-1.1 pragma solidity 0.6.11; /** * @notice Used by the `NamedAddressSet` library to store sets of contracts */ interface INameIdentifier { /// @notice Should be implemented as a constant value // solhint-disable-next-line func-name-mixedcase function NAME() external view returns (string memory); } // SPDX-License-Identifier: BUSDL-1.1 pragma solidity 0.6.11; pragma experimental ABIEncoderV2; import {INameIdentifier} from "./INameIdentifier.sol"; /** * @notice For use with the `TvlManager` to track the value locked in a protocol */ interface IAssetAllocation is INameIdentifier { struct TokenData { address token; string symbol; uint8 decimals; } /** * @notice Get data for the underlying tokens stored in the protocol * @return The array of `TokenData` */ function tokens() external view returns (TokenData[] memory); /** * @notice Get the number of different tokens stored in the protocol * @return The number of tokens */ function numberOfTokens() external view returns (uint256); /** * @notice Get an account's balance for a token stored in the protocol * @dev The token index should be ordered the same as the `tokens()` array * @param account The account to get the balance for * @param tokenIndex The index of the token to get the balance for * @return The account's balance */ function balanceOf(address account, uint8 tokenIndex) external view returns (uint256); /** * @notice Get the symbol of a token stored in the protocol * @dev The token index should be ordered the same as the `tokens()` array * @param tokenIndex The index of the token * @return The symbol of the token */ function symbolOf(uint8 tokenIndex) external view returns (string memory); /** * @notice Get the decimals of a token stored in the protocol * @dev The token index should be ordered the same as the `tokens()` array * @param tokenIndex The index of the token * @return The decimals of the token */ function decimalsOf(uint8 tokenIndex) external view returns (uint8); } // SPDX-License-Identifier: BUSDL-1.1 pragma solidity 0.6.11; import {IERC20} from "./Imports.sol"; /** * @notice Used for contracts that need an emergency escape hatch * @notice Should only be used in an emergency to keep funds safu */ interface IEmergencyExit { /** * @param emergencySafe The address the tokens were escaped to * @param token The token escaped * @param balance The amount of tokens escaped */ event EmergencyExit(address emergencySafe, IERC20 token, uint256 balance); /** * @notice Transfer all tokens to the emergency Safe * @dev Should only be callable by the emergency Safe * @dev Should only transfer tokens to the emergency Safe * @param token The token to transfer */ function emergencyExit(address token) external; } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b > a) return (false, 0); return (true, a - b); } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a / b); } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a % b); } /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a, "SafeMath: subtraction overflow"); return a - b; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) return 0; uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers, reverting on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: division by zero"); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: modulo by zero"); return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); return a - b; } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryDiv}. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a % b; } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.2 <0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: value }(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.delegatecall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "../utils/EnumerableSet.sol"; import "../utils/Address.sol"; import "../utils/Context.sol"; /** * @dev Contract module that allows children to implement role-based access * control mechanisms. * * Roles are referred to by their `bytes32` identifier. These should be exposed * in the external API and be unique. The best way to achieve this is by * using `public constant` hash digests: * * ``` * bytes32 public constant MY_ROLE = keccak256("MY_ROLE"); * ``` * * Roles can be used to represent a set of permissions. To restrict access to a * function call, use {hasRole}: * * ``` * function foo() public { * require(hasRole(MY_ROLE, msg.sender)); * ... * } * ``` * * Roles can be granted and revoked dynamically via the {grantRole} and * {revokeRole} functions. Each role has an associated admin role, and only * accounts that have a role's admin role can call {grantRole} and {revokeRole}. * * By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means * that only accounts with this role will be able to grant or revoke other * roles. More complex role relationships can be created by using * {_setRoleAdmin}. * * WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to * grant and revoke this role. Extra precautions should be taken to secure * accounts that have been granted it. */ abstract contract AccessControl is Context { using EnumerableSet for EnumerableSet.AddressSet; using Address for address; struct RoleData { EnumerableSet.AddressSet members; bytes32 adminRole; } mapping (bytes32 => RoleData) private _roles; bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00; /** * @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole` * * `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite * {RoleAdminChanged} not being emitted signaling this. * * _Available since v3.1._ */ event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole); /** * @dev Emitted when `account` is granted `role`. * * `sender` is the account that originated the contract call, an admin role * bearer except when using {_setupRole}. */ event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Emitted when `account` is revoked `role`. * * `sender` is the account that originated the contract call: * - if using `revokeRole`, it is the admin role bearer * - if using `renounceRole`, it is the role bearer (i.e. `account`) */ event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Returns `true` if `account` has been granted `role`. */ function hasRole(bytes32 role, address account) public view returns (bool) { return _roles[role].members.contains(account); } /** * @dev Returns the number of accounts that have `role`. Can be used * together with {getRoleMember} to enumerate all bearers of a role. */ function getRoleMemberCount(bytes32 role) public view returns (uint256) { return _roles[role].members.length(); } /** * @dev Returns one of the accounts that have `role`. `index` must be a * value between 0 and {getRoleMemberCount}, non-inclusive. * * Role bearers are not sorted in any particular way, and their ordering may * change at any point. * * WARNING: When using {getRoleMember} and {getRoleMemberCount}, make sure * you perform all queries on the same block. See the following * https://forum.openzeppelin.com/t/iterating-over-elements-on-enumerableset-in-openzeppelin-contracts/2296[forum post] * for more information. */ function getRoleMember(bytes32 role, uint256 index) public view returns (address) { return _roles[role].members.at(index); } /** * @dev Returns the admin role that controls `role`. See {grantRole} and * {revokeRole}. * * To change a role's admin, use {_setRoleAdmin}. */ function getRoleAdmin(bytes32 role) public view returns (bytes32) { return _roles[role].adminRole; } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function grantRole(bytes32 role, address account) public virtual { require(hasRole(_roles[role].adminRole, _msgSender()), "AccessControl: sender must be an admin to grant"); _grantRole(role, account); } /** * @dev Revokes `role` from `account`. * * If `account` had been granted `role`, emits a {RoleRevoked} event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function revokeRole(bytes32 role, address account) public virtual { require(hasRole(_roles[role].adminRole, _msgSender()), "AccessControl: sender must be an admin to revoke"); _revokeRole(role, account); } /** * @dev Revokes `role` from the calling account. * * Roles are often managed via {grantRole} and {revokeRole}: this function's * purpose is to provide a mechanism for accounts to lose their privileges * if they are compromised (such as when a trusted device is misplaced). * * If the calling account had been granted `role`, emits a {RoleRevoked} * event. * * Requirements: * * - the caller must be `account`. */ function renounceRole(bytes32 role, address account) public virtual { require(account == _msgSender(), "AccessControl: can only renounce roles for self"); _revokeRole(role, account); } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. Note that unlike {grantRole}, this function doesn't perform any * checks on the calling account. * * [WARNING] * ==== * This function should only be called from the constructor when setting * up the initial roles for the system. * * Using this function in any other way is effectively circumventing the admin * system imposed by {AccessControl}. * ==== */ function _setupRole(bytes32 role, address account) internal virtual { _grantRole(role, account); } /** * @dev Sets `adminRole` as ``role``'s admin role. * * Emits a {RoleAdminChanged} event. */ function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual { emit RoleAdminChanged(role, _roles[role].adminRole, adminRole); _roles[role].adminRole = adminRole; } function _grantRole(bytes32 role, address account) private { if (_roles[role].members.add(account)) { emit RoleGranted(role, account, _msgSender()); } } function _revokeRole(bytes32 role, address account) private { if (_roles[role].members.remove(account)) { emit RoleRevoked(role, account, _msgSender()); } } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @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: BUSDL-1.1 pragma solidity 0.6.11; import {CTokenInterface} from "./CTokenInterface.sol"; import {ITokenMinter} from "./ITokenMinter.sol"; import {IStableSwap, IStableSwap3} from "./IStableSwap.sol"; import {IStableSwap2} from "./IStableSwap2.sol"; import {IStableSwap4} from "./IStableSwap4.sol"; import {IOldStableSwap2} from "./IOldStableSwap2.sol"; import {IOldStableSwap3} from "./IOldStableSwap3.sol"; import {IOldStableSwap4} from "./IOldStableSwap4.sol"; import {ILiquidityGauge} from "./ILiquidityGauge.sol"; import {IStakingRewards} from "./IStakingRewards.sol"; import {IDepositZap} from "./IDepositZap.sol"; import {IDepositZap3} from "./IDepositZap3.sol"; // SPDX-License-Identifier: BSD 3-Clause /* * https://github.com/compound-finance/compound-protocol/blob/master/contracts/CTokenInterfaces.sol */ pragma solidity 0.6.11; interface CTokenInterface { function symbol() external returns (string memory); function decimals() external returns (uint8); function totalSupply() external returns (uint256); function isCToken() external returns (bool); function transfer(address dst, uint256 amount) external returns (bool); function transferFrom( address src, address dst, uint256 amount ) external returns (bool); function approve(address spender, uint256 amount) external returns (bool); function totalBorrowsCurrent() external returns (uint256); function borrowBalanceCurrent(address account) external returns (uint256); function accrueInterest() external returns (uint256); function exchangeRateCurrent() external returns (uint256); function exchangeRateStored() external view returns (uint256); function getCash() external view returns (uint256); function borrowBalanceStored(address account) external view returns (uint256); function allowance(address owner, address spender) external view returns (uint256); function balanceOf(address owner) external view returns (uint256); function borrowRatePerBlock() external view returns (uint256); function supplyRatePerBlock() external view returns (uint256); function getAccountSnapshot(address account) external view returns ( uint256, uint256, uint256, uint256 ); } // SPDX-License-Identifier: MIT pragma solidity 0.6.11; /** * @notice the Curve token minter * @author Curve Finance * @dev translated from vyper * license MIT * version 0.2.4 */ // solhint-disable func-name-mixedcase, func-param-name-mixedcase interface ITokenMinter { /** * @notice Mint everything which belongs to `msg.sender` and send to them * @param gauge_addr `LiquidityGauge` address to get mintable amount from */ function mint(address gauge_addr) external; /** * @notice Mint everything which belongs to `msg.sender` across multiple gauges * @param gauge_addrs List of `LiquidityGauge` addresses */ function mint_many(address[8] calldata gauge_addrs) external; /** * @notice Mint tokens for `_for` * @dev Only possible when `msg.sender` has been approved via `toggle_approve_mint` * @param gauge_addr `LiquidityGauge` address to get mintable amount from * @param _for Address to mint to */ function mint_for(address gauge_addr, address _for) external; /** * @notice allow `minting_user` to mint for `msg.sender` * @param minting_user Address to toggle permission for */ function toggle_approve_mint(address minting_user) external; } // solhint-enable // SPDX-License-Identifier: BUSDL-1.1 pragma solidity 0.6.11; /** * @notice the stablecoin pool contract */ interface IStableSwap { function balances(uint256 coin) external view returns (uint256); function coins(uint256 coin) external view returns (address); // solhint-disable-next-line function underlying_coins(uint256 coin) external view returns (address); /** * @dev the number of coins is hard-coded in curve contracts */ // solhint-disable-next-line function add_liquidity(uint256[3] memory amounts, uint256 min_mint_amount) external; // solhint-disable-next-line function add_liquidity( uint256[3] memory amounts, uint256 minMinAmount, bool useUnderlyer ) external; /** * @dev the number of coins is hard-coded in curve contracts */ // solhint-disable-next-line function remove_liquidity(uint256 _amount, uint256[3] memory min_amounts) external; // solhint-disable-next-line function remove_liquidity_one_coin( uint256 tokenAmount, int128 tokenIndex, uint256 minAmount ) external; // solhint-disable-next-line function remove_liquidity_one_coin( uint256 tokenAmount, int128 tokenIndex, uint256 minAmount, bool useUnderlyer ) external; // solhint-disable-next-line function get_virtual_price() external view returns (uint256); /** * @dev For newest curve pools like aave; older pools refer to a private `token` variable. */ // function lp_token() external view returns (address); // solhint-disable-line func-name-mixedcase } // solhint-disable-next-line no-empty-blocks interface IStableSwap3 is IStableSwap { } // SPDX-License-Identifier: BUSDL-1.1 pragma solidity 0.6.11; import {SafeMath} from "@openzeppelin/contracts/math/SafeMath.sol"; import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; /** * @notice the stablecoin pool contract */ interface IStableSwap2 { function balances(uint256 coin) external view returns (uint256); function coins(uint256 coin) external view returns (address); // solhint-disable-next-line function underlying_coins(uint256 coin) external view returns (address); /** * @dev the number of coins is hard-coded in curve contracts */ // solhint-disable-next-line function add_liquidity(uint256[2] memory amounts, uint256 min_mint_amount) external; // solhint-disable-next-line function add_liquidity( uint256[2] memory amounts, uint256 minMinAmount, bool useUnderlyer ) external; /** * @dev the number of coins is hard-coded in curve contracts */ // solhint-disable-next-line function remove_liquidity(uint256 _amount, uint256[2] memory min_amounts) external; // solhint-disable-next-line function remove_liquidity_one_coin( uint256 tokenAmount, int128 tokenIndex, uint256 minAmount ) external; // solhint-disable-next-line function remove_liquidity_one_coin( uint256 tokenAmount, int128 tokenIndex, uint256 minAmount, bool useUnderlyer ) external; // solhint-disable-next-line function get_virtual_price() external view returns (uint256); /** * @dev For newest curve pools like aave; older pools refer to a private `token` variable. */ // function lp_token() external view returns (address); // solhint-disable-line func-name-mixedcase } // SPDX-License-Identifier: BUSDL-1.1 pragma solidity 0.6.11; import {SafeMath} from "@openzeppelin/contracts/math/SafeMath.sol"; import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; /** * @notice the stablecoin pool contract */ interface IStableSwap4 { function balances(uint256 coin) external view returns (uint256); function coins(uint256 coin) external view returns (address); /** * @dev the number of coins is hard-coded in curve contracts */ // solhint-disable-next-line function add_liquidity(uint256[4] memory amounts, uint256 min_mint_amount) external; /** * @dev the number of coins is hard-coded in curve contracts */ // solhint-disable-next-line function remove_liquidity(uint256 _amount, uint256[4] memory min_amounts) external; // solhint-disable-next-line function remove_liquidity_one_coin( uint256 tokenAmount, int128 tokenIndex, uint256 minAmount ) external; // solhint-disable-next-line function get_virtual_price() external view returns (uint256); /** * @dev For newest curve pools like aave; older pools refer to a private `token` variable. */ // function lp_token() external view returns (address); // solhint-disable-line func-name-mixedcase } // SPDX-License-Identifier: BUSDL-1.1 pragma solidity 0.6.11; import {SafeMath} from "@openzeppelin/contracts/math/SafeMath.sol"; import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; /** * @notice the stablecoin pool contract */ interface IOldStableSwap2 { function balances(int128 coin) external view returns (uint256); function coins(int128 coin) external view returns (address); /** * @dev the number of coins is hard-coded in curve contracts */ // solhint-disable-next-line function add_liquidity(uint256[2] memory amounts, uint256 min_mint_amount) external; /** * @dev the number of coins is hard-coded in curve contracts */ // solhint-disable-next-line function remove_liquidity(uint256 _amount, uint256[2] memory min_amounts) external; /// @dev need this due to lack of `remove_liquidity_one_coin` function exchange( int128 i, int128 j, uint256 dx, uint256 min_dy // solhint-disable-line func-param-name-mixedcase ) external; // solhint-disable-next-line function get_virtual_price() external view returns (uint256); /** * @dev For newest curve pools like aave; older pools refer to a private `token` variable. */ // function lp_token() external view returns (address); // solhint-disable-line func-name-mixedcase } // SPDX-License-Identifier: BUSDL-1.1 pragma solidity 0.6.11; import {SafeMath} from "@openzeppelin/contracts/math/SafeMath.sol"; import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; /** * @notice the stablecoin pool contract */ interface IOldStableSwap3 { function balances(int128 coin) external view returns (uint256); function coins(int128 coin) external view returns (address); /** * @dev the number of coins is hard-coded in curve contracts */ // solhint-disable-next-line function add_liquidity(uint256[3] memory amounts, uint256 min_mint_amount) external; /** * @dev the number of coins is hard-coded in curve contracts */ // solhint-disable-next-line function remove_liquidity(uint256 _amount, uint256[3] memory min_amounts) external; /// @dev need this due to lack of `remove_liquidity_one_coin` function exchange( int128 i, int128 j, uint256 dx, uint256 min_dy // solhint-disable-line func-param-name-mixedcase ) external; // solhint-disable-next-line function get_virtual_price() external view returns (uint256); } // SPDX-License-Identifier: BUSDL-1.1 pragma solidity 0.6.11; import {SafeMath} from "@openzeppelin/contracts/math/SafeMath.sol"; import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; /** * @notice the stablecoin pool contract */ interface IOldStableSwap4 { function balances(int128 coin) external view returns (uint256); function coins(int128 coin) external view returns (address); /** * @dev the number of coins is hard-coded in curve contracts */ // solhint-disable-next-line function add_liquidity(uint256[4] memory amounts, uint256 min_mint_amount) external; /** * @dev the number of coins is hard-coded in curve contracts */ // solhint-disable-next-line function remove_liquidity(uint256 _amount, uint256[4] memory min_amounts) external; /// @dev need this due to lack of `remove_liquidity_one_coin` function exchange( int128 i, int128 j, uint256 dx, uint256 min_dy // solhint-disable-line func-param-name-mixedcase ) external; // solhint-disable-next-line function get_virtual_price() external view returns (uint256); } // SPDX-License-Identifier: BUSDL-1.1 pragma solidity 0.6.11; import {SafeMath} from "@openzeppelin/contracts/math/SafeMath.sol"; import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; /** * @notice the liquidity gauge, i.e. staking contract, for the stablecoin pool */ interface ILiquidityGauge { function deposit(uint256 _value) external; function deposit(uint256 _value, address _addr) external; function withdraw(uint256 _value) external; /** * @notice Claim available reward tokens for msg.sender */ // solhint-disable-next-line func-name-mixedcase function claim_rewards() external; /** * @notice Get the number of claimable reward tokens for a user * @dev This function should be manually changed to "view" in the ABI * Calling it via a transaction will claim available reward tokens * @param _addr Account to get reward amount for * @param _token Token to get reward amount for * @return uint256 Claimable reward token amount */ // solhint-disable-next-line func-name-mixedcase function claimable_reward(address _addr, address _token) external returns (uint256); function balanceOf(address account) external view returns (uint256); } // SPDX-License-Identifier: MIT pragma solidity 0.6.11; /* * Synthetix: StakingRewards.sol * * Docs: https://docs.synthetix.io/ * * * MIT License * =========== * * Copyright (c) 2020 Synthetix * */ interface IStakingRewards { // Mutative function stake(uint256 amount) external; function withdraw(uint256 amount) external; function getReward() external; function exit() external; // 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); } // SPDX-License-Identifier: BUSDL-2.1 pragma solidity 0.6.11; import {SafeMath} from "@openzeppelin/contracts/math/SafeMath.sol"; import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; /** * @notice deposit contract used for pools such as Compound and USDT */ interface IDepositZap { // solhint-disable-next-line function underlying_coins(int128 coin) external view returns (address); /** * @dev the number of coins is hard-coded in curve contracts */ // solhint-disable-next-line function add_liquidity(uint256[2] memory amounts, uint256 min_mint_amount) external; /** * @dev the number of coins is hard-coded in curve contracts */ // solhint-disable-next-line function remove_liquidity_one_coin( uint256 _amount, int128 i, uint256 minAmount ) external; function curve() external view returns (address); } // SPDX-License-Identifier: BUSDL-2.1 pragma solidity 0.6.11; import {SafeMath} from "@openzeppelin/contracts/math/SafeMath.sol"; import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; /** * @notice deposit contract used for pools such as Compound and USDT */ interface IDepositZap3 { // solhint-disable-next-line function underlying_coins(int128 coin) external view returns (address); /** * @dev the number of coins is hard-coded in curve contracts */ // solhint-disable-next-line function add_liquidity(uint256[3] memory amounts, uint256 min_mint_amount) external; /** * @dev the number of coins is hard-coded in curve contracts */ // solhint-disable-next-line function remove_liquidity_one_coin( uint256 _amount, int128 i, uint256 minAmount ) external; function curve() external view returns (address); } // SPDX-License-Identifier: BUSDL-1.1 pragma solidity 0.6.11; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; /** * @notice the Curve metapool contract * @dev A metapool is sometimes its own LP token */ interface IMetaPool is IERC20 { /// @dev 1st coin is the protocol token, 2nd is the Curve base pool function balances(uint256 coin) external view returns (uint256); /// @dev 1st coin is the protocol token, 2nd is the Curve base pool function coins(uint256 coin) external view returns (address); /// @dev the number of coins is hard-coded in curve contracts // solhint-disable-next-line function add_liquidity(uint256[2] memory amounts, uint256 min_mint_amount) external; /// @dev the number of coins is hard-coded in curve contracts // solhint-disable-next-line function remove_liquidity(uint256 _amount, uint256[3] memory min_amounts) external; // solhint-disable-next-line function remove_liquidity_one_coin( uint256 tokenAmount, int128 tokenIndex, uint256 minAmount ) external; // solhint-disable-next-line function get_virtual_price() external view returns (uint256); } // SPDX-License-Identifier: BUSDL-1.1 pragma solidity 0.6.11; interface IOldDepositor { // solhint-disable function add_liquidity(uint256[4] calldata amounts, uint256 min_mint_amount) external returns (uint256); function remove_liquidity_one_coin( uint256 _token_amount, int128 i, uint256 _min_amount ) external returns (uint256); function coins(uint256 i) external view returns (address); function base_coins(uint256 i) external view returns (address); // solhint-enable } // SPDX-License-Identifier: BUSDL-1.1 pragma solidity 0.6.11; interface IDepositor { // solhint-disable function add_liquidity( address _pool, uint256[4] calldata _deposit_amounts, uint256 _min_mint_amount ) external returns (uint256); // solhint-enable // solhint-disable function remove_liquidity_one_coin( address _pool, uint256 _burn_amount, int128 i, uint256 _min_amounts ) external returns (uint256); // solhint-enable } // SPDX-License-Identifier: BUSDL-1.1 pragma solidity 0.6.11; import { IStableSwap } from "contracts/protocols/curve/common/interfaces/Imports.sol"; import {IDepositor} from "./IDepositor.sol"; abstract contract DepositorConstants { IStableSwap public constant BASE_POOL = IStableSwap(0xbEbc44782C7dB0a1A60Cb6fe97d0b483032FF1C7); // A depositor "zap" contract for metapools IDepositor public constant DEPOSITOR = IDepositor(0xA79828DF1850E8a3A3064576f380D90aECDD3359); } // SPDX-License-Identifier: UNLICENSED pragma solidity 0.6.11; import {SafeMath} from "contracts/libraries/Imports.sol"; import {IERC20} from "contracts/common/Imports.sol"; import { ILiquidityGauge } from "contracts/protocols/curve/common/interfaces/Imports.sol"; import {IMetaPool} from "./IMetaPool.sol"; import { Curve3poolAllocation } from "contracts/protocols/curve/3pool/Allocation.sol"; import {ImmutableAssetAllocation} from "contracts/tvl/Imports.sol"; import { Curve3poolUnderlyerConstants } from "contracts/protocols/curve/3pool/Constants.sol"; /** * @title Periphery Contract for a Curve metapool * @author APY.Finance * @notice This contract enables the APY.Finance system to retrieve the balance * of an underlyer of a Curve LP token. The balance is used as part * of the Chainlink computation of the deployed TVL. The primary * `getUnderlyerBalance` function is invoked indirectly when a * Chainlink node calls `balanceOf` on the APYAssetAllocationRegistry. */ abstract contract MetaPoolAllocationBase is ImmutableAssetAllocation, Curve3poolUnderlyerConstants { using SafeMath for uint256; /// @dev all existing Curve metapools are paired with 3pool Curve3poolAllocation public immutable curve3poolAllocation; constructor(address curve3poolAllocation_) public { curve3poolAllocation = Curve3poolAllocation(curve3poolAllocation_); } /** * @notice Returns the balance of an underlying token represented by * an account's LP token balance. * @param metaPool the liquidity pool comprised of multiple underlyers * @param gauge the staking contract for the LP tokens * @param coin the index indicating which underlyer * @return balance */ function getUnderlyerBalance( address account, IMetaPool metaPool, ILiquidityGauge gauge, IERC20 lpToken, uint256 coin ) public view returns (uint256 balance) { require(address(metaPool) != address(0), "INVALID_POOL"); require(address(gauge) != address(0), "INVALID_GAUGE"); require(address(lpToken) != address(0), "INVALID_LP_TOKEN"); uint256 poolBalance = getPoolBalance(metaPool, coin); (uint256 lpTokenBalance, uint256 lpTokenSupply) = getLpTokenShare(account, metaPool, gauge, lpToken); balance = lpTokenBalance.mul(poolBalance).div(lpTokenSupply); } function getPoolBalance(IMetaPool metaPool, uint256 coin) public view returns (uint256) { require(address(metaPool) != address(0), "INVALID_POOL"); require(coin < 256, "INVALID_COIN"); if (coin == 0) { return metaPool.balances(0); } coin -= 1; uint256 balance = curve3poolAllocation.balanceOf(address(metaPool), uint8(coin)); // renormalize using the pool's tracked 3Crv balance IERC20 baseLpToken = IERC20(metaPool.coins(1)); uint256 adjustedBalance = balance.mul(metaPool.balances(1)).div( baseLpToken.balanceOf(address(metaPool)) ); return adjustedBalance; } function getLpTokenShare( address account, IMetaPool metaPool, ILiquidityGauge gauge, IERC20 lpToken ) public view returns (uint256 balance, uint256 totalSupply) { require(address(metaPool) != address(0), "INVALID_POOL"); require(address(gauge) != address(0), "INVALID_GAUGE"); require(address(lpToken) != address(0), "INVALID_LP_TOKEN"); totalSupply = lpToken.totalSupply(); balance = lpToken.balanceOf(account); balance = balance.add(gauge.balanceOf(account)); } function _getBasePoolTokenData( address primaryUnderlyer, string memory symbol, uint8 decimals ) internal pure returns (TokenData[] memory) { TokenData[] memory tokens = new TokenData[](4); tokens[0] = TokenData(primaryUnderlyer, symbol, decimals); tokens[1] = TokenData(DAI_ADDRESS, "DAI", 18); tokens[2] = TokenData(USDC_ADDRESS, "USDC", 6); tokens[3] = TokenData(USDT_ADDRESS, "USDT", 6); return tokens; } } // SPDX-License-Identifier: BUSDL-1.1 pragma solidity 0.6.11; pragma experimental ABIEncoderV2; import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import {IAssetAllocation} from "contracts/common/Imports.sol"; import {IMetaPool} from "./IMetaPool.sol"; import {IOldDepositor} from "./IOldDepositor.sol"; import {CurveGaugeZapBase} from "contracts/protocols/curve/common/Imports.sol"; abstract contract MetaPoolOldDepositorZap is CurveGaugeZapBase { IOldDepositor internal immutable _DEPOSITOR; IMetaPool internal immutable _META_POOL; constructor( IOldDepositor depositor, IMetaPool metapool, address lpAddress, address gaugeAddress, uint256 denominator, uint256 slippage ) public CurveGaugeZapBase( address(depositor), lpAddress, gaugeAddress, denominator, slippage, 4 ) { _DEPOSITOR = depositor; _META_POOL = metapool; } function _addLiquidity(uint256[] calldata amounts, uint256 minAmount) internal override { _DEPOSITOR.add_liquidity( [amounts[0], amounts[1], amounts[2], amounts[3]], minAmount ); } function _removeLiquidity( uint256 lpBalance, uint8 index, uint256 minAmount ) internal override { IERC20(LP_ADDRESS).safeApprove(address(_DEPOSITOR), 0); IERC20(LP_ADDRESS).safeApprove(address(_DEPOSITOR), lpBalance); _DEPOSITOR.remove_liquidity_one_coin(lpBalance, index, minAmount); } function _getVirtualPrice() internal view override returns (uint256) { return _META_POOL.get_virtual_price(); } function _getCoinAtIndex(uint256 i) internal view override returns (address) { if (i == 0) { return _DEPOSITOR.coins(0); } else { return _DEPOSITOR.base_coins(i.sub(1)); } } } // SPDX-License-Identifier: BUSDL-1.1 pragma solidity 0.6.11; pragma experimental ABIEncoderV2; import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import {IAssetAllocation} from "contracts/common/Imports.sol"; import {IMetaPool} from "./IMetaPool.sol"; import {DepositorConstants} from "./Constants.sol"; import {CurveGaugeZapBase} from "contracts/protocols/curve/common/Imports.sol"; abstract contract MetaPoolDepositorZap is CurveGaugeZapBase, DepositorConstants { IMetaPool internal immutable _META_POOL; constructor( IMetaPool metapool, address lpAddress, address gaugeAddress, uint256 denominator, uint256 slippage ) public CurveGaugeZapBase( address(DEPOSITOR), lpAddress, gaugeAddress, denominator, slippage, 4 ) { _META_POOL = metapool; } function _addLiquidity(uint256[] calldata amounts, uint256 minAmount) internal override { DEPOSITOR.add_liquidity( address(_META_POOL), [amounts[0], amounts[1], amounts[2], amounts[3]], minAmount ); } function _removeLiquidity( uint256 lpBalance, uint8 index, uint256 minAmount ) internal override { IERC20(LP_ADDRESS).safeApprove(address(DEPOSITOR), 0); IERC20(LP_ADDRESS).safeApprove(address(DEPOSITOR), lpBalance); DEPOSITOR.remove_liquidity_one_coin( address(_META_POOL), lpBalance, index, minAmount ); } function _getVirtualPrice() internal view override returns (uint256) { return _META_POOL.get_virtual_price(); } function _getCoinAtIndex(uint256 i) internal view override returns (address) { if (i == 0) { return _META_POOL.coins(0); } else { return BASE_POOL.coins(i.sub(1)); } } } // SPDX-License-Identifier: BUSDL-1.1 pragma solidity 0.6.11; import {Address} from "@openzeppelin/contracts/utils/Address.sol"; import {SafeMath} from "@openzeppelin/contracts/math/SafeMath.sol"; import {SignedSafeMath} from "@openzeppelin/contracts/math/SignedSafeMath.sol"; import {SafeERC20} from "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import {EnumerableSet} from "@openzeppelin/contracts/utils/EnumerableSet.sol"; import {NamedAddressSet} from "./NamedAddressSet.sol"; // SPDX-License-Identifier: BUSDL-1.1 pragma solidity 0.6.11; pragma experimental ABIEncoderV2; import {IERC20} from "contracts/common/Imports.sol"; import {SafeMath} from "contracts/libraries/Imports.sol"; import {ImmutableAssetAllocation} from "contracts/tvl/Imports.sol"; import { IStableSwap, ILiquidityGauge } from "contracts/protocols/curve/common/interfaces/Imports.sol"; import { CurveAllocationBase } from "contracts/protocols/curve/common/Imports.sol"; import {Curve3poolConstants} from "./Constants.sol"; contract Curve3poolAllocation is CurveAllocationBase, ImmutableAssetAllocation, Curve3poolConstants { function balanceOf(address account, uint8 tokenIndex) public view override returns (uint256) { return super.getUnderlyerBalance( account, IStableSwap(STABLE_SWAP_ADDRESS), ILiquidityGauge(LIQUIDITY_GAUGE_ADDRESS), IERC20(LP_TOKEN_ADDRESS), uint256(tokenIndex) ); } function _getTokenData() internal pure override returns (TokenData[] memory) { TokenData[] memory tokens = new TokenData[](3); tokens[0] = TokenData(DAI_ADDRESS, "DAI", 18); tokens[1] = TokenData(USDC_ADDRESS, "USDC", 6); tokens[2] = TokenData(USDT_ADDRESS, "USDT", 6); return tokens; } } // SPDX-License-Identifier: BUSDL-1.1 pragma solidity 0.6.11; import {IErc20Allocation} from "./IErc20Allocation.sol"; import {IChainlinkRegistry} from "./IChainlinkRegistry.sol"; import {IAssetAllocationRegistry} from "./IAssetAllocationRegistry.sol"; import {AssetAllocationBase} from "./AssetAllocationBase.sol"; import {ImmutableAssetAllocation} from "./ImmutableAssetAllocation.sol"; import {Erc20AllocationConstants} from "./Erc20Allocation.sol"; // SPDX-License-Identifier: BUSDL-1.1 pragma solidity 0.6.11; import {INameIdentifier} from "contracts/common/Imports.sol"; abstract contract Curve3poolUnderlyerConstants { // underlyer addresses address public constant DAI_ADDRESS = 0x6B175474E89094C44Da98b954EedeAC495271d0F; address public constant USDC_ADDRESS = 0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48; address public constant USDT_ADDRESS = 0xdAC17F958D2ee523a2206206994597C13D831ec7; } abstract contract Curve3poolConstants is Curve3poolUnderlyerConstants, INameIdentifier { string public constant override NAME = "curve-3pool"; address public constant STABLE_SWAP_ADDRESS = 0xbEbc44782C7dB0a1A60Cb6fe97d0b483032FF1C7; address public constant LP_TOKEN_ADDRESS = 0x6c3F90f043a72FA612cbac8115EE7e52BDe6E490; address public constant LIQUIDITY_GAUGE_ADDRESS = 0xbFcF63294aD7105dEa65aA58F8AE5BE2D9d0952A; } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @title SignedSafeMath * @dev Signed math operations with safety checks that revert on error. */ library SignedSafeMath { int256 constant private _INT256_MIN = -2**255; /** * @dev Returns the multiplication of two signed integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(int256 a, int256 b) internal pure returns (int256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } require(!(a == -1 && b == _INT256_MIN), "SignedSafeMath: multiplication overflow"); int256 c = a * b; require(c / a == b, "SignedSafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two signed integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(int256 a, int256 b) internal pure returns (int256) { require(b != 0, "SignedSafeMath: division by zero"); require(!(b == -1 && a == _INT256_MIN), "SignedSafeMath: division overflow"); int256 c = a / b; return c; } /** * @dev Returns the subtraction of two signed integers, reverting on * overflow. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(int256 a, int256 b) internal pure returns (int256) { int256 c = a - b; require((b >= 0 && c <= a) || (b < 0 && c > a), "SignedSafeMath: subtraction overflow"); return c; } /** * @dev Returns the addition of two signed integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(int256 a, int256 b) internal pure returns (int256) { int256 c = a + b; require((b >= 0 && c >= a) || (b < 0 && c < a), "SignedSafeMath: addition overflow"); return c; } } // SPDX-License-Identifier: BUSDL-1.1 pragma solidity 0.6.11; import {Address} from "@openzeppelin/contracts/utils/Address.sol"; import {EnumerableSet} from "@openzeppelin/contracts/utils/EnumerableSet.sol"; import {IAssetAllocation, INameIdentifier} from "contracts/common/Imports.sol"; import {IZap, ISwap} from "contracts/lpaccount/Imports.sol"; /** * @notice Stores a set of addresses that can be looked up by name * @notice Addresses can be added or removed dynamically * @notice Useful for keeping track of unique deployed contracts * @dev Each address must be a contract with a `NAME` constant for lookup */ // solhint-disable ordering library NamedAddressSet { using EnumerableSet for EnumerableSet.AddressSet; struct Set { EnumerableSet.AddressSet _namedAddresses; mapping(string => INameIdentifier) _nameLookup; } struct AssetAllocationSet { Set _inner; } struct ZapSet { Set _inner; } struct SwapSet { Set _inner; } function _add(Set storage set, INameIdentifier namedAddress) private { require(Address.isContract(address(namedAddress)), "INVALID_ADDRESS"); require( !set._namedAddresses.contains(address(namedAddress)), "DUPLICATE_ADDRESS" ); string memory name = namedAddress.NAME(); require(bytes(name).length != 0, "INVALID_NAME"); require(address(set._nameLookup[name]) == address(0), "DUPLICATE_NAME"); set._namedAddresses.add(address(namedAddress)); set._nameLookup[name] = namedAddress; } function _remove(Set storage set, string memory name) private { address namedAddress = address(set._nameLookup[name]); require(namedAddress != address(0), "INVALID_NAME"); set._namedAddresses.remove(namedAddress); delete set._nameLookup[name]; } function _contains(Set storage set, INameIdentifier namedAddress) private view returns (bool) { return set._namedAddresses.contains(address(namedAddress)); } function _length(Set storage set) private view returns (uint256) { return set._namedAddresses.length(); } function _at(Set storage set, uint256 index) private view returns (INameIdentifier) { return INameIdentifier(set._namedAddresses.at(index)); } function _get(Set storage set, string memory name) private view returns (INameIdentifier) { return set._nameLookup[name]; } function _names(Set storage set) private view returns (string[] memory) { uint256 length_ = set._namedAddresses.length(); string[] memory names_ = new string[](length_); for (uint256 i = 0; i < length_; i++) { INameIdentifier namedAddress = INameIdentifier(set._namedAddresses.at(i)); names_[i] = namedAddress.NAME(); } return names_; } function add( AssetAllocationSet storage set, IAssetAllocation assetAllocation ) internal { _add(set._inner, assetAllocation); } function remove(AssetAllocationSet storage set, string memory name) internal { _remove(set._inner, name); } function contains( AssetAllocationSet storage set, IAssetAllocation assetAllocation ) internal view returns (bool) { return _contains(set._inner, assetAllocation); } function length(AssetAllocationSet storage set) internal view returns (uint256) { return _length(set._inner); } function at(AssetAllocationSet storage set, uint256 index) internal view returns (IAssetAllocation) { return IAssetAllocation(address(_at(set._inner, index))); } function get(AssetAllocationSet storage set, string memory name) internal view returns (IAssetAllocation) { return IAssetAllocation(address(_get(set._inner, name))); } function names(AssetAllocationSet storage set) internal view returns (string[] memory) { return _names(set._inner); } function add(ZapSet storage set, IZap zap) internal { _add(set._inner, zap); } function remove(ZapSet storage set, string memory name) internal { _remove(set._inner, name); } function contains(ZapSet storage set, IZap zap) internal view returns (bool) { return _contains(set._inner, zap); } function length(ZapSet storage set) internal view returns (uint256) { return _length(set._inner); } function at(ZapSet storage set, uint256 index) internal view returns (IZap) { return IZap(address(_at(set._inner, index))); } function get(ZapSet storage set, string memory name) internal view returns (IZap) { return IZap(address(_get(set._inner, name))); } function names(ZapSet storage set) internal view returns (string[] memory) { return _names(set._inner); } function add(SwapSet storage set, ISwap swap) internal { _add(set._inner, swap); } function remove(SwapSet storage set, string memory name) internal { _remove(set._inner, name); } function contains(SwapSet storage set, ISwap swap) internal view returns (bool) { return _contains(set._inner, swap); } function length(SwapSet storage set) internal view returns (uint256) { return _length(set._inner); } function at(SwapSet storage set, uint256 index) internal view returns (ISwap) { return ISwap(address(_at(set._inner, index))); } function get(SwapSet storage set, string memory name) internal view returns (ISwap) { return ISwap(address(_get(set._inner, name))); } function names(SwapSet storage set) internal view returns (string[] memory) { return _names(set._inner); } } // solhint-enable ordering // SPDX-License-Identifier: BUSDL-1.1 pragma solidity 0.6.11; import {IZap} from "./IZap.sol"; import {ISwap} from "./ISwap.sol"; import {ILpAccount} from "./ILpAccount.sol"; import {IZapRegistry} from "./IZapRegistry.sol"; import {ISwapRegistry} from "./ISwapRegistry.sol"; import {IStableSwap3Pool} from "./IStableSwap3Pool.sol"; // SPDX-License-Identifier: BUSDL-1.1 pragma solidity 0.6.11; pragma experimental ABIEncoderV2; import { IAssetAllocation, INameIdentifier, IERC20 } from "contracts/common/Imports.sol"; /** * @notice Used to define how an LP Account farms an external protocol */ interface IZap is INameIdentifier { /** * @notice Deploy liquidity to a protocol (i.e. enter a farm) * @dev Implementation should add liquidity and stake LP tokens * @param amounts Amount of each token to deploy */ function deployLiquidity(uint256[] calldata amounts) external; /** * @notice Unwind liquidity from a protocol (i.e exit a farm) * @dev Implementation should unstake LP tokens and remove liquidity * @dev If there is only one token to unwind, `index` should be 0 * @param amount Amount of liquidity to unwind * @param index Which token should be unwound */ function unwindLiquidity(uint256 amount, uint8 index) external; /** * @notice Claim accrued rewards from the protocol (i.e. harvest yield) */ function claim() external; /** * @notice Retrieves the LP token balance */ function getLpTokenBalance(address account) external view returns (uint256); /** * @notice Order of tokens for deploy `amounts` and unwind `index` * @dev Implementation should use human readable symbols * @dev Order should be the same for deploy and unwind * @return The array of symbols in order */ function sortedSymbols() external view returns (string[] memory); /** * @notice Asset allocations to include in TVL * @dev Requires all allocations that track value deployed to the protocol * @return An array of the asset allocation names */ function assetAllocations() external view returns (string[] memory); /** * @notice ERC20 asset allocations to include in TVL * @dev Should return addresses for all tokens that get deployed or unwound * @return The array of ERC20 token addresses */ function erc20Allocations() external view returns (IERC20[] memory); } // SPDX-License-Identifier: BUSDL-1.1 pragma solidity 0.6.11; pragma experimental ABIEncoderV2; import { IAssetAllocation, INameIdentifier, IERC20 } from "contracts/common/Imports.sol"; /** * @notice Used to define a token swap that can be performed by an LP Account */ interface ISwap is INameIdentifier { /** * @dev Implementation should perform a token swap * @param amount The amount of the input token to swap * @param minAmount The minimum amount of the output token to accept */ function swap(uint256 amount, uint256 minAmount) external; /** * @notice ERC20 asset allocations to include in TVL * @dev Should return addresses for all tokens going in and out of the swap * @return The array of ERC20 token addresses */ function erc20Allocations() external view returns (IERC20[] memory); } // SPDX-License-Identifier: BUSDL-1.1 pragma solidity 0.6.11; /** * @notice For contracts that provide liquidity to external protocols */ interface ILpAccount { /** * @notice Deploy liquidity with a registered `IZap` * @dev The order of token amounts should match `IZap.sortedSymbols` * @param name The name of the `IZap` * @param amounts The token amounts to deploy */ function deployStrategy(string calldata name, uint256[] calldata amounts) external; /** * @notice Unwind liquidity with a registered `IZap` * @dev The index should match the order of `IZap.sortedSymbols` * @param name The name of the `IZap` * @param amount The amount of the token to unwind * @param index The index of the token to unwind into */ function unwindStrategy( string calldata name, uint256 amount, uint8 index ) external; /** * @notice Return liquidity to a pool * @notice Typically used to refill a liquidity pool's reserve * @dev This should only be callable by the `MetaPoolToken` * @param pool The `IReservePool` to transfer to * @param amount The amount of the pool's underlyer token to transer */ function transferToPool(address pool, uint256 amount) external; /** * @notice Swap tokens with a registered `ISwap` * @notice Used to compound reward tokens * @notice Used to rebalance underlyer tokens * @param name The name of the `IZap` * @param amount The amount of tokens to swap * @param minAmount The minimum amount of tokens to receive from the swap */ function swap( string calldata name, uint256 amount, uint256 minAmount ) external; /** * @notice Claim reward tokens with a registered `IZap` * @param name The name of the `IZap` */ function claim(string calldata name) external; } // SPDX-License-Identifier: BUSDL-1.1 pragma solidity 0.6.11; pragma experimental ABIEncoderV2; import {IZap} from "./IZap.sol"; /** * @notice For managing a collection of `IZap` contracts */ interface IZapRegistry { /** @notice Log when a new `IZap` is registered */ event ZapRegistered(IZap zap); /** @notice Log when an `IZap` is removed */ event ZapRemoved(string name); /** * @notice Add a new `IZap` to the registry * @dev Should not allow duplicate swaps * @param zap The new `IZap` */ function registerZap(IZap zap) external; /** * @notice Remove an `IZap` from the registry * @param name The name of the `IZap` (see `INameIdentifier`) */ function removeZap(string calldata name) external; /** * @notice Get the names of all registered `IZap` * @return An array of `IZap` names */ function zapNames() external view returns (string[] memory); } // SPDX-License-Identifier: BUSDL-1.1 pragma solidity 0.6.11; pragma experimental ABIEncoderV2; import {ISwap} from "./ISwap.sol"; /** * @notice For managing a collection of `ISwap` contracts */ interface ISwapRegistry { /** @notice Log when a new `ISwap` is registered */ event SwapRegistered(ISwap swap); /** @notice Log when an `ISwap` is removed */ event SwapRemoved(string name); /** * @notice Add a new `ISwap` to the registry * @dev Should not allow duplicate swaps * @param swap The new `ISwap` */ function registerSwap(ISwap swap) external; /** * @notice Remove an `ISwap` from the registry * @param name The name of the `ISwap` (see `INameIdentifier`) */ function removeSwap(string calldata name) external; /** * @notice Get the names of all registered `ISwap` * @return An array of `ISwap` names */ function swapNames() external view returns (string[] memory); } // SPDX-License-Identifier: BUSDL-1.1 pragma solidity 0.6.11; /** * @notice the stablecoin pool contract */ interface IStableSwap3Pool { function exchange( int128 i, int128 j, uint256 dx, uint256 min_dy // solhint-disable-line func-param-name-mixedcase ) external; function coins(uint256 coin) external view returns (address); // solhint-disable-next-line func-name-mixedcase function get_dy( int128 i, int128 j, uint256 dx ) external view returns (uint256); } // SPDX-License-Identifier: BUSDL-1.1 pragma solidity 0.6.11; import {CurveAllocationBase, CurveAllocationBase3} from "./CurveAllocationBase.sol"; import {CurveAllocationBase2} from "./CurveAllocationBase2.sol"; import {CurveAllocationBase4} from "./CurveAllocationBase4.sol"; import {CurveGaugeZapBase} from "./CurveGaugeZapBase.sol"; import {CurveZapBase} from "./CurveZapBase.sol"; import {OldCurveAllocationBase2} from "./OldCurveAllocationBase2.sol"; import {OldCurveAllocationBase3} from "./OldCurveAllocationBase3.sol"; import {OldCurveAllocationBase4} from "./OldCurveAllocationBase4.sol"; import {TestCurveZap} from "./TestCurveZap.sol"; // SPDX-License-Identifier: BUSDL-1.1 pragma solidity 0.6.11; import {IERC20, IDetailedERC20} from "contracts/common/Imports.sol"; /** * @notice An asset allocation for tokens not stored in a protocol * @dev `IZap`s and `ISwap`s register these separate from other allocations * @dev Unlike other asset allocations, new tokens can be added or removed * @dev Registration can override `symbol` and `decimals` manually because * they are optional in the ERC20 standard. */ interface IErc20Allocation { /** @notice Log when an ERC20 allocation is registered */ event Erc20TokenRegistered(IERC20 token, string symbol, uint8 decimals); /** @notice Log when an ERC20 allocation is removed */ event Erc20TokenRemoved(IERC20 token); /** * @notice Add a new ERC20 token to the asset allocation * @dev Should not allow duplicate tokens * @param token The new token */ function registerErc20Token(IDetailedERC20 token) external; /** * @notice Add a new ERC20 token to the asset allocation * @dev Should not allow duplicate tokens * @param token The new token * @param symbol Override the token symbol */ function registerErc20Token(IDetailedERC20 token, string calldata symbol) external; /** * @notice Add a new ERC20 token to the asset allocation * @dev Should not allow duplicate tokens * @param token The new token * @param symbol Override the token symbol * @param decimals Override the token decimals */ function registerErc20Token( IERC20 token, string calldata symbol, uint8 decimals ) external; /** * @notice Remove an ERC20 token from the asset allocation * @param token The token to remove */ function removeErc20Token(IERC20 token) external; /** * @notice Check if an ERC20 token is registered * @param token The token to check * @return `true` if the token is registered, `false` otherwise */ function isErc20TokenRegistered(IERC20 token) external view returns (bool); /** * @notice Check if multiple ERC20 tokens are ALL registered * @param tokens An array of tokens to check * @return `true` if every token is registered, `false` otherwise */ function isErc20TokenRegistered(IERC20[] calldata tokens) external view returns (bool); } // SPDX-License-Identifier: BUSDL-1.1 pragma solidity 0.6.11; /** * @notice Interface used by Chainlink to aggregate allocations and compute TVL */ interface IChainlinkRegistry { /** * @notice Get all IDs from registered asset allocations * @notice Each ID is a unique asset allocation and token index pair * @dev Should contain no duplicate IDs * @return list of all IDs */ function getAssetAllocationIds() external view returns (bytes32[] memory); /** * @notice Get the LP Account's balance for an asset allocation ID * @param allocationId The ID to fetch the balance for * @return The balance for the LP Account */ function balanceOf(bytes32 allocationId) external view returns (uint256); /** * @notice Get the symbol for an allocation ID's underlying token * @param allocationId The ID to fetch the symbol for * @return The underlying token symbol */ function symbolOf(bytes32 allocationId) external view returns (string memory); /** * @notice Get the decimals for an allocation ID's underlying token * @param allocationId The ID to fetch the decimals for * @return The underlying token decimals */ function decimalsOf(bytes32 allocationId) external view returns (uint256); } // SPDX-License-Identifier: BUSDL-1.1 pragma solidity 0.6.11; pragma experimental ABIEncoderV2; import {IAssetAllocation} from "contracts/common/Imports.sol"; /** * @notice For managing a collection of `IAssetAllocation` contracts */ interface IAssetAllocationRegistry { /** @notice Log when an asset allocation is registered */ event AssetAllocationRegistered(IAssetAllocation assetAllocation); /** @notice Log when an asset allocation is removed */ event AssetAllocationRemoved(string name); /** * @notice Add a new asset allocation to the registry * @dev Should not allow duplicate asset allocations * @param assetAllocation The new asset allocation */ function registerAssetAllocation(IAssetAllocation assetAllocation) external; /** * @notice Remove an asset allocation from the registry * @param name The name of the asset allocation (see `INameIdentifier`) */ function removeAssetAllocation(string memory name) external; /** * @notice Check if multiple asset allocations are ALL registered * @param allocationNames An array of asset allocation names * @return `true` if every allocation is registered, otherwise `false` */ function isAssetAllocationRegistered(string[] calldata allocationNames) external view returns (bool); /** * @notice Get the registered asset allocation with a given name * @param name The asset allocation name * @return The asset allocation */ function getAssetAllocation(string calldata name) external view returns (IAssetAllocation); } // SPDX-License-Identifier: BUSDL-1.1 pragma solidity 0.6.11; pragma experimental ABIEncoderV2; import {IAssetAllocation} from "contracts/common/Imports.sol"; abstract contract AssetAllocationBase is IAssetAllocation { function numberOfTokens() external view override returns (uint256) { return tokens().length; } function symbolOf(uint8 tokenIndex) public view override returns (string memory) { return tokens()[tokenIndex].symbol; } function decimalsOf(uint8 tokenIndex) public view override returns (uint8) { return tokens()[tokenIndex].decimals; } function addressOf(uint8 tokenIndex) public view returns (address) { return tokens()[tokenIndex].token; } function tokens() public view virtual override returns (TokenData[] memory); } // SPDX-License-Identifier: BUSDL-1.1 pragma solidity 0.6.11; pragma experimental ABIEncoderV2; import {Address} from "contracts/libraries/Imports.sol"; import {AssetAllocationBase} from "./AssetAllocationBase.sol"; /** * @notice Asset allocation with underlying tokens that cannot be added/removed */ abstract contract ImmutableAssetAllocation is AssetAllocationBase { using Address for address; constructor() public { _validateTokens(_getTokenData()); } function tokens() public view override returns (TokenData[] memory) { TokenData[] memory tokens_ = _getTokenData(); return tokens_; } /** * @notice Verifies that a `TokenData` array works with the `TvlManager` * @dev Reverts when there is invalid `TokenData` * @param tokens_ The array of `TokenData` */ function _validateTokens(TokenData[] memory tokens_) internal view virtual { // length restriction due to encoding logic for allocation IDs require(tokens_.length < type(uint8).max, "TOO_MANY_TOKENS"); for (uint256 i = 0; i < tokens_.length; i++) { address token = tokens_[i].token; _validateTokenAddress(token); string memory symbol = tokens_[i].symbol; require(bytes(symbol).length != 0, "INVALID_SYMBOL"); } // TODO: check for duplicate tokens } /** * @notice Verify that a token is a contract * @param token The token to verify */ function _validateTokenAddress(address token) internal view virtual { require(token.isContract(), "INVALID_ADDRESS"); } /** * @notice Get the immutable array of underlying `TokenData` * @dev Should be implemented in child contracts with a hardcoded array * @return The array of `TokenData` */ function _getTokenData() internal pure virtual returns (TokenData[] memory); } // SPDX-License-Identifier: BUSDL-1.1 pragma solidity 0.6.11; pragma experimental ABIEncoderV2; import { IERC20, IDetailedERC20, AccessControl, INameIdentifier, ReentrancyGuard } from "contracts/common/Imports.sol"; import {Address, EnumerableSet} from "contracts/libraries/Imports.sol"; import {IAddressRegistryV2} from "contracts/registry/Imports.sol"; import {ILockingOracle} from "contracts/oracle/Imports.sol"; import {IErc20Allocation} from "./IErc20Allocation.sol"; import {AssetAllocationBase} from "./AssetAllocationBase.sol"; abstract contract Erc20AllocationConstants is INameIdentifier { string public constant override NAME = "erc20Allocation"; } contract Erc20Allocation is IErc20Allocation, AssetAllocationBase, Erc20AllocationConstants, AccessControl, ReentrancyGuard { using Address for address; using EnumerableSet for EnumerableSet.AddressSet; IAddressRegistryV2 public addressRegistry; EnumerableSet.AddressSet private _tokenAddresses; mapping(address => TokenData) private _tokenToData; /** @notice Log when the address registry is changed */ event AddressRegistryChanged(address); constructor(address addressRegistry_) public { _setAddressRegistry(addressRegistry_); _setupRole(DEFAULT_ADMIN_ROLE, addressRegistry.emergencySafeAddress()); _setupRole(EMERGENCY_ROLE, addressRegistry.emergencySafeAddress()); _setupRole(ADMIN_ROLE, addressRegistry.adminSafeAddress()); _setupRole(CONTRACT_ROLE, addressRegistry.mAptAddress()); } /** * @notice Set the new address registry * @param addressRegistry_ The new address registry */ function emergencySetAddressRegistry(address addressRegistry_) external nonReentrant onlyEmergencyRole { _setAddressRegistry(addressRegistry_); } function registerErc20Token(IDetailedERC20 token) external override nonReentrant onlyAdminOrContractRole { string memory symbol = token.symbol(); uint8 decimals = token.decimals(); _registerErc20Token(token, symbol, decimals); } function registerErc20Token(IDetailedERC20 token, string calldata symbol) external override nonReentrant onlyAdminRole { uint8 decimals = token.decimals(); _registerErc20Token(token, symbol, decimals); } function registerErc20Token( IERC20 token, string calldata symbol, uint8 decimals ) external override nonReentrant onlyAdminRole { _registerErc20Token(token, symbol, decimals); } function removeErc20Token(IERC20 token) external override nonReentrant onlyAdminRole { _tokenAddresses.remove(address(token)); delete _tokenToData[address(token)]; _lockOracleAdapter(); emit Erc20TokenRemoved(token); } function isErc20TokenRegistered(IERC20 token) external view override returns (bool) { return _tokenAddresses.contains(address(token)); } function isErc20TokenRegistered(IERC20[] calldata tokens) external view override returns (bool) { uint256 length = tokens.length; for (uint256 i = 0; i < length; i++) { if (!_tokenAddresses.contains(address(tokens[i]))) { return false; } } return true; } function balanceOf(address account, uint8 tokenIndex) external view override returns (uint256) { address token = addressOf(tokenIndex); return IERC20(token).balanceOf(account); } function tokens() public view override returns (TokenData[] memory) { TokenData[] memory _tokens = new TokenData[](_tokenAddresses.length()); for (uint256 i = 0; i < _tokens.length; i++) { address tokenAddress = _tokenAddresses.at(i); _tokens[i] = _tokenToData[tokenAddress]; } return _tokens; } function _setAddressRegistry(address addressRegistry_) internal { require(addressRegistry_.isContract(), "INVALID_ADDRESS"); addressRegistry = IAddressRegistryV2(addressRegistry_); emit AddressRegistryChanged(addressRegistry_); } function _registerErc20Token( IERC20 token, string memory symbol, uint8 decimals ) internal { require(address(token).isContract(), "INVALID_ADDRESS"); require(bytes(symbol).length != 0, "INVALID_SYMBOL"); _tokenAddresses.add(address(token)); _tokenToData[address(token)] = TokenData( address(token), symbol, decimals ); _lockOracleAdapter(); emit Erc20TokenRegistered(token, symbol, decimals); } /** * @notice Lock the `OracleAdapter` for the default period of time * @dev Locking protects against front-running while Chainlink updates */ function _lockOracleAdapter() internal { ILockingOracle oracleAdapter = ILockingOracle(addressRegistry.oracleAdapterAddress()); oracleAdapter.lock(); } } // SPDX-License-Identifier: BUSDL-1.1 pragma solidity 0.6.11; import {IAddressRegistryV2} from "./IAddressRegistryV2.sol"; // SPDX-License-Identifier: BUSDL-1.1 pragma solidity 0.6.11; import {AggregatorV3Interface, FluxAggregator} from "./FluxAggregator.sol"; import {IOracleAdapter} from "./IOracleAdapter.sol"; import {IOverrideOracle} from "./IOverrideOracle.sol"; import {ILockingOracle} from "./ILockingOracle.sol"; // SPDX-License-Identifier: BUSDL-1.1 pragma solidity 0.6.11; /** * @notice The address registry has two important purposes, one which * is fairly concrete and another abstract. * * 1. The registry enables components of the APY.Finance system * and external systems to retrieve core addresses reliably * even when the functionality may move to a different * address. * * 2. The registry also makes explicit which contracts serve * as primary entrypoints for interacting with different * components. Not every contract is registered here, only * the ones properly deserving of an identifier. This helps * define explicit boundaries between groups of contracts, * each of which is logically cohesive. */ interface IAddressRegistryV2 { /** * @notice Log when a new address is registered * @param id The ID of the new address * @param _address The new address */ event AddressRegistered(bytes32 id, address _address); /** * @notice Log when an address is removed from the registry * @param id The ID of the address * @param _address The address */ event AddressDeleted(bytes32 id, address _address); /** * @notice Register address with identifier * @dev Using an existing ID will replace the old address with new * @dev Currently there is no way to remove an ID, as attempting to * register the zero address will revert. */ function registerAddress(bytes32 id, address address_) external; /** * @notice Registers multiple address at once * @dev Convenient method to register multiple addresses at once. * @param ids Ids to register addresses under * @param addresses Addresses to register */ function registerMultipleAddresses( bytes32[] calldata ids, address[] calldata addresses ) external; /** * @notice Removes a registered id and it's associated address * @dev Delete the address corresponding to the identifier Time-complexity is O(n) where n is the length of `_idList`. * @param id ID to remove along with it's associated address */ function deleteAddress(bytes32 id) external; /** * @notice Returns the list of all registered identifiers. * @return List of identifiers */ function getIds() external view returns (bytes32[] memory); /** * @notice Returns the list of all registered identifiers * @param id Component identifier * @return The current address represented by an identifier */ function getAddress(bytes32 id) external view returns (address); /** * @notice Returns the TVL Manager Address * @dev Not just a helper function, this makes explicit a key ID for the system * @return TVL Manager Address */ function tvlManagerAddress() external view returns (address); /** * @notice Returns the Chainlink Registry Address * @dev Not just a helper function, this makes explicit a key ID for the system * @return Chainlink Registry Address */ function chainlinkRegistryAddress() external view returns (address); /** * @notice Returns the DAI Pool Address * @dev Not just a helper function, this makes explicit a key ID for the system * @return DAI Pool Address */ function daiPoolAddress() external view returns (address); /** * @notice Returns the USDC Pool Address * @dev Not just a helper function, this makes explicit a key ID for the system * @return USDC Pool Address */ function usdcPoolAddress() external view returns (address); /** * @notice Returns the USDT Pool Address * @dev Not just a helper function, this makes explicit a key ID for the system * @return USDT Pool Address */ function usdtPoolAddress() external view returns (address); /** * @notice Returns the MAPT Pool Address * @dev Not just a helper function, this makes explicit a key ID for the system * @return MAPT Pool Address */ function mAptAddress() external view returns (address); /** * @notice Returns the LP Account Address * @dev Not just a helper function, this makes explicit a key ID for the system * @return LP Account Address */ function lpAccountAddress() external view returns (address); /** * @notice Returns the LP Safe Address * @dev Not just a helper function, this makes explicit a key ID for the system * @return LP Safe Address */ function lpSafeAddress() external view returns (address); /** * @notice Returns the Admin Safe Address * @dev Not just a helper function, this makes explicit a key ID for the system * @return Admin Safe Address */ function adminSafeAddress() external view returns (address); /** * @notice Returns the Emergency Safe Address * @dev Not just a helper function, this makes explicit a key ID for the system * @return Emergency Safe Address */ function emergencySafeAddress() external view returns (address); /** * @notice Returns the Oracle Adapter Address * @dev Not just a helper function, this makes explicit a key ID for the system * @return Oracle Adapter Address */ function oracleAdapterAddress() external view returns (address); /** * @notice Returns the ERC20 Allocation Address * @dev Not just a helper function, this makes explicit a key ID for the system * @return ERC20 Allocation Address */ function erc20AllocationAddress() external view returns (address); } /** SPDX-License-Identifier: UNLICENSED ---------------------------------- ---- APY.Finance comments -------- ---------------------------------- Due to pragma being fixed at 0.6.6, we had to copy over this contract and fix the imports. original path: @chainlink/contracts/src/v0.6/FluxAggregator.sol npm package version: 0.0.9 */ pragma solidity 0.6.11; import "@chainlink/contracts/src/v0.6/Median.sol"; import "@chainlink/contracts/src/v0.6/Owned.sol"; import "@chainlink/contracts/src/v0.6/SafeMath128.sol"; import "@chainlink/contracts/src/v0.6/SafeMath32.sol"; import "@chainlink/contracts/src/v0.6/SafeMath64.sol"; import "@chainlink/contracts/src/v0.6/interfaces/AggregatorV2V3Interface.sol"; import "@chainlink/contracts/src/v0.6/interfaces/AggregatorValidatorInterface.sol"; import "@chainlink/contracts/src/v0.6/interfaces/LinkTokenInterface.sol"; import "@chainlink/contracts/src/v0.6/vendor/SafeMath.sol"; /* solhint-disable */ /** * @title The Prepaid Aggregator contract * @notice Handles aggregating data pushed in from off-chain, and unlocks * payment for oracles as they report. Oracles' submissions are gathered in * rounds, with each round aggregating the submissions for each oracle into a * single answer. The latest aggregated answer is exposed as well as historical * answers and their updated at timestamp. */ contract FluxAggregator is AggregatorV2V3Interface, Owned { using SafeMath for uint256; using SafeMath128 for uint128; using SafeMath64 for uint64; using SafeMath32 for uint32; struct Round { int256 answer; uint64 startedAt; uint64 updatedAt; uint32 answeredInRound; } struct RoundDetails { int256[] submissions; uint32 maxSubmissions; uint32 minSubmissions; uint32 timeout; uint128 paymentAmount; } struct OracleStatus { uint128 withdrawable; uint32 startingRound; uint32 endingRound; uint32 lastReportedRound; uint32 lastStartedRound; int256 latestSubmission; uint16 index; address admin; address pendingAdmin; } struct Requester { bool authorized; uint32 delay; uint32 lastStartedRound; } struct Funds { uint128 available; uint128 allocated; } LinkTokenInterface public linkToken; AggregatorValidatorInterface public validator; // Round related params uint128 public paymentAmount; uint32 public maxSubmissionCount; uint32 public minSubmissionCount; uint32 public restartDelay; uint32 public timeout; uint8 public override decimals; string public override description; int256 public immutable minSubmissionValue; int256 public immutable maxSubmissionValue; uint256 public constant override version = 3; /** * @notice To ensure owner isn't withdrawing required funds as oracles are * submitting updates, we enforce that the contract maintains a minimum * reserve of RESERVE_ROUNDS * oracleCount() LINK earmarked for payment to * oracles. (Of course, this doesn't prevent the contract from running out of * funds without the owner's intervention.) */ uint256 private constant RESERVE_ROUNDS = 2; uint256 private constant MAX_ORACLE_COUNT = 77; uint32 private constant ROUND_MAX = 2**32 - 1; uint256 private constant VALIDATOR_GAS_LIMIT = 100000; // An error specific to the Aggregator V3 Interface, to prevent possible // confusion around accidentally reading unset values as reported values. string private constant V3_NO_DATA_ERROR = "No data present"; uint32 private reportingRoundId; uint32 internal latestRoundId; mapping(address => OracleStatus) private oracles; mapping(uint32 => Round) internal rounds; mapping(uint32 => RoundDetails) internal details; mapping(address => Requester) internal requesters; address[] private oracleAddresses; Funds private recordedFunds; event AvailableFundsUpdated(uint256 indexed amount); event RoundDetailsUpdated( uint128 indexed paymentAmount, uint32 indexed minSubmissionCount, uint32 indexed maxSubmissionCount, uint32 restartDelay, uint32 timeout // measured in seconds ); event OraclePermissionsUpdated( address indexed oracle, bool indexed whitelisted ); event OracleAdminUpdated(address indexed oracle, address indexed newAdmin); event OracleAdminUpdateRequested( address indexed oracle, address admin, address newAdmin ); event SubmissionReceived( int256 indexed submission, uint32 indexed round, address indexed oracle ); event RequesterPermissionsSet( address indexed requester, bool authorized, uint32 delay ); event ValidatorUpdated(address indexed previous, address indexed current); /** * @notice set up the aggregator with initial configuration * @param _link The address of the LINK token * @param _paymentAmount The amount paid of LINK paid to each oracle per submission, in wei (units of 10⁻¹⁸ LINK) * @param _timeout is the number of seconds after the previous round that are * allowed to lapse before allowing an oracle to skip an unfinished round * @param _validator is an optional contract address for validating * external validation of answers * @param _minSubmissionValue is an immutable check for a lower bound of what * submission values are accepted from an oracle * @param _maxSubmissionValue is an immutable check for an upper bound of what * submission values are accepted from an oracle * @param _decimals represents the number of decimals to offset the answer by * @param _description a short description of what is being reported */ constructor( address _link, uint128 _paymentAmount, uint32 _timeout, address _validator, int256 _minSubmissionValue, int256 _maxSubmissionValue, uint8 _decimals, string memory _description ) public { linkToken = LinkTokenInterface(_link); updateFutureRounds(_paymentAmount, 0, 0, 0, _timeout); setValidator(_validator); minSubmissionValue = _minSubmissionValue; maxSubmissionValue = _maxSubmissionValue; decimals = _decimals; description = _description; rounds[0].updatedAt = uint64(block.timestamp.sub(uint256(_timeout))); } /** * @notice called by oracles when they have witnessed a need to update * @param _roundId is the ID of the round this submission pertains to * @param _submission is the updated data that the oracle is submitting */ function submit(uint256 _roundId, int256 _submission) external { bytes memory error = validateOracleRound(msg.sender, uint32(_roundId)); require( _submission >= minSubmissionValue, "value below minSubmissionValue" ); require( _submission <= maxSubmissionValue, "value above maxSubmissionValue" ); require(error.length == 0, string(error)); oracleInitializeNewRound(uint32(_roundId)); recordSubmission(_submission, uint32(_roundId)); (bool updated, int256 newAnswer) = updateRoundAnswer(uint32(_roundId)); payOracle(uint32(_roundId)); deleteRoundDetails(uint32(_roundId)); if (updated) { validateAnswer(uint32(_roundId), newAnswer); } } /** * @notice called by the owner to remove and add new oracles as well as * update the round related parameters that pertain to total oracle count * @param _removed is the list of addresses for the new Oracles being removed * @param _added is the list of addresses for the new Oracles being added * @param _addedAdmins is the admin addresses for the new respective _added * list. Only this address is allowed to access the respective oracle's funds * @param _minSubmissions is the new minimum submission count for each round * @param _maxSubmissions is the new maximum submission count for each round * @param _restartDelay is the number of rounds an Oracle has to wait before * they can initiate a round */ function changeOracles( address[] calldata _removed, address[] calldata _added, address[] calldata _addedAdmins, uint32 _minSubmissions, uint32 _maxSubmissions, uint32 _restartDelay ) external onlyOwner() { for (uint256 i = 0; i < _removed.length; i++) { removeOracle(_removed[i]); } require( _added.length == _addedAdmins.length, "need same oracle and admin count" ); require( uint256(oracleCount()).add(_added.length) <= MAX_ORACLE_COUNT, "max oracles allowed" ); for (uint256 i = 0; i < _added.length; i++) { addOracle(_added[i], _addedAdmins[i]); } updateFutureRounds( paymentAmount, _minSubmissions, _maxSubmissions, _restartDelay, timeout ); } /** * @notice update the round and payment related parameters for subsequent * rounds * @param _paymentAmount is the payment amount for subsequent rounds * @param _minSubmissions is the new minimum submission count for each round * @param _maxSubmissions is the new maximum submission count for each round * @param _restartDelay is the number of rounds an Oracle has to wait before * they can initiate a round */ function updateFutureRounds( uint128 _paymentAmount, uint32 _minSubmissions, uint32 _maxSubmissions, uint32 _restartDelay, uint32 _timeout ) public onlyOwner() { uint32 oracleNum = oracleCount(); // Save on storage reads require( _maxSubmissions >= _minSubmissions, "max must equal/exceed min" ); require(oracleNum >= _maxSubmissions, "max cannot exceed total"); require( oracleNum == 0 || oracleNum > _restartDelay, "delay cannot exceed total" ); require( recordedFunds.available >= requiredReserve(_paymentAmount), "insufficient funds for payment" ); if (oracleCount() > 0) { require(_minSubmissions > 0, "min must be greater than 0"); } paymentAmount = _paymentAmount; minSubmissionCount = _minSubmissions; maxSubmissionCount = _maxSubmissions; restartDelay = _restartDelay; timeout = _timeout; emit RoundDetailsUpdated( paymentAmount, _minSubmissions, _maxSubmissions, _restartDelay, _timeout ); } /** * @notice the amount of payment yet to be withdrawn by oracles */ function allocatedFunds() external view returns (uint128) { return recordedFunds.allocated; } /** * @notice the amount of future funding available to oracles */ function availableFunds() external view returns (uint128) { return recordedFunds.available; } /** * @notice recalculate the amount of LINK available for payouts */ function updateAvailableFunds() public { Funds memory funds = recordedFunds; uint256 nowAvailable = linkToken.balanceOf(address(this)).sub(funds.allocated); if (funds.available != nowAvailable) { recordedFunds.available = uint128(nowAvailable); emit AvailableFundsUpdated(nowAvailable); } } /** * @notice returns the number of oracles */ function oracleCount() public view returns (uint8) { return uint8(oracleAddresses.length); } /** * @notice returns an array of addresses containing the oracles on contract */ function getOracles() external view returns (address[] memory) { return oracleAddresses; } /** * @notice get the most recently reported answer * * @dev #[deprecated] Use latestRoundData instead. This does not error if no * answer has been reached, it will simply return 0. Either wait to point to * an already answered Aggregator or use the recommended latestRoundData * instead which includes better verification information. */ function latestAnswer() public view virtual override returns (int256) { return rounds[latestRoundId].answer; } /** * @notice get the most recent updated at timestamp * * @dev #[deprecated] Use latestRoundData instead. This does not error if no * answer has been reached, it will simply return 0. Either wait to point to * an already answered Aggregator or use the recommended latestRoundData * instead which includes better verification information. */ function latestTimestamp() public view virtual override returns (uint256) { return rounds[latestRoundId].updatedAt; } /** * @notice get the ID of the last updated round * * @dev #[deprecated] Use latestRoundData instead. This does not error if no * answer has been reached, it will simply return 0. Either wait to point to * an already answered Aggregator or use the recommended latestRoundData * instead which includes better verification information. */ function latestRound() public view virtual override returns (uint256) { return latestRoundId; } /** * @notice get past rounds answers * @param _roundId the round number to retrieve the answer for * * @dev #[deprecated] Use getRoundData instead. This does not error if no * answer has been reached, it will simply return 0. Either wait to point to * an already answered Aggregator or use the recommended getRoundData * instead which includes better verification information. */ function getAnswer(uint256 _roundId) public view virtual override returns (int256) { if (validRoundId(_roundId)) { return rounds[uint32(_roundId)].answer; } return 0; } /** * @notice get timestamp when an answer was last updated * @param _roundId the round number to retrieve the updated timestamp for * * @dev #[deprecated] Use getRoundData instead. This does not error if no * answer has been reached, it will simply return 0. Either wait to point to * an already answered Aggregator or use the recommended getRoundData * instead which includes better verification information. */ function getTimestamp(uint256 _roundId) public view virtual override returns (uint256) { if (validRoundId(_roundId)) { return rounds[uint32(_roundId)].updatedAt; } return 0; } /** * @notice get data about a round. Consumers are encouraged to check * that they're receiving fresh data by inspecting the updatedAt and * answeredInRound return values. * @param _roundId the round ID to retrieve the round data for * @return roundId is the round ID for which data was retrieved * @return answer is the answer for the given round * @return startedAt is the timestamp when the round was started. This is 0 * if the round hasn't been started yet. * @return updatedAt is the timestamp when the round last was updated (i.e. * answer was last computed) * @return answeredInRound is the round ID of the round in which the answer * was computed. answeredInRound may be smaller than roundId when the round * timed out. answeredInRound is equal to roundId when the round didn't time out * and was completed regularly. * @dev Note that for in-progress rounds (i.e. rounds that haven't yet received * maxSubmissions) answer and updatedAt may change between queries. */ function getRoundData(uint80 _roundId) public view virtual override returns ( uint80 roundId, int256 answer, uint256 startedAt, uint256 updatedAt, uint80 answeredInRound ) { Round memory r = rounds[uint32(_roundId)]; require( r.answeredInRound > 0 && validRoundId(_roundId), V3_NO_DATA_ERROR ); return ( _roundId, r.answer, r.startedAt, r.updatedAt, r.answeredInRound ); } /** * @notice get data about the latest round. Consumers are encouraged to check * that they're receiving fresh data by inspecting the updatedAt and * answeredInRound return values. Consumers are encouraged to * use this more fully featured method over the "legacy" latestRound/ * latestAnswer/latestTimestamp functions. Consumers are encouraged to check * that they're receiving fresh data by inspecting the updatedAt and * answeredInRound return values. * @return roundId is the round ID for which data was retrieved * @return answer is the answer for the given round * @return startedAt is the timestamp when the round was started. This is 0 * if the round hasn't been started yet. * @return updatedAt is the timestamp when the round last was updated (i.e. * answer was last computed) * @return answeredInRound is the round ID of the round in which the answer * was computed. answeredInRound may be smaller than roundId when the round * timed out. answeredInRound is equal to roundId when the round didn't time * out and was completed regularly. * @dev Note that for in-progress rounds (i.e. rounds that haven't yet * received maxSubmissions) answer and updatedAt may change between queries. */ function latestRoundData() public view virtual override returns ( uint80 roundId, int256 answer, uint256 startedAt, uint256 updatedAt, uint80 answeredInRound ) { return getRoundData(latestRoundId); } /** * @notice query the available amount of LINK for an oracle to withdraw */ function withdrawablePayment(address _oracle) external view returns (uint256) { return oracles[_oracle].withdrawable; } /** * @notice transfers the oracle's LINK to another address. Can only be called * by the oracle's admin. * @param _oracle is the oracle whose LINK is transferred * @param _recipient is the address to send the LINK to * @param _amount is the amount of LINK to send */ function withdrawPayment( address _oracle, address _recipient, uint256 _amount ) external { require(oracles[_oracle].admin == msg.sender, "only callable by admin"); // Safe to downcast _amount because the total amount of LINK is less than 2^128. uint128 amount = uint128(_amount); uint128 available = oracles[_oracle].withdrawable; require(available >= amount, "insufficient withdrawable funds"); oracles[_oracle].withdrawable = available.sub(amount); recordedFunds.allocated = recordedFunds.allocated.sub(amount); assert(linkToken.transfer(_recipient, uint256(amount))); } /** * @notice transfers the owner's LINK to another address * @param _recipient is the address to send the LINK to * @param _amount is the amount of LINK to send */ function withdrawFunds(address _recipient, uint256 _amount) external onlyOwner() { uint256 available = uint256(recordedFunds.available); require( available.sub(requiredReserve(paymentAmount)) >= _amount, "insufficient reserve funds" ); require( linkToken.transfer(_recipient, _amount), "token transfer failed" ); updateAvailableFunds(); } /** * @notice get the admin address of an oracle * @param _oracle is the address of the oracle whose admin is being queried */ function getAdmin(address _oracle) external view returns (address) { return oracles[_oracle].admin; } /** * @notice transfer the admin address for an oracle * @param _oracle is the address of the oracle whose admin is being transferred * @param _newAdmin is the new admin address */ function transferAdmin(address _oracle, address _newAdmin) external { require(oracles[_oracle].admin == msg.sender, "only callable by admin"); oracles[_oracle].pendingAdmin = _newAdmin; emit OracleAdminUpdateRequested(_oracle, msg.sender, _newAdmin); } /** * @notice accept the admin address transfer for an oracle * @param _oracle is the address of the oracle whose admin is being transferred */ function acceptAdmin(address _oracle) external { require( oracles[_oracle].pendingAdmin == msg.sender, "only callable by pending admin" ); oracles[_oracle].pendingAdmin = address(0); oracles[_oracle].admin = msg.sender; emit OracleAdminUpdated(_oracle, msg.sender); } /** * @notice allows non-oracles to request a new round */ function requestNewRound() external returns (uint80) { require(requesters[msg.sender].authorized, "not authorized requester"); uint32 current = reportingRoundId; require( rounds[current].updatedAt > 0 || timedOut(current), "prev round must be supersedable" ); uint32 newRoundId = current.add(1); requesterInitializeNewRound(newRoundId); return newRoundId; } /** * @notice allows the owner to specify new non-oracles to start new rounds * @param _requester is the address to set permissions for * @param _authorized is a boolean specifying whether they can start new rounds or not * @param _delay is the number of rounds the requester must wait before starting another round */ function setRequesterPermissions( address _requester, bool _authorized, uint32 _delay ) external onlyOwner() { if (requesters[_requester].authorized == _authorized) return; if (_authorized) { requesters[_requester].authorized = _authorized; requesters[_requester].delay = _delay; } else { delete requesters[_requester]; } emit RequesterPermissionsSet(_requester, _authorized, _delay); } /** * @notice called through LINK's transferAndCall to update available funds * in the same transaction as the funds were transferred to the aggregator * @param _data is mostly ignored. It is checked for length, to be sure * nothing strange is passed in. */ function onTokenTransfer( address, uint256, bytes calldata _data ) external { require(_data.length == 0, "transfer doesn't accept calldata"); updateAvailableFunds(); } /** * @notice a method to provide all current info oracles need. Intended only * only to be callable by oracles. Not for use by contracts to read state. * @param _oracle the address to look up information for. */ function oracleRoundState(address _oracle, uint32 _queriedRoundId) external view returns ( bool _eligibleToSubmit, uint32 _roundId, int256 _latestSubmission, uint64 _startedAt, uint64 _timeout, uint128 _availableFunds, uint8 _oracleCount, uint128 _paymentAmount ) { require(msg.sender == tx.origin, "off-chain reading only"); if (_queriedRoundId > 0) { Round storage round = rounds[_queriedRoundId]; RoundDetails storage details = details[_queriedRoundId]; return ( eligibleForSpecificRound(_oracle, _queriedRoundId), _queriedRoundId, oracles[_oracle].latestSubmission, round.startedAt, details.timeout, recordedFunds.available, oracleCount(), (round.startedAt > 0 ? details.paymentAmount : paymentAmount) ); } else { return oracleRoundStateSuggestRound(_oracle); } } /** * @notice method to update the address which does external data validation. * @param _newValidator designates the address of the new validation contract. */ function setValidator(address _newValidator) public onlyOwner() { address previous = address(validator); if (previous != _newValidator) { validator = AggregatorValidatorInterface(_newValidator); emit ValidatorUpdated(previous, _newValidator); } } /** * Private */ function initializeNewRound(uint32 _roundId) private { updateTimedOutRoundInfo(_roundId.sub(1)); reportingRoundId = _roundId; RoundDetails memory nextDetails = RoundDetails( new int256[](0), maxSubmissionCount, minSubmissionCount, timeout, paymentAmount ); details[_roundId] = nextDetails; rounds[_roundId].startedAt = uint64(block.timestamp); emit NewRound(_roundId, msg.sender, rounds[_roundId].startedAt); } function oracleInitializeNewRound(uint32 _roundId) private { if (!newRound(_roundId)) return; uint256 lastStarted = oracles[msg.sender].lastStartedRound; // cache storage reads if (_roundId <= lastStarted + restartDelay && lastStarted != 0) return; initializeNewRound(_roundId); oracles[msg.sender].lastStartedRound = _roundId; } function requesterInitializeNewRound(uint32 _roundId) private { if (!newRound(_roundId)) return; uint256 lastStarted = requesters[msg.sender].lastStartedRound; // cache storage reads require( _roundId > lastStarted + requesters[msg.sender].delay || lastStarted == 0, "must delay requests" ); initializeNewRound(_roundId); requesters[msg.sender].lastStartedRound = _roundId; } function updateTimedOutRoundInfo(uint32 _roundId) private { if (!timedOut(_roundId)) return; uint32 prevId = _roundId.sub(1); rounds[_roundId].answer = rounds[prevId].answer; rounds[_roundId].answeredInRound = rounds[prevId].answeredInRound; rounds[_roundId].updatedAt = uint64(block.timestamp); delete details[_roundId]; } function eligibleForSpecificRound(address _oracle, uint32 _queriedRoundId) private view returns (bool _eligible) { if (rounds[_queriedRoundId].startedAt > 0) { return acceptingSubmissions(_queriedRoundId) && validateOracleRound(_oracle, _queriedRoundId).length == 0; } else { return delayed(_oracle, _queriedRoundId) && validateOracleRound(_oracle, _queriedRoundId).length == 0; } } function oracleRoundStateSuggestRound(address _oracle) private view returns ( bool _eligibleToSubmit, uint32 _roundId, int256 _latestSubmission, uint64 _startedAt, uint64 _timeout, uint128 _availableFunds, uint8 _oracleCount, uint128 _paymentAmount ) { Round storage round = rounds[0]; OracleStatus storage oracle = oracles[_oracle]; bool shouldSupersede = oracle.lastReportedRound == reportingRoundId || !acceptingSubmissions(reportingRoundId); // Instead of nudging oracles to submit to the next round, the inclusion of // the shouldSupersede bool in the if condition pushes them towards // submitting in a currently open round. if (supersedable(reportingRoundId) && shouldSupersede) { _roundId = reportingRoundId.add(1); round = rounds[_roundId]; _paymentAmount = paymentAmount; _eligibleToSubmit = delayed(_oracle, _roundId); } else { _roundId = reportingRoundId; round = rounds[_roundId]; _paymentAmount = details[_roundId].paymentAmount; _eligibleToSubmit = acceptingSubmissions(_roundId); } if (validateOracleRound(_oracle, _roundId).length != 0) { _eligibleToSubmit = false; } return ( _eligibleToSubmit, _roundId, oracle.latestSubmission, round.startedAt, details[_roundId].timeout, recordedFunds.available, oracleCount(), _paymentAmount ); } function updateRoundAnswer(uint32 _roundId) internal returns (bool, int256) { if ( details[_roundId].submissions.length < details[_roundId].minSubmissions ) { return (false, 0); } int256 newAnswer = Median.calculateInplace(details[_roundId].submissions); rounds[_roundId].answer = newAnswer; rounds[_roundId].updatedAt = uint64(block.timestamp); rounds[_roundId].answeredInRound = _roundId; latestRoundId = _roundId; emit AnswerUpdated(newAnswer, _roundId, now); return (true, newAnswer); } function validateAnswer(uint32 _roundId, int256 _newAnswer) private { AggregatorValidatorInterface av = validator; // cache storage reads if (address(av) == address(0)) return; uint32 prevRound = _roundId.sub(1); uint32 prevAnswerRoundId = rounds[prevRound].answeredInRound; int256 prevRoundAnswer = rounds[prevRound].answer; // We do not want the validator to ever prevent reporting, so we limit its // gas usage and catch any errors that may arise. try av.validate{gas: VALIDATOR_GAS_LIMIT}( prevAnswerRoundId, prevRoundAnswer, _roundId, _newAnswer ) {} catch {} } function payOracle(uint32 _roundId) private { uint128 payment = details[_roundId].paymentAmount; Funds memory funds = recordedFunds; funds.available = funds.available.sub(payment); funds.allocated = funds.allocated.add(payment); recordedFunds = funds; oracles[msg.sender].withdrawable = oracles[msg.sender].withdrawable.add( payment ); emit AvailableFundsUpdated(funds.available); } function recordSubmission(int256 _submission, uint32 _roundId) private { require( acceptingSubmissions(_roundId), "round not accepting submissions" ); details[_roundId].submissions.push(_submission); oracles[msg.sender].lastReportedRound = _roundId; oracles[msg.sender].latestSubmission = _submission; emit SubmissionReceived(_submission, _roundId, msg.sender); } function deleteRoundDetails(uint32 _roundId) private { if ( details[_roundId].submissions.length < details[_roundId].maxSubmissions ) return; delete details[_roundId]; } function timedOut(uint32 _roundId) private view returns (bool) { uint64 startedAt = rounds[_roundId].startedAt; uint32 roundTimeout = details[_roundId].timeout; return startedAt > 0 && roundTimeout > 0 && startedAt.add(roundTimeout) < block.timestamp; } function getStartingRound(address _oracle) private view returns (uint32) { uint32 currentRound = reportingRoundId; if (currentRound != 0 && currentRound == oracles[_oracle].endingRound) { return currentRound; } return currentRound.add(1); } function previousAndCurrentUnanswered(uint32 _roundId, uint32 _rrId) private view returns (bool) { return _roundId.add(1) == _rrId && rounds[_rrId].updatedAt == 0; } function requiredReserve(uint256 payment) private view returns (uint256) { return payment.mul(oracleCount()).mul(RESERVE_ROUNDS); } function addOracle(address _oracle, address _admin) private { require(!oracleEnabled(_oracle), "oracle already enabled"); require(_admin != address(0), "cannot set admin to 0"); require( oracles[_oracle].admin == address(0) || oracles[_oracle].admin == _admin, "owner cannot overwrite admin" ); oracles[_oracle].startingRound = getStartingRound(_oracle); oracles[_oracle].endingRound = ROUND_MAX; oracles[_oracle].index = uint16(oracleAddresses.length); oracleAddresses.push(_oracle); oracles[_oracle].admin = _admin; emit OraclePermissionsUpdated(_oracle, true); emit OracleAdminUpdated(_oracle, _admin); } function removeOracle(address _oracle) private { require(oracleEnabled(_oracle), "oracle not enabled"); oracles[_oracle].endingRound = reportingRoundId.add(1); address tail = oracleAddresses[uint256(oracleCount()).sub(1)]; uint16 index = oracles[_oracle].index; oracles[tail].index = index; delete oracles[_oracle].index; oracleAddresses[index] = tail; oracleAddresses.pop(); emit OraclePermissionsUpdated(_oracle, false); } function validateOracleRound(address _oracle, uint32 _roundId) private view returns (bytes memory) { // cache storage reads uint32 startingRound = oracles[_oracle].startingRound; uint32 rrId = reportingRoundId; if (startingRound == 0) return "not enabled oracle"; if (startingRound > _roundId) return "not yet enabled oracle"; if (oracles[_oracle].endingRound < _roundId) return "no longer allowed oracle"; if (oracles[_oracle].lastReportedRound >= _roundId) return "cannot report on previous rounds"; if ( _roundId != rrId && _roundId != rrId.add(1) && !previousAndCurrentUnanswered(_roundId, rrId) ) return "invalid round to report"; if (_roundId != 1 && !supersedable(_roundId.sub(1))) return "previous round not supersedable"; } function supersedable(uint32 _roundId) private view returns (bool) { return rounds[_roundId].updatedAt > 0 || timedOut(_roundId); } function oracleEnabled(address _oracle) private view returns (bool) { return oracles[_oracle].endingRound == ROUND_MAX; } function acceptingSubmissions(uint32 _roundId) private view returns (bool) { return details[_roundId].maxSubmissions != 0; } function delayed(address _oracle, uint32 _roundId) private view returns (bool) { uint256 lastStarted = oracles[_oracle].lastStartedRound; return _roundId > lastStarted + restartDelay || lastStarted == 0; } function newRound(uint32 _roundId) private view returns (bool) { return _roundId == reportingRoundId.add(1); } function validRoundId(uint256 _roundId) private view returns (bool) { return _roundId <= ROUND_MAX; } } // SPDX-License-Identifier: BUSDL-1.1 pragma solidity 0.6.11; /** * @notice Interface for securely interacting with Chainlink aggregators */ interface IOracleAdapter { struct Value { uint256 value; uint256 periodEnd; } /// @notice Event fired when asset's pricing source (aggregator) is updated event AssetSourceUpdated(address indexed asset, address indexed source); /// @notice Event fired when the TVL aggregator address is updated event TvlSourceUpdated(address indexed source); /** * @notice Set the TVL source (aggregator) * @param source The new TVL source (aggregator) */ function emergencySetTvlSource(address source) external; /** * @notice Set an asset's price source (aggregator) * @param asset The asset to change the source of * @param source The new source (aggregator) */ function emergencySetAssetSource(address asset, address source) external; /** * @notice Set multiple assets' pricing sources * @param assets An array of assets (tokens) * @param sources An array of price sources (aggregators) */ function emergencySetAssetSources( address[] memory assets, address[] memory sources ) external; /** * @notice Retrieve the asset's price from its pricing source * @param asset The asset address * @return The price of the asset */ function getAssetPrice(address asset) external view returns (uint256); /** * @notice Retrieve the deployed TVL from the TVL aggregator * @return The TVL */ function getTvl() external view returns (uint256); } // SPDX-License-Identifier: BUSDL-1.1 pragma solidity 0.6.11; import {IOracleAdapter} from "./IOracleAdapter.sol"; interface IOverrideOracle is IOracleAdapter { /** * @notice Event fired when asset value is set manually * @param asset The asset that is being overridden * @param value The new value used for the override * @param period The number of blocks the override will be active for * @param periodEnd The block on which the override ends */ event AssetValueSet( address asset, uint256 value, uint256 period, uint256 periodEnd ); /** * @notice Event fired when manually submitted asset value is * invalidated, allowing usual Chainlink pricing. */ event AssetValueUnset(address asset); /** * @notice Event fired when deployed TVL is set manually * @param value The new value used for the override * @param period The number of blocks the override will be active for * @param periodEnd The block on which the override ends */ event TvlSet(uint256 value, uint256 period, uint256 periodEnd); /** * @notice Event fired when manually submitted TVL is * invalidated, allowing usual Chainlink pricing. */ event TvlUnset(); /** * @notice Manually override the asset pricing source with a value * @param asset The asset that is being overriden * @param value asset value to return instead of from Chainlink * @param period length of time, in number of blocks, to use manual override */ function emergencySetAssetValue( address asset, uint256 value, uint256 period ) external; /** * @notice Revoke manually set value, allowing usual Chainlink pricing * @param asset address of asset to price */ function emergencyUnsetAssetValue(address asset) external; /** * @notice Manually override the TVL source with a value * @param value TVL to return instead of from Chainlink * @param period length of time, in number of blocks, to use manual override */ function emergencySetTvl(uint256 value, uint256 period) external; /// @notice Revoke manually set value, allowing usual Chainlink pricing function emergencyUnsetTvl() external; /// @notice Check if TVL has active manual override function hasTvlOverride() external view returns (bool); /** * @notice Check if asset has active manual override * @param asset address of the asset * @return `true` if manual override is active */ function hasAssetOverride(address asset) external view returns (bool); } // SPDX-License-Identifier: BUSDL-1.1 pragma solidity 0.6.11; import {IOracleAdapter} from "./IOracleAdapter.sol"; /** * @notice For an `IOracleAdapter` that can be locked and unlocked */ interface ILockingOracle is IOracleAdapter { /// @notice Event fired when using the default lock event DefaultLocked(address locker, uint256 defaultPeriod, uint256 lockEnd); /// @notice Event fired when using a specified lock period event Locked(address locker, uint256 activePeriod, uint256 lockEnd); /// @notice Event fired when changing the default locking period event DefaultLockPeriodChanged(uint256 newPeriod); /// @notice Event fired when unlocking the adapter event Unlocked(); /// @notice Event fired when updating the threshold for stale data event ChainlinkStalePeriodUpdated(uint256 period); /// @notice Block price/value retrieval for the default locking duration function lock() external; /** * @notice Block price/value retrieval for the specified duration. * @param period number of blocks to block retrieving values */ function lockFor(uint256 period) external; /** * @notice Unblock price/value retrieval. Should only be callable * by the Emergency Safe. */ function emergencyUnlock() external; /** * @notice Set the length of time before values can be retrieved. * @param newPeriod number of blocks before values can be retrieved */ function setDefaultLockPeriod(uint256 newPeriod) external; /** * @notice Set the length of time before an agg value is considered stale. * @param chainlinkStalePeriod_ the length of time in seconds */ function setChainlinkStalePeriod(uint256 chainlinkStalePeriod_) external; /** * @notice Get the length of time, in number of blocks, before values * can be retrieved. */ function defaultLockPeriod() external returns (uint256 period); /// @notice Check if the adapter is blocked from retrieving values. function isLocked() external view returns (bool); } pragma solidity ^0.6.0; import "./vendor/SafeMath.sol"; import "./SignedSafeMath.sol"; library Median { using SignedSafeMath for int256; int256 constant INT_MAX = 2**255-1; /** * @notice Returns the sorted middle, or the average of the two middle indexed items if the * array has an even number of elements. * @dev The list passed as an argument isn't modified. * @dev This algorithm has expected runtime O(n), but for adversarially chosen inputs * the runtime is O(n^2). * @param list The list of elements to compare */ function calculate(int256[] memory list) internal pure returns (int256) { return calculateInplace(copy(list)); } /** * @notice See documentation for function calculate. * @dev The list passed as an argument may be permuted. */ function calculateInplace(int256[] memory list) internal pure returns (int256) { require(0 < list.length, "list must not be empty"); uint256 len = list.length; uint256 middleIndex = len / 2; if (len % 2 == 0) { int256 median1; int256 median2; (median1, median2) = quickselectTwo(list, 0, len - 1, middleIndex - 1, middleIndex); return SignedSafeMath.avg(median1, median2); } else { return quickselect(list, 0, len - 1, middleIndex); } } /** * @notice Maximum length of list that shortSelectTwo can handle */ uint256 constant SHORTSELECTTWO_MAX_LENGTH = 7; /** * @notice Select the k1-th and k2-th element from list of length at most 7 * @dev Uses an optimal sorting network */ function shortSelectTwo( int256[] memory list, uint256 lo, uint256 hi, uint256 k1, uint256 k2 ) private pure returns (int256 k1th, int256 k2th) { // Uses an optimal sorting network (https://en.wikipedia.org/wiki/Sorting_network) // for lists of length 7. Network layout is taken from // http://jgamble.ripco.net/cgi-bin/nw.cgi?inputs=7&algorithm=hibbard&output=svg uint256 len = hi + 1 - lo; int256 x0 = list[lo + 0]; int256 x1 = 1 < len ? list[lo + 1] : INT_MAX; int256 x2 = 2 < len ? list[lo + 2] : INT_MAX; int256 x3 = 3 < len ? list[lo + 3] : INT_MAX; int256 x4 = 4 < len ? list[lo + 4] : INT_MAX; int256 x5 = 5 < len ? list[lo + 5] : INT_MAX; int256 x6 = 6 < len ? list[lo + 6] : INT_MAX; if (x0 > x1) {(x0, x1) = (x1, x0);} if (x2 > x3) {(x2, x3) = (x3, x2);} if (x4 > x5) {(x4, x5) = (x5, x4);} if (x0 > x2) {(x0, x2) = (x2, x0);} if (x1 > x3) {(x1, x3) = (x3, x1);} if (x4 > x6) {(x4, x6) = (x6, x4);} if (x1 > x2) {(x1, x2) = (x2, x1);} if (x5 > x6) {(x5, x6) = (x6, x5);} if (x0 > x4) {(x0, x4) = (x4, x0);} if (x1 > x5) {(x1, x5) = (x5, x1);} if (x2 > x6) {(x2, x6) = (x6, x2);} if (x1 > x4) {(x1, x4) = (x4, x1);} if (x3 > x6) {(x3, x6) = (x6, x3);} if (x2 > x4) {(x2, x4) = (x4, x2);} if (x3 > x5) {(x3, x5) = (x5, x3);} if (x3 > x4) {(x3, x4) = (x4, x3);} uint256 index1 = k1 - lo; if (index1 == 0) {k1th = x0;} else if (index1 == 1) {k1th = x1;} else if (index1 == 2) {k1th = x2;} else if (index1 == 3) {k1th = x3;} else if (index1 == 4) {k1th = x4;} else if (index1 == 5) {k1th = x5;} else if (index1 == 6) {k1th = x6;} else {revert("k1 out of bounds");} uint256 index2 = k2 - lo; if (k1 == k2) {return (k1th, k1th);} else if (index2 == 0) {return (k1th, x0);} else if (index2 == 1) {return (k1th, x1);} else if (index2 == 2) {return (k1th, x2);} else if (index2 == 3) {return (k1th, x3);} else if (index2 == 4) {return (k1th, x4);} else if (index2 == 5) {return (k1th, x5);} else if (index2 == 6) {return (k1th, x6);} else {revert("k2 out of bounds");} } /** * @notice Selects the k-th ranked element from list, looking only at indices between lo and hi * (inclusive). Modifies list in-place. */ function quickselect(int256[] memory list, uint256 lo, uint256 hi, uint256 k) private pure returns (int256 kth) { require(lo <= k); require(k <= hi); while (lo < hi) { if (hi - lo < SHORTSELECTTWO_MAX_LENGTH) { int256 ignore; (kth, ignore) = shortSelectTwo(list, lo, hi, k, k); return kth; } uint256 pivotIndex = partition(list, lo, hi); if (k <= pivotIndex) { // since pivotIndex < (original hi passed to partition), // termination is guaranteed in this case hi = pivotIndex; } else { // since (original lo passed to partition) <= pivotIndex, // termination is guaranteed in this case lo = pivotIndex + 1; } } return list[lo]; } /** * @notice Selects the k1-th and k2-th ranked elements from list, looking only at indices between * lo and hi (inclusive). Modifies list in-place. */ function quickselectTwo( int256[] memory list, uint256 lo, uint256 hi, uint256 k1, uint256 k2 ) internal // for testing pure returns (int256 k1th, int256 k2th) { require(k1 < k2); require(lo <= k1 && k1 <= hi); require(lo <= k2 && k2 <= hi); while (true) { if (hi - lo < SHORTSELECTTWO_MAX_LENGTH) { return shortSelectTwo(list, lo, hi, k1, k2); } uint256 pivotIdx = partition(list, lo, hi); if (k2 <= pivotIdx) { hi = pivotIdx; } else if (pivotIdx < k1) { lo = pivotIdx + 1; } else { assert(k1 <= pivotIdx && pivotIdx < k2); k1th = quickselect(list, lo, pivotIdx, k1); k2th = quickselect(list, pivotIdx + 1, hi, k2); return (k1th, k2th); } } } /** * @notice Partitions list in-place using Hoare's partitioning scheme. * Only elements of list between indices lo and hi (inclusive) will be modified. * Returns an index i, such that: * - lo <= i < hi * - forall j in [lo, i]. list[j] <= list[i] * - forall j in [i, hi]. list[i] <= list[j] */ function partition(int256[] memory list, uint256 lo, uint256 hi) private pure returns (uint256) { // We don't care about overflow of the addition, because it would require a list // larger than any feasible computer's memory. int256 pivot = list[(lo + hi) / 2]; lo -= 1; // this can underflow. that's intentional. hi += 1; while (true) { do { lo += 1; } while (list[lo] < pivot); do { hi -= 1; } while (list[hi] > pivot); if (lo < hi) { (list[lo], list[hi]) = (list[hi], list[lo]); } else { // Let orig_lo and orig_hi be the original values of lo and hi passed to partition. // Then, hi < orig_hi, because hi decreases *strictly* monotonically // in each loop iteration and // - either list[orig_hi] > pivot, in which case the first loop iteration // will achieve hi < orig_hi; // - or list[orig_hi] <= pivot, in which case at least two loop iterations are // needed: // - lo will have to stop at least once in the interval // [orig_lo, (orig_lo + orig_hi)/2] // - (orig_lo + orig_hi)/2 < orig_hi return hi; } } } /** * @notice Makes an in-memory copy of the array passed in * @param list Reference to the array to be copied */ function copy(int256[] memory list) private pure returns(int256[] memory) { int256[] memory list2 = new int256[](list.length); for (uint256 i = 0; i < list.length; i++) { list2[i] = list[i]; } return list2; } } pragma solidity ^0.6.0; /** * @title The Owned contract * @notice A contract with helpers for basic contract ownership. */ contract Owned { address payable public owner; address private pendingOwner; event OwnershipTransferRequested( address indexed from, address indexed to ); event OwnershipTransferred( address indexed from, address indexed to ); constructor() public { owner = msg.sender; } /** * @dev Allows an owner to begin transferring ownership to a new address, * pending. */ function transferOwnership(address _to) external onlyOwner() { pendingOwner = _to; emit OwnershipTransferRequested(owner, _to); } /** * @dev Allows an ownership transfer to be completed by the recipient. */ function acceptOwnership() external { require(msg.sender == pendingOwner, "Must be proposed owner"); address oldOwner = owner; owner = msg.sender; pendingOwner = address(0); emit OwnershipTransferred(oldOwner, msg.sender); } /** * @dev Reverts if called by anyone other than the contract owner. */ modifier onlyOwner() { require(msg.sender == owner, "Only callable by owner"); _; } } 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. * * This library is a version of Open Zeppelin's SafeMath, modified to support * unsigned 128 bit integers. */ library SafeMath128 { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * - Addition cannot overflow. */ function add(uint128 a, uint128 b) internal pure returns (uint128) { uint128 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(uint128 a, uint128 b) internal pure returns (uint128) { require(b <= a, "SafeMath: subtraction overflow"); uint128 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(uint128 a, uint128 b) internal pure returns (uint128) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522 if (a == 0) { return 0; } uint128 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(uint128 a, uint128 b) internal pure returns (uint128) { // Solidity only automatically asserts when dividing by 0 require(b > 0, "SafeMath: division by zero"); uint128 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(uint128 a, uint128 b) internal pure returns (uint128) { require(b != 0, "SafeMath: modulo by zero"); return a % b; } } 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. * * This library is a version of Open Zeppelin's SafeMath, modified to support * unsigned 32 bit integers. */ library SafeMath32 { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * - Addition cannot overflow. */ function add(uint32 a, uint32 b) internal pure returns (uint32) { uint32 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(uint32 a, uint32 b) internal pure returns (uint32) { require(b <= a, "SafeMath: subtraction overflow"); uint32 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(uint32 a, uint32 b) internal pure returns (uint32) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522 if (a == 0) { return 0; } uint32 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(uint32 a, uint32 b) internal pure returns (uint32) { // Solidity only automatically asserts when dividing by 0 require(b > 0, "SafeMath: division by zero"); uint32 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(uint32 a, uint32 b) internal pure returns (uint32) { require(b != 0, "SafeMath: modulo by zero"); return a % b; } } 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. * * This library is a version of Open Zeppelin's SafeMath, modified to support * unsigned 64 bit integers. */ library SafeMath64 { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * - Addition cannot overflow. */ function add(uint64 a, uint64 b) internal pure returns (uint64) { uint64 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(uint64 a, uint64 b) internal pure returns (uint64) { require(b <= a, "SafeMath: subtraction overflow"); uint64 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(uint64 a, uint64 b) internal pure returns (uint64) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522 if (a == 0) { return 0; } uint64 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(uint64 a, uint64 b) internal pure returns (uint64) { // Solidity only automatically asserts when dividing by 0 require(b > 0, "SafeMath: division by zero"); uint64 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(uint64 a, uint64 b) internal pure returns (uint64) { require(b != 0, "SafeMath: modulo by zero"); return a % b; } } pragma solidity >=0.6.0; import "./AggregatorInterface.sol"; import "./AggregatorV3Interface.sol"; interface AggregatorV2V3Interface is AggregatorInterface, AggregatorV3Interface { } pragma solidity ^0.6.0; interface AggregatorValidatorInterface { function validate( uint256 previousRoundId, int256 previousAnswer, uint256 currentRoundId, int256 currentAnswer ) external returns (bool); } pragma solidity ^0.6.0; interface LinkTokenInterface { function allowance(address owner, address spender) external view returns (uint256 remaining); function approve(address spender, uint256 value) external returns (bool success); function balanceOf(address owner) external view returns (uint256 balance); function decimals() external view returns (uint8 decimalPlaces); function decreaseApproval(address spender, uint256 addedValue) external returns (bool success); function increaseApproval(address spender, uint256 subtractedValue) external; function name() external view returns (string memory tokenName); function symbol() external view returns (string memory tokenSymbol); function totalSupply() external view returns (uint256 totalTokensIssued); function transfer(address to, uint256 value) external returns (bool success); function transferAndCall(address to, uint256 value, bytes calldata data) external returns (bool success); function transferFrom(address from, address to, uint256 value) external returns (bool success); } 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) { require(b <= a, "SafeMath: subtraction overflow"); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // Solidity only automatically asserts when dividing by 0 require(b > 0, "SafeMath: division by zero"); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b != 0, "SafeMath: modulo by zero"); return a % b; } } pragma solidity ^0.6.0; 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; } /** * @notice Computes average of two signed integers, ensuring that the computation * doesn't overflow. * @dev If the result is not an integer, it is rounded towards zero. For example, * avg(-3, -4) = -3 */ function avg(int256 _a, int256 _b) internal pure returns (int256) { if ((_a < 0 && _b > 0) || (_a > 0 && _b < 0)) { return add(_a, _b) / 2; } int256 remainder = (_a % 2 + _b % 2) / 2; return add(add(_a / 2, _b / 2), remainder); } } pragma solidity >=0.6.0; interface AggregatorInterface { function latestAnswer() external view returns (int256); function latestTimestamp() external view returns (uint256); function latestRound() external view returns (uint256); function getAnswer(uint256 roundId) external view returns (int256); function getTimestamp(uint256 roundId) external view returns (uint256); event AnswerUpdated(int256 indexed current, uint256 indexed roundId, uint256 updatedAt); event NewRound(uint256 indexed roundId, address indexed startedBy, uint256 startedAt); } pragma solidity >=0.6.0; interface AggregatorV3Interface { function decimals() external view returns (uint8); function description() external view returns (string memory); function version() external view returns (uint256); // getRoundData and latestRoundData should both raise "No data present" // if they do not have data to report, instead of returning unset values // which could be misinterpreted as actual reported values. function getRoundData(uint80 _roundId) external view returns ( uint80 roundId, int256 answer, uint256 startedAt, uint256 updatedAt, uint80 answeredInRound ); function latestRoundData() external view returns ( uint80 roundId, int256 answer, uint256 startedAt, uint256 updatedAt, uint80 answeredInRound ); } // SPDX-License-Identifier: BUSDL-1.1 pragma solidity 0.6.11; pragma experimental ABIEncoderV2; import {SafeMath} from "contracts/libraries/Imports.sol"; import {IERC20} from "contracts/common/Imports.sol"; import {ImmutableAssetAllocation} from "contracts/tvl/Imports.sol"; import { IStableSwap, ILiquidityGauge } from "contracts/protocols/curve/common/interfaces/Imports.sol"; /** * @title Periphery Contract for the Curve 3pool * @author APY.Finance * @notice This contract enables the APY.Finance system to retrieve the balance * of an underlyer of a Curve LP token. The balance is used as part * of the Chainlink computation of the deployed TVL. The primary * `getUnderlyerBalance` function is invoked indirectly when a * Chainlink node calls `balanceOf` on the APYAssetAllocationRegistry. */ contract CurveAllocationBase { using SafeMath for uint256; /** * @notice Returns the balance of an underlying token represented by * an account's LP token balance. * @param stableSwap the liquidity pool comprised of multiple underlyers * @param gauge the staking contract for the LP tokens * @param lpToken the LP token representing the share of the pool * @param coin the index indicating which underlyer * @return balance */ function getUnderlyerBalance( address account, IStableSwap stableSwap, ILiquidityGauge gauge, IERC20 lpToken, uint256 coin ) public view returns (uint256 balance) { require(address(stableSwap) != address(0), "INVALID_STABLESWAP"); require(address(gauge) != address(0), "INVALID_GAUGE"); require(address(lpToken) != address(0), "INVALID_LP_TOKEN"); uint256 poolBalance = getPoolBalance(stableSwap, coin); (uint256 lpTokenBalance, uint256 lpTokenSupply) = getLpTokenShare(account, stableSwap, gauge, lpToken); balance = lpTokenBalance.mul(poolBalance).div(lpTokenSupply); } function getPoolBalance(IStableSwap stableSwap, uint256 coin) public view returns (uint256) { require(address(stableSwap) != address(0), "INVALID_STABLESWAP"); return stableSwap.balances(coin); } function getLpTokenShare( address account, IStableSwap stableSwap, ILiquidityGauge gauge, IERC20 lpToken ) public view returns (uint256 balance, uint256 totalSupply) { require(address(stableSwap) != address(0), "INVALID_STABLESWAP"); require(address(gauge) != address(0), "INVALID_GAUGE"); require(address(lpToken) != address(0), "INVALID_LP_TOKEN"); totalSupply = lpToken.totalSupply(); balance = lpToken.balanceOf(account); balance = balance.add(gauge.balanceOf(account)); } } // solhint-disable-next-line no-empty-blocks contract CurveAllocationBase3 is CurveAllocationBase { } // SPDX-License-Identifier: BUSDL-1.1 pragma solidity 0.6.11; pragma experimental ABIEncoderV2; import {SafeMath} from "contracts/libraries/Imports.sol"; import {IERC20} from "contracts/common/Imports.sol"; import {ImmutableAssetAllocation} from "contracts/tvl/Imports.sol"; import { IStableSwap2, ILiquidityGauge } from "contracts/protocols/curve/common/interfaces/Imports.sol"; /** * @title Periphery Contract for the Curve 3pool * @author APY.Finance * @notice This contract enables the APY.Finance system to retrieve the balance * of an underlyer of a Curve LP token. The balance is used as part * of the Chainlink computation of the deployed TVL. The primary * `getUnderlyerBalance` function is invoked indirectly when a * Chainlink node calls `balanceOf` on the APYAssetAllocationRegistry. */ contract CurveAllocationBase2 { using SafeMath for uint256; /** * @notice Returns the balance of an underlying token represented by * an account's LP token balance. * @param stableSwap the liquidity pool comprised of multiple underlyers * @param gauge the staking contract for the LP tokens * @param lpToken the LP token representing the share of the pool * @param coin the index indicating which underlyer * @return balance */ function getUnderlyerBalance( address account, IStableSwap2 stableSwap, ILiquidityGauge gauge, IERC20 lpToken, uint256 coin ) public view returns (uint256 balance) { require(address(stableSwap) != address(0), "INVALID_STABLESWAP"); require(address(gauge) != address(0), "INVALID_GAUGE"); require(address(lpToken) != address(0), "INVALID_LP_TOKEN"); uint256 poolBalance = getPoolBalance(stableSwap, coin); (uint256 lpTokenBalance, uint256 lpTokenSupply) = getLpTokenShare(account, stableSwap, gauge, lpToken); balance = lpTokenBalance.mul(poolBalance).div(lpTokenSupply); } function getPoolBalance(IStableSwap2 stableSwap, uint256 coin) public view returns (uint256) { require(address(stableSwap) != address(0), "INVALID_STABLESWAP"); return stableSwap.balances(coin); } function getLpTokenShare( address account, IStableSwap2 stableSwap, ILiquidityGauge gauge, IERC20 lpToken ) public view returns (uint256 balance, uint256 totalSupply) { require(address(stableSwap) != address(0), "INVALID_STABLESWAP"); require(address(gauge) != address(0), "INVALID_GAUGE"); require(address(lpToken) != address(0), "INVALID_LP_TOKEN"); totalSupply = lpToken.totalSupply(); balance = lpToken.balanceOf(account); balance = balance.add(gauge.balanceOf(account)); } } // SPDX-License-Identifier: BUSDL-1.1 pragma solidity 0.6.11; pragma experimental ABIEncoderV2; import {SafeMath} from "contracts/libraries/Imports.sol"; import {IERC20} from "contracts/common/Imports.sol"; import {ImmutableAssetAllocation} from "contracts/tvl/Imports.sol"; import { IStableSwap4, ILiquidityGauge } from "contracts/protocols/curve/common/interfaces/Imports.sol"; /** * @title Periphery Contract for the Curve 3pool * @author APY.Finance * @notice This contract enables the APY.Finance system to retrieve the balance * of an underlyer of a Curve LP token. The balance is used as part * of the Chainlink computation of the deployed TVL. The primary * `getUnderlyerBalance` function is invoked indirectly when a * Chainlink node calls `balanceOf` on the APYAssetAllocationRegistry. */ contract CurveAllocationBase4 { using SafeMath for uint256; /** * @notice Returns the balance of an underlying token represented by * an account's LP token balance. * @param stableSwap the liquidity pool comprised of multiple underlyers * @param gauge the staking contract for the LP tokens * @param lpToken the LP token representing the share of the pool * @param coin the index indicating which underlyer * @return balance */ function getUnderlyerBalance( address account, IStableSwap4 stableSwap, ILiquidityGauge gauge, IERC20 lpToken, uint256 coin ) public view returns (uint256 balance) { require(address(stableSwap) != address(0), "INVALID_STABLESWAP"); require(address(gauge) != address(0), "INVALID_GAUGE"); require(address(lpToken) != address(0), "INVALID_LP_TOKEN"); uint256 poolBalance = getPoolBalance(stableSwap, coin); (uint256 lpTokenBalance, uint256 lpTokenSupply) = getLpTokenShare(account, stableSwap, gauge, lpToken); balance = lpTokenBalance.mul(poolBalance).div(lpTokenSupply); } function getPoolBalance(IStableSwap4 stableSwap, uint256 coin) public view returns (uint256) { require(address(stableSwap) != address(0), "INVALID_STABLESWAP"); return stableSwap.balances(coin); } function getLpTokenShare( address account, IStableSwap4 stableSwap, ILiquidityGauge gauge, IERC20 lpToken ) public view returns (uint256 balance, uint256 totalSupply) { require(address(stableSwap) != address(0), "INVALID_STABLESWAP"); require(address(gauge) != address(0), "INVALID_GAUGE"); require(address(lpToken) != address(0), "INVALID_LP_TOKEN"); totalSupply = lpToken.totalSupply(); balance = lpToken.balanceOf(account); balance = balance.add(gauge.balanceOf(account)); } } // SPDX-License-Identifier: BUSDL-1.1 pragma solidity 0.6.11; pragma experimental ABIEncoderV2; import {IZap} from "contracts/lpaccount/Imports.sol"; import { IAssetAllocation, IERC20, IDetailedERC20 } from "contracts/common/Imports.sol"; import {SafeERC20} from "contracts/libraries/Imports.sol"; import { ILiquidityGauge, ITokenMinter } from "contracts/protocols/curve/common/interfaces/Imports.sol"; import {CurveZapBase} from "contracts/protocols/curve/common/CurveZapBase.sol"; abstract contract CurveGaugeZapBase is IZap, CurveZapBase { using SafeERC20 for IERC20; address internal constant MINTER_ADDRESS = 0xd061D61a4d941c39E5453435B6345Dc261C2fcE0; address internal immutable LP_ADDRESS; address internal immutable GAUGE_ADDRESS; constructor( address swapAddress, address lpAddress, address gaugeAddress, uint256 denominator, uint256 slippage, uint256 nCoins ) public CurveZapBase(swapAddress, denominator, slippage, nCoins) // solhint-disable-next-line no-empty-blocks { LP_ADDRESS = lpAddress; GAUGE_ADDRESS = gaugeAddress; } function getLpTokenBalance(address account) external view override returns (uint256) { return ILiquidityGauge(GAUGE_ADDRESS).balanceOf(account); } function _depositToGauge() internal override { ILiquidityGauge liquidityGauge = ILiquidityGauge(GAUGE_ADDRESS); uint256 lpBalance = IERC20(LP_ADDRESS).balanceOf(address(this)); IERC20(LP_ADDRESS).safeApprove(GAUGE_ADDRESS, 0); IERC20(LP_ADDRESS).safeApprove(GAUGE_ADDRESS, lpBalance); liquidityGauge.deposit(lpBalance); } function _withdrawFromGauge(uint256 amount) internal override returns (uint256) { ILiquidityGauge liquidityGauge = ILiquidityGauge(GAUGE_ADDRESS); liquidityGauge.withdraw(amount); //lpBalance return IERC20(LP_ADDRESS).balanceOf(address(this)); } function _claim() internal override { // claim CRV ITokenMinter(MINTER_ADDRESS).mint(GAUGE_ADDRESS); // claim protocol-specific rewards _claimRewards(); } // solhint-disable-next-line no-empty-blocks function _claimRewards() internal virtual {} } // SPDX-License-Identifier: BUSDL-1.1 pragma solidity 0.6.11; pragma experimental ABIEncoderV2; import {SafeMath, SafeERC20} from "contracts/libraries/Imports.sol"; import {IZap} from "contracts/lpaccount/Imports.sol"; import { IAssetAllocation, IDetailedERC20, IERC20 } from "contracts/common/Imports.sol"; import { Curve3poolUnderlyerConstants } from "contracts/protocols/curve/3pool/Constants.sol"; abstract contract CurveZapBase is Curve3poolUnderlyerConstants, IZap { using SafeMath for uint256; using SafeERC20 for IERC20; address internal constant CRV_ADDRESS = 0xD533a949740bb3306d119CC777fa900bA034cd52; address internal immutable SWAP_ADDRESS; uint256 internal immutable DENOMINATOR; uint256 internal immutable SLIPPAGE; uint256 internal immutable N_COINS; constructor( address swapAddress, uint256 denominator, uint256 slippage, uint256 nCoins ) public { SWAP_ADDRESS = swapAddress; DENOMINATOR = denominator; SLIPPAGE = slippage; N_COINS = nCoins; } /// @param amounts array of underlyer amounts function deployLiquidity(uint256[] calldata amounts) external override { require(amounts.length == N_COINS, "INVALID_AMOUNTS"); uint256 totalNormalizedDeposit = 0; for (uint256 i = 0; i < amounts.length; i++) { if (amounts[i] == 0) continue; uint256 deposit = amounts[i]; address underlyerAddress = _getCoinAtIndex(i); uint8 decimals = IDetailedERC20(underlyerAddress).decimals(); uint256 normalizedDeposit = deposit.mul(10**uint256(18)).div(10**uint256(decimals)); totalNormalizedDeposit = totalNormalizedDeposit.add( normalizedDeposit ); IERC20(underlyerAddress).safeApprove(SWAP_ADDRESS, 0); IERC20(underlyerAddress).safeApprove(SWAP_ADDRESS, amounts[i]); } uint256 minAmount = _calcMinAmount(totalNormalizedDeposit, _getVirtualPrice()); _addLiquidity(amounts, minAmount); _depositToGauge(); } /** * @param amount LP token amount * @param index underlyer index */ function unwindLiquidity(uint256 amount, uint8 index) external override { require(index < N_COINS, "INVALID_INDEX"); uint256 lpBalance = _withdrawFromGauge(amount); address underlyerAddress = _getCoinAtIndex(index); uint8 decimals = IDetailedERC20(underlyerAddress).decimals(); uint256 minAmount = _calcMinAmountUnderlyer(lpBalance, _getVirtualPrice(), decimals); _removeLiquidity(lpBalance, index, minAmount); } function claim() external override { _claim(); } function sortedSymbols() public view override returns (string[] memory) { // N_COINS is not available as a public function // so we have to hardcode the number here string[] memory symbols = new string[](N_COINS); for (uint256 i = 0; i < symbols.length; i++) { address underlyerAddress = _getCoinAtIndex(i); symbols[i] = IDetailedERC20(underlyerAddress).symbol(); } return symbols; } function _getVirtualPrice() internal view virtual returns (uint256); function _getCoinAtIndex(uint256 i) internal view virtual returns (address); function _addLiquidity(uint256[] calldata amounts_, uint256 minAmount) internal virtual; function _removeLiquidity( uint256 lpBalance, uint8 index, uint256 minAmount ) internal virtual; function _depositToGauge() internal virtual; function _withdrawFromGauge(uint256 amount) internal virtual returns (uint256); function _claim() internal virtual; /** * @dev normalizedDepositAmount the amount in same units as virtual price (18 decimals) * @dev virtualPrice the "price", in 18 decimals, per big token unit of the LP token * @return required minimum amount of LP token (in token wei) */ function _calcMinAmount( uint256 normalizedDepositAmount, uint256 virtualPrice ) internal view returns (uint256) { uint256 idealLpTokenAmount = normalizedDepositAmount.mul(1e18).div(virtualPrice); // allow some slippage/MEV return idealLpTokenAmount.mul(DENOMINATOR.sub(SLIPPAGE)).div(DENOMINATOR); } /** * @param lpTokenAmount the amount in the same units as Curve LP token (18 decimals) * @param virtualPrice the "price", in 18 decimals, per big token unit of the LP token * @param decimals the number of decimals for underlyer token * @return required minimum amount of underlyer (in token wei) */ function _calcMinAmountUnderlyer( uint256 lpTokenAmount, uint256 virtualPrice, uint8 decimals ) internal view returns (uint256) { // TODO: grab LP Token decimals explicitly? uint256 normalizedUnderlyerAmount = lpTokenAmount.mul(virtualPrice).div(1e18); uint256 underlyerAmount = normalizedUnderlyerAmount.mul(10**uint256(decimals)).div( 10**uint256(18) ); // allow some slippage/MEV return underlyerAmount.mul(DENOMINATOR.sub(SLIPPAGE)).div(DENOMINATOR); } function _createErc20AllocationArray(uint256 extraAllocations) internal pure returns (IERC20[] memory) { IERC20[] memory allocations = new IERC20[](extraAllocations.add(4)); allocations[0] = IERC20(CRV_ADDRESS); allocations[1] = IERC20(DAI_ADDRESS); allocations[2] = IERC20(USDC_ADDRESS); allocations[3] = IERC20(USDT_ADDRESS); return allocations; } } // SPDX-License-Identifier: BUSDL-1.1 pragma solidity 0.6.11; pragma experimental ABIEncoderV2; import {SafeMath} from "contracts/libraries/Imports.sol"; import {IERC20} from "contracts/common/Imports.sol"; import {ImmutableAssetAllocation} from "contracts/tvl/Imports.sol"; import { IOldStableSwap2, ILiquidityGauge } from "contracts/protocols/curve/common/interfaces/Imports.sol"; /** * @title Periphery Contract for the Curve 3pool * @author APY.Finance * @notice This contract enables the APY.Finance system to retrieve the balance * of an underlyer of a Curve LP token. The balance is used as part * of the Chainlink computation of the deployed TVL. The primary * `getUnderlyerBalance` function is invoked indirectly when a * Chainlink node calls `balanceOf` on the APYAssetAllocationRegistry. */ contract OldCurveAllocationBase2 { using SafeMath for uint256; /** * @notice Returns the balance of an underlying token represented by * an account's LP token balance. * @param stableSwap the liquidity pool comprised of multiple underlyers * @param gauge the staking contract for the LP tokens * @param lpToken the LP token representing the share of the pool * @param coin the index indicating which underlyer * @return balance */ function getUnderlyerBalance( address account, IOldStableSwap2 stableSwap, ILiquidityGauge gauge, IERC20 lpToken, int128 coin ) public view returns (uint256 balance) { require(address(stableSwap) != address(0), "INVALID_STABLESWAP"); require(address(gauge) != address(0), "INVALID_GAUGE"); require(address(lpToken) != address(0), "INVALID_LP_TOKEN"); uint256 poolBalance = getPoolBalance(stableSwap, coin); (uint256 lpTokenBalance, uint256 lpTokenSupply) = getLpTokenShare(account, stableSwap, gauge, lpToken); balance = lpTokenBalance.mul(poolBalance).div(lpTokenSupply); } function getPoolBalance(IOldStableSwap2 stableSwap, int128 coin) public view returns (uint256) { require(address(stableSwap) != address(0), "INVALID_STABLESWAP"); return stableSwap.balances(coin); } function getLpTokenShare( address account, IOldStableSwap2 stableSwap, ILiquidityGauge gauge, IERC20 lpToken ) public view returns (uint256 balance, uint256 totalSupply) { require(address(stableSwap) != address(0), "INVALID_STABLESWAP"); require(address(gauge) != address(0), "INVALID_GAUGE"); require(address(lpToken) != address(0), "INVALID_LP_TOKEN"); totalSupply = lpToken.totalSupply(); balance = lpToken.balanceOf(account); balance = balance.add(gauge.balanceOf(account)); } } // SPDX-License-Identifier: BUSDL-1.1 pragma solidity 0.6.11; pragma experimental ABIEncoderV2; import {SafeMath} from "contracts/libraries/Imports.sol"; import {IERC20} from "contracts/common/Imports.sol"; import {ImmutableAssetAllocation} from "contracts/tvl/Imports.sol"; import {IOldStableSwap3, ILiquidityGauge} from "contracts/protocols/curve/common/interfaces/Imports.sol"; /** * @title Periphery Contract for the Curve 3pool * @author APY.Finance * @notice This contract enables the APY.Finance system to retrieve the balance * of an underlyer of a Curve LP token. The balance is used as part * of the Chainlink computation of the deployed TVL. The primary * `getUnderlyerBalance` function is invoked indirectly when a * Chainlink node calls `balanceOf` on the APYAssetAllocationRegistry. */ contract OldCurveAllocationBase3 { using SafeMath for uint256; /** * @notice Returns the balance of an underlying token represented by * an account's LP token balance. * @param stableSwap the liquidity pool comprised of multiple underlyers * @param gauge the staking contract for the LP tokens * @param lpToken the LP token representing the share of the pool * @param coin the index indicating which underlyer * @return balance */ function getUnderlyerBalance( address account, IOldStableSwap3 stableSwap, ILiquidityGauge gauge, IERC20 lpToken, int128 coin ) public view returns (uint256 balance) { require(address(stableSwap) != address(0), "INVALID_STABLESWAP"); require(address(gauge) != address(0), "INVALID_GAUGE"); require(address(lpToken) != address(0), "INVALID_LP_TOKEN"); uint256 poolBalance = getPoolBalance(stableSwap, coin); (uint256 lpTokenBalance, uint256 lpTokenSupply) = getLpTokenShare( account, stableSwap, gauge, lpToken ); balance = lpTokenBalance.mul(poolBalance).div(lpTokenSupply); } function getPoolBalance(IOldStableSwap3 stableSwap, int128 coin) public view returns (uint256) { require(address(stableSwap) != address(0), "INVALID_STABLESWAP"); return stableSwap.balances(coin); } function getLpTokenShare( address account, IOldStableSwap3 stableSwap, ILiquidityGauge gauge, IERC20 lpToken ) public view returns (uint256 balance, uint256 totalSupply) { require(address(stableSwap) != address(0), "INVALID_STABLESWAP"); require(address(gauge) != address(0), "INVALID_GAUGE"); require(address(lpToken) != address(0), "INVALID_LP_TOKEN"); totalSupply = lpToken.totalSupply(); balance = lpToken.balanceOf(account); balance = balance.add(gauge.balanceOf(account)); } } // SPDX-License-Identifier: BUSDL-1.1 pragma solidity 0.6.11; pragma experimental ABIEncoderV2; import {SafeMath} from "contracts/libraries/Imports.sol"; import {IERC20} from "contracts/common/Imports.sol"; import {ImmutableAssetAllocation} from "contracts/tvl/Imports.sol"; import { IOldStableSwap4, ILiquidityGauge } from "contracts/protocols/curve/common/interfaces/Imports.sol"; /** * @title Periphery Contract for the Curve 3pool * @author APY.Finance * @notice This contract enables the APY.Finance system to retrieve the balance * of an underlyer of a Curve LP token. The balance is used as part * of the Chainlink computation of the deployed TVL. The primary * `getUnderlyerBalance` function is invoked indirectly when a * Chainlink node calls `balanceOf` on the APYAssetAllocationRegistry. */ contract OldCurveAllocationBase4 { using SafeMath for uint256; /** * @notice Returns the balance of an underlying token represented by * an account's LP token balance. * @param stableSwap the liquidity pool comprised of multiple underlyers * @param gauge the staking contract for the LP tokens * @param lpToken the LP token representing the share of the pool * @param coin the index indicating which underlyer * @return balance */ function getUnderlyerBalance( address account, IOldStableSwap4 stableSwap, ILiquidityGauge gauge, IERC20 lpToken, int128 coin ) public view returns (uint256 balance) { require(address(stableSwap) != address(0), "INVALID_STABLESWAP"); require(address(gauge) != address(0), "INVALID_GAUGE"); require(address(lpToken) != address(0), "INVALID_LP_TOKEN"); uint256 poolBalance = getPoolBalance(stableSwap, coin); (uint256 lpTokenBalance, uint256 lpTokenSupply) = getLpTokenShare(account, stableSwap, gauge, lpToken); balance = lpTokenBalance.mul(poolBalance).div(lpTokenSupply); } function getPoolBalance(IOldStableSwap4 stableSwap, int128 coin) public view returns (uint256) { require(address(stableSwap) != address(0), "INVALID_STABLESWAP"); return stableSwap.balances(coin); } function getLpTokenShare( address account, IOldStableSwap4 stableSwap, ILiquidityGauge gauge, IERC20 lpToken ) public view returns (uint256 balance, uint256 totalSupply) { require(address(stableSwap) != address(0), "INVALID_STABLESWAP"); require(address(gauge) != address(0), "INVALID_GAUGE"); require(address(lpToken) != address(0), "INVALID_LP_TOKEN"); totalSupply = lpToken.totalSupply(); balance = lpToken.balanceOf(account); balance = balance.add(gauge.balanceOf(account)); } } // SPDX-License-Identifier: BUSDL-1.1 pragma solidity 0.6.11; pragma experimental ABIEncoderV2; import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import {IAssetAllocation} from "contracts/common/Imports.sol"; import { CurveGaugeZapBase } from "contracts/protocols/curve/common/CurveGaugeZapBase.sol"; contract TestCurveZap is CurveGaugeZapBase { string public constant override NAME = "TestCurveZap"; address[] private _underlyers; constructor( address swapAddress, address lpTokenAddress, address liquidityGaugeAddress, uint256 denominator, uint256 slippage, uint256 numOfCoins ) public CurveGaugeZapBase( swapAddress, lpTokenAddress, liquidityGaugeAddress, denominator, slippage, numOfCoins ) // solhint-disable-next-line no-empty-blocks {} function setUnderlyers(address[] calldata underlyers) external { _underlyers = underlyers; } function getSwapAddress() external view returns (address) { return SWAP_ADDRESS; } function getLpTokenAddress() external view returns (address) { return address(LP_ADDRESS); } function getGaugeAddress() external view returns (address) { return GAUGE_ADDRESS; } function getDenominator() external view returns (uint256) { return DENOMINATOR; } function getSlippage() external view returns (uint256) { return SLIPPAGE; } function getNumberOfCoins() external view returns (uint256) { return N_COINS; } function calcMinAmount(uint256 totalAmount, uint256 virtualPrice) external view returns (uint256) { return _calcMinAmount(totalAmount, virtualPrice); } function calcMinAmountUnderlyer( uint256 totalAmount, uint256 virtualPrice, uint8 decimals ) external view returns (uint256) { return _calcMinAmountUnderlyer(totalAmount, virtualPrice, decimals); } function assetAllocations() public view override returns (string[] memory) { string[] memory allocationNames = new string[](1); return allocationNames; } function erc20Allocations() public view override returns (IERC20[] memory) { IERC20[] memory allocations = new IERC20[](0); return allocations; } function _getVirtualPrice() internal view override returns (uint256) { return 1; } function _getCoinAtIndex(uint256 i) internal view override returns (address) { return _underlyers[i]; } function _addLiquidity(uint256[] calldata amounts, uint256 minAmount) internal override // solhint-disable-next-line no-empty-blocks { } function _removeLiquidity( uint256 lpBalance, uint8 index, uint256 minAmount // solhint-disable-next-line no-empty-blocks ) internal override {} }
recalculate the amount of LINK available for payouts/
function updateAvailableFunds() public { Funds memory funds = recordedFunds; uint256 nowAvailable = linkToken.balanceOf(address(this)).sub(funds.allocated); if (funds.available != nowAvailable) { recordedFunds.available = uint128(nowAvailable); emit AvailableFundsUpdated(nowAvailable); } }
53,182
pragma solidity 0.4.24; import "openzeppelin-solidity/contracts/math/SafeMath.sol"; import 'openzeppelin-solidity/contracts/lifecycle/Pausable.sol'; import "./Society.sol"; /** @title Societhy Data */ contract Data is Pausable { using SafeMath for uint; struct User { address wallet; bool registered; string name; mapping(address => bool) memberOf; uint memberships; } mapping(address => User) public users; mapping(string => Society[]) societiesInLocation; User[] public allUsers; Society[] public allSocieties; uint public numberOfSocieties; uint public numberOfUsers; uint public totalDonations; event NewUserAdded(); event NewSocietyAdded(); /* Getters */ /** * @dev Getter for user name * @param _user Address to identify user * @return _name Identified user's name */ function userGetName(address _user) public view returns (string _name) { _name = users[_user].name; } /** * @dev Getter for user registration status * @param _user Address to identify user * @return _registered Identified user's registration status */ function userIsRegistered(address _user) public view returns (bool _registered) { _registered = users[_user].registered; } /** * @dev Getter for user existence * @param _user Address to identify user * @return _exists Identified user's existence */ function userExists(address _user) public view returns (bool _exists) { _exists = users[_user].registered; } /** * @dev Getter for user membership status * @param _user Address to identify user * @param _society Address to identify society * @return _isMemberOf Identified user's membership status of identified society */ function userIsMemberOf(address _user, address _society) private view returns (bool _isMemberOf) { _isMemberOf = users[_user].memberOf[_society]; } /** * @dev Getter for list of societies user is member of * @param _user Address to identify user * @return {address[]} List of addresses identifying societies the identified user is member of */ function userGetMemberships(address _user) public view returns (address[]) { uint len = users[_user].memberships; address[] memory memberships = new address[](len); uint pointer = 0; for (uint i = 0; i < allSocieties.length; i++) { if (allSocieties[i].userIsMember(_user)) { memberships[pointer] = address(allSocieties[i]); pointer = pointer.add(1); } } return memberships; } /** * @dev Getter for list of members that belong to a society * @param _society Address to identify society * @return {address[]} List of addresses identifying users the identified society has */ function societyGetMembers(address _society) public view returns (address[]) { Society s = Society(_society); uint len = s.memberships(); address[] memory memberships = new address[](len); uint pointer = 0; for (uint i = 0; i < allUsers.length; i++) { if (allUsers[i].memberOf[_society]) { memberships[pointer] = allUsers[i].wallet; pointer = pointer.add(1); } } return memberships; } /** * @dev Getter for list of societies that are in an identified location * @param _location String to identify location * @return _inLocation List of addresses identifying societies in the identified location */ function getSocietiesInLocation(string _location) public view returns (Society[] _inLocation) { _inLocation = societiesInLocation[_location]; } /* Society utilities */ /** * @dev Creates a new society * @param _name String for new society name * @param _location String for new society location * @param _name String for new society's social link * @return _society New society contract address */ function createSociety(string _name, string _location, string _socialLink) public whenNotPaused returns (Society _society) { require(userExists(msg.sender)); _society = new Society(_name, _location, msg.sender, _socialLink); allSocieties.push(_society); societiesInLocation[_location].push(_society); users[msg.sender].memberOf[_society] = true; users[msg.sender].memberships = users[msg.sender].memberships.add(1); newSocietyAdded(); } /** * @dev Allows user to join an existing society * @param _society Address to identify society * @return {bool} Success */ function joinSociety(address _society) public whenNotPaused returns (bool) { require(userExists(msg.sender)); users[msg.sender].memberOf[_society] = true; users[msg.sender].memberships = users[msg.sender].memberships.add(1); Society s = Society(_society); s.join(msg.sender); return true; } /** * @dev Allows user to leave an existing society * @param _society Address to identify society * @return {bool} Success */ function leaveSociety(address _society) whenNotPaused public returns (bool) { require(userExists(msg.sender)); users[msg.sender].memberOf[_society] = false; users[msg.sender].memberships = users[msg.sender].memberships.sub(1); Society s = Society(_society); s.leave(msg.sender); return true; } /** * @dev Allows user to donate to an existing society they're a member of * @param _society Address to identify society * @return {bool} Success */ function makeDonation(address _society) public whenNotPaused payable returns (bool) { require(userExists(msg.sender) && users[msg.sender].memberOf[_society]); _society.transfer(msg.value); totalDonations = totalDonations.add(msg.value); return true; } /* User utilities */ /** * @dev Registers a new user * @param _name String for new user name * @return {bool} Success */ function addNewUser(string _name) public whenNotPaused returns (bool) { require(!userExists(msg.sender)); users[msg.sender].name = _name; users[msg.sender].wallet = msg.sender; users[msg.sender].registered = true; allUsers.push(users[msg.sender]); newUserAdded(); return true; } /* Other utilities */ /** * @dev Logs a new society being added */ function newSocietyAdded() private { numberOfSocieties = numberOfSocieties.add(1); emit NewSocietyAdded(); } /** * @dev Logs a new user being registered */ function newUserAdded() private { numberOfUsers = numberOfUsers.add(1); emit NewUserAdded(); } }
Getter for list of societies that are in an identified location _location String to identify location return _inLocation List of addresses identifying societies in the identified location/
function getSocietiesInLocation(string _location) public view returns (Society[] _inLocation) { _inLocation = societiesInLocation[_location]; }
990,442
./full_match/421611/0x54e2B241a3f9Fc47Bb7408Aa348a76bF96956508/sources/contracts/Omnitoken.sol
Endpoint.sol estimateFees() returns the fees for the message
function estimateFees( uint16 _dstChainId, address to, uint256 amount ) external view returns (uint256 nativeFee, uint256 zroFee) { bytes memory payload = abi.encode(_msgSender(), amount); return ILayerZeroEndpoint(lzEndpoint).estimateFees( _dstChainId, to, payload, false, bytes("") ); }
13,220,819
/** *Submitted for verification at Etherscan.io on 2022-02-26 */ // SPDX-License-Identifier: OSL-3.0 pragma solidity 0.8.11; /* __ __ __ __ ______ ______ __ __ __ ______ /\ \/\ \ /\ \/ / /\ == \ /\ __ \ /\ \ /\ "-.\ \ /\ ___\ \ \ \_\ \ \ \ _"-. \ \ __< \ \ __ \ \ \ \ \ \ \-. \ \ \ __\ \ \_____\ \ \_\ \_\ \ \_\ \_\ \ \_\ \_\ \ \_\ \ \_\\"\_\ \ \_____\ \/_____/ \/_/\/_/ \/_/ /_/ \/_/\/_/ \/_/ \/_/ \/_/ \/_____/ |########################################################################| |########################################################################| |########################################################################| |########################################################################| |########################################################################| |::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::| |::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::| |::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::| |::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::| |::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::| Pussy Riot, Trippy Labs, PleasrDAO, CXIP */ contract UkraineDAO_NFT { address private _owner; string private _name = "UKRAINE"; string private _symbol = unicode"🇺🇦"; string private _domain = "UkraineDAO.love"; address private _tokenOwner; address private _tokenApproval; string private _flag = "<svg xmlns=\"http://www.w3.org/2000/svg\" width=\"1200\" height=\"800\">" "<rect width=\"1200\" height=\"800\" fill=\"#005BBB\"/>" "<rect width=\"1200\" height=\"400\" y=\"400\" fill=\"#FFD500\"/>" "</svg>"; string private _flagSafe = "<svg xmlns=\\\"http://www.w3.org/2000/svg\\\" width=\\\"1200\\\" height=\\\"800\\\">" "<rect width=\\\"1200\\\" height=\\\"800\\\" fill=\\\"#005BBB\\\"/>" "<rect width=\\\"1200\\\" height=\\\"400\\\" y=\\\"400\\\" fill=\\\"#FFD500\\\"/>" "</svg>"; mapping(address => mapping(address => bool)) private _operatorApprovals; event Approval (address indexed wallet, address indexed operator, uint256 indexed tokenId); event ApprovalForAll (address indexed wallet, address indexed operator, bool approved); event Transfer (address indexed from, address indexed to, uint256 indexed tokenId); event OwnershipTransferred (address indexed previousOwner, address indexed newOwner); /* * @dev Only one NFT is ever created. */ constructor(address contractOwner) { _owner = contractOwner; emit OwnershipTransferred(address(0), _owner); _mint(_owner, 1); } /* * @dev Left empty to not block any smart contract transfers from running out of gas. */ receive() external payable {} /* * @dev Left empty to not allow any other functions to be called. */ fallback() external {} /* * @dev Allows to limit certain function calls to only the contract owner. */ modifier onlyOwner() { require(isOwner(), "you are not the owner"); _; } /* * @dev Can transfer smart contract ownership to another wallet/smart contract. */ function changeOwner (address newOwner) public onlyOwner { require(newOwner != address(0), "empty address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } /* * @dev Provisional functionality to allow the removal of any spammy NFTs. */ function withdrawERC1155 (address token, uint256 tokenId, uint256 amount) public onlyOwner { ERCTransferable(token).safeTransferFrom(address(this), _owner, tokenId, amount, ""); } /* * @dev Provisional functionality to allow the withdrawal of accidentally received ERC20 tokens. */ function withdrawERC20 (address token, uint256 amount) public onlyOwner { ERCTransferable(token).transfer(_owner, amount); } /* * @dev Provisional functionality to allow the removal of any spammy NFTs. */ function withdrawERC721 (address token, uint256 tokenId) public onlyOwner { ERCTransferable(token).safeTransferFrom(address(this), _owner, tokenId); } /* * @dev Provisional functionality to allow the withdrawal of accidentally received ETH. */ function withdrawETH () public onlyOwner { payable(address(msg.sender)).transfer(address(this).balance); } /* * @dev Approve a third-party wallet/contract to manage the token on behalf of a token owner. */ function approve (address operator, uint256 tokenId) public { require(operator != _tokenOwner, "one cannot approve one self"); require(_isApproved(msg.sender, tokenId), "the sender is not approved"); _tokenApproval = operator; emit Approval(_tokenOwner, operator, tokenId); } /* * @dev Safely transfer a token to another wallet/contract. */ function safeTransferFrom (address from, address to, uint256 tokenId) public payable { safeTransferFrom(from, to, tokenId, ""); } /* * @dev Safely transfer a token to another wallet/contract. */ function safeTransferFrom (address from, address to, uint256 tokenId, bytes memory data) public payable { require(_isApproved(msg.sender, tokenId), "sender is not approved"); _transferFrom(from, to, tokenId); if (isContract(to) && ERCTransferable(to).supportsInterface(0x150b7a02)) { require(ERCTransferable(to).onERC721Received(address(this), from, tokenId, data) == 0x150b7a02, "onERC721Received has failed"); } } /* * @dev Approve a third-party wallet/contract to manage all tokens on behalf of a token owner. */ function setApprovalForAll (address operator, bool approved) public { require(operator != msg.sender, "one cannot approve one self"); _operatorApprovals[msg.sender][operator] = approved; emit ApprovalForAll(msg.sender, operator, approved); } /* * @dev Transfer a token to anther wallet/contract. */ function transfer (address to, uint256 tokenId) public payable { transferFrom(msg.sender, to, tokenId, ""); } /* * @dev Transfer a token to another wallet/contract. */ function transferFrom (address from, address to, uint256 tokenId) public payable { transferFrom(from, to, tokenId, ""); } /* * @dev Transfer a token to another wallet/contract. */ function transferFrom (address from, address to, uint256 tokenId, bytes memory) public payable { require(_isApproved(msg.sender, tokenId), "the sender is not approved"); _transferFrom(from, to, tokenId); } /* * @dev Gets the token balance of a wallet/contract. */ function balanceOf (address wallet) public view returns (uint256) { require(wallet != address(0), "empty address"); return wallet == _tokenOwner ? 1 : 0; } /* * @dev Gets the base64 encoded JSON data stream of contract descriptors. */ function contractURI () public view returns (string memory) { return string( abi.encodePacked( "data:application/json;base64,", Base64.encode( abi.encodePacked( "{", "\"name\":\"", _name, "\",", unicode"\"description\":\"This is the Ukranian flag 🇺🇦 1/1\",", "\"external_link\":\"https://", _domain, "/\",", "\"image\":\"data:image/svg+xml;base64,", Base64.encode(_flag), "\"", "}" ) ) ) ); } /* * @dev Check if a token exists. */ function exists (uint256 tokenId) public pure returns (bool) { return (tokenId == 1); } /* * @dev Check if an approved wallet/address was added for a particular token. */ function getApproved (uint256) public view returns (address) { return _tokenApproval; } /* * @dev Check if an operator was approved for a particular wallet/contract. */ function isApprovedForAll (address wallet, address operator) public view returns (bool) { return _operatorApprovals[wallet][operator]; } /* * @dev Check if current wallet/caller is the owner of the smart contract. */ function isOwner () public view returns (bool) { return (msg.sender == _owner); } /* * @dev Get the name of the collection. */ function name () public view returns (string memory) { return _name; } /* * @dev Get the owner of the smart contract. */ function owner () public view returns (address) { return _owner; } /* * @dev Get the owner of a particular token. */ function ownerOf (uint256 tokenId) public view returns (address) { require(tokenId == 1, "token does not exist"); return _tokenOwner; } /* * @dev Check if the smart contract supports a particular interface. */ function supportsInterface (bytes4 interfaceId) public pure returns (bool) { if ( interfaceId == 0x01ffc9a7 || // ERC165 interfaceId == 0x80ac58cd || // ERC721 interfaceId == 0x780e9d63 || // ERC721Enumerable interfaceId == 0x5b5e139f || // ERC721Metadata interfaceId == 0x150b7a02 || // ERC721TokenReceiver interfaceId == 0xe8a3d485 // contractURI() ) { return true; } else { return false; } } /* * @dev Get the collection's symbol. */ function symbol () public view returns (string memory) { return _symbol; } /* * @dev Get token by index. */ function tokenByIndex (uint256 index) public pure returns (uint256) { require(index == 0, "index out of bounds"); return 1; } /* * @dev Get wallet/contract token by index. */ function tokenOfOwnerByIndex (address wallet, uint256 index) public view returns (uint256) { require(wallet == _tokenOwner && index == 0, "index out of bounds"); return 1; } /* * @dev Gets the base64 encoded data stream of token. */ function tokenURI (uint256 tokenId) public view returns (string memory) { require(_exists(tokenId), "token does not exist"); return string( abi.encodePacked( "data:application/json;base64,", Base64.encode( abi.encodePacked( "{", "\"name\":\"Ukrainian Flag\",", unicode"\"description\":\"This is the Ukrainian flag 🇺🇦 1/1. Funds raised from this sale will be directed to helping the Ukrainian civilians suffering from the war initiated by Putin. \\\"Come Back Alive,\\\" one of the most effective and transparent Ukrainian charitable and volunteer initiatives can be found at: https://savelife.in.ua\\n\\n", "This project has been organized by Pussy Riot, Trippy Labs, PleasrDAO, CXIP, and many Ukrainian humanitarian activists working tirelessly on the ground and generously consulting with us to assure we have a safe place to direct our donations that will help those who need it the most.\\n\\n", unicode"Much support and love to Ukraine 🇺🇦\",", "\"external_url\":\"https://", _domain, "/\",", "\"image\":\"data:image/svg+xml;base64,", Base64.encode(_flag), "\",", "\"image_data\":\"", _flagSafe, "\"", "}" ) ) ) ); } /* * @dev Get list of all tokens of an owner. */ function tokensOfOwner (address wallet) public view returns (uint256[] memory tokens) { if (wallet == _tokenOwner) { tokens = new uint256[](1); tokens[0] = 1; } return tokens; } /* * @dev Get the total supply of tokens in the collection. */ function totalSupply () public pure returns (uint256) { return 1; } /* * @dev Signal to sending contract that a token was received. */ function onERC721Received (address operator, address, uint256 tokenId, bytes calldata) public returns (bytes4) { ERCTransferable(operator).safeTransferFrom(address(this), _owner, tokenId); return 0x150b7a02; } function _clearApproval () internal { delete _tokenApproval; } function _mint (address to, uint256 tokenId) internal { require(to != address(0)); _tokenOwner = to; emit Transfer(address(0), to, tokenId); } function _transferFrom (address from, address to, uint256 tokenId) internal { require(_tokenOwner == from, "you are not token owner"); require(to != address(0), "you cannot burn this"); _clearApproval(); _tokenOwner = to; emit Transfer(from, to, tokenId); } function _exists (uint256 tokenId) internal pure returns (bool) { return (tokenId == 1); } function _isApproved (address spender, uint256 tokenId) internal view returns (bool) { require(_exists(tokenId)); return (spender == _tokenOwner || getApproved(tokenId) == spender || isApprovedForAll(_tokenOwner, spender)); } function isContract (address account) internal view returns (bool) { bytes32 codehash; assembly { codehash := extcodehash(account) } return (codehash != 0x0 && codehash != 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470); } } interface ERCTransferable { // ERC155 function safeTransferFrom (address from, address to, uint256 tokenid, uint256 amount, bytes calldata data) external; // ERC20 function transfer (address recipient, uint256 amount) external returns (bool); // ERC721 function safeTransferFrom (address from, address to, uint256 tokenId) external payable; // ERC721 function onERC721Received (address operator, address from, uint256 tokenId, bytes calldata data) external view returns (bytes4); // ERC721 function supportsInterface (bytes4 interfaceId) external view returns (bool); } library Base64 { function encode (string memory _str) internal pure returns (string memory) { bytes memory data = bytes(_str); return encode(data); } function encode (bytes memory data) internal pure returns (string memory) { string memory table = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; uint256 encodedLen = 4 * ((data.length + 2) / 3); string memory result = new string(encodedLen + 32); assembly { mstore(result, encodedLen) let tablePtr := add(table, 1) let dataPtr := data let endPtr := add(dataPtr, mload(data)) let resultPtr := add(result, 32) for {} lt(dataPtr, endPtr) {} { dataPtr := add(dataPtr, 3) let input := mload(dataPtr) mstore8(resultPtr, mload(add(tablePtr, and(shr(18, input), 0x3F)))) resultPtr := add(resultPtr, 1) mstore8(resultPtr, mload(add(tablePtr, and(shr(12, input), 0x3F)))) resultPtr := add(resultPtr, 1) mstore8(resultPtr, mload(add(tablePtr, and(shr(6, input), 0x3F)))) resultPtr := add(resultPtr, 1) mstore8(resultPtr, mload(add(tablePtr, and(input, 0x3F)))) resultPtr := add(resultPtr, 1) } switch mod(mload(data), 3) case 1 { mstore(sub(resultPtr, 2), shl(240, 0x3d3d)) } case 2 { mstore(sub(resultPtr, 1), shl(248, 0x3d)) } } return result; } }
Get the total supply of tokens in the collection./
function totalSupply () public pure returns (uint256) { return 1; }
6,549,531
./partial_match/42/0x30E761d94E357ABD4C15878ae795312868F1c32B/sources/Perifi.sol
https:docs.pynthetix.io/contracts/source/interfaces/ipynthetixstate Views Mutative functions
interface IPynthetixState { function debtLedger(uint index) external view returns (uint); function issuanceData(address account) external view returns (uint initialDebtOwnership, uint debtEntryIndex); function debtLedgerLength() external view returns (uint); function hasIssued(address account) external view returns (bool); function lastDebtLedgerEntry() external view returns (uint); function incrementTotalIssuerCount() external; function decrementTotalIssuerCount() external; function setCurrentIssuanceData(address account, uint initialDebtOwnership) external; function appendDebtLedgerValue(uint value) external; function clearIssuanceData(address account) external; }
3,299,359
./full_match/5/0xC74C30a05E2AD02F35c8C4573081cB4772a0682F/sources/project_/contracts/CGameSystem.sol
函數:取得等待審查的召集id(場主限定) 建立一個空陣列,長度等於召集陣列長度 將召集陣列的召集id,放入空陣列 如果召集狀態為「審核中」,則將召集id放入陣列
function getGameAuditingIds() public view onlyHost returns (uint256[] memory) { uint256[] memory _recruitsId; for (uint256 i = 0; i < recruits.length; i++) { if (recruits[i].status == GameStatus.AUDITING) { _recruitsId[i] = recruits[i].recruitId; } } return _recruitsId; }
1,926,853
./partial_match/5/0x0a81e39a27644BEAd19737A8Ec34b18DF472C576/sources/MintManager_v2.sol
TODO:: add validation that the token that is complient with the "PatronageToken" ERC721 interface extension somehow!
function listNewTokens( uint256[] memory tokens, address payable[] memory _benefactors, uint256[] memory _patronageNumerator, uint256[] memory _tokenGenerationRate ) public onlyAdmin { assert(tokens.length == _benefactors.length); assert(tokens.length == _patronageNumerator.length); assert(tokens.length == _tokenGenerationRate.length); for (uint8 i = 0; i < tokens.length; ++i) { assert(_benefactors[i] != address(0)); benefactors[tokens[i]] = _benefactors[i]; patronageNumerator[tokens[i]] = _patronageNumerator[i]; tokenGenerationRate[tokens[i]] = _tokenGenerationRate[i]; emit AddToken( tokens[i], _patronageNumerator[i], _tokenGenerationRate[i] ); } }
16,844,549
pragma solidity 0.4.20; // File: contracts\external\usingOraclize.sol // <ORACLIZE_API> /* Copyright (c) 2015-2016 Oraclize SRL Copyright (c) 2016 Oraclize LTD Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ // This api is currently targeted at 0.4.18, please import oraclizeAPI_pre0.4.sol or oraclizeAPI_0.4 where necessary pragma solidity >=0.4.18 <=0.4.20;// Incompatible compiler version... please select one stated within pragma solidity or use different oraclizeAPI version contract OraclizeI { address public cbAddress; function query(uint _timestamp, string _datasource, string _arg) external payable returns (bytes32 _id); function query_withGasLimit(uint _timestamp, string _datasource, string _arg, uint _gaslimit) external payable returns (bytes32 _id); function query2(uint _timestamp, string _datasource, string _arg1, string _arg2) public payable returns (bytes32 _id); function query2_withGasLimit(uint _timestamp, string _datasource, string _arg1, string _arg2, uint _gaslimit) external payable returns (bytes32 _id); function queryN(uint _timestamp, string _datasource, bytes _argN) public payable returns (bytes32 _id); function queryN_withGasLimit(uint _timestamp, string _datasource, bytes _argN, uint _gaslimit) external payable returns (bytes32 _id); function getPrice(string _datasource) public returns (uint _dsprice); function getPrice(string _datasource, uint gaslimit) public returns (uint _dsprice); function setProofType(byte _proofType) external; function setCustomGasPrice(uint _gasPrice) external; function randomDS_getSessionPubKeyHash() external view returns(bytes32); } contract OraclizeAddrResolverI { function getAddress() public returns (address _addr); } /* Begin solidity-cborutils https://github.com/smartcontractkit/solidity-cborutils MIT License Copyright (c) 2018 SmartContract ChainLink, Ltd. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ library Buffer { struct buffer { bytes buf; uint capacity; } function init(buffer memory buf, uint capacity) internal pure { if(capacity % 32 != 0) capacity += 32 - (capacity % 32); // Allocate space for the buffer data buf.capacity = capacity; assembly { let ptr := mload(0x40) mstore(buf, ptr) mstore(0x40, add(ptr, capacity)) } } function resize(buffer memory buf, uint capacity) private pure { bytes memory oldbuf = buf.buf; init(buf, capacity); append(buf, oldbuf); } function max(uint a, uint b) private pure returns(uint) { if(a > b) { return a; } return b; } /** * @dev Appends a byte array to the end of the buffer. Reverts if doing so * would exceed the capacity of the buffer. * @param buf The buffer to append to. * @param data The data to append. * @return The original buffer. */ function append(buffer memory buf, bytes data) internal pure returns(buffer memory) { if(data.length + buf.buf.length > buf.capacity) { resize(buf, max(buf.capacity, data.length) * 2); } uint dest; uint src; uint len = data.length; assembly { // Memory address of the buffer data let bufptr := mload(buf) // Length of existing buffer data let buflen := mload(bufptr) // Start address = buffer address + buffer length + sizeof(buffer length) dest := add(add(bufptr, buflen), 32) // Update buffer length mstore(bufptr, add(buflen, mload(data))) src := add(data, 32) } // Copy word-length chunks while possible for(; len >= 32; len -= 32) { assembly { mstore(dest, mload(src)) } dest += 32; src += 32; } // Copy remaining bytes uint mask = 256 ** (32 - len) - 1; assembly { let srcpart := and(mload(src), not(mask)) let destpart := and(mload(dest), mask) mstore(dest, or(destpart, srcpart)) } return buf; } /** * @dev Appends a byte to the end of the buffer. Reverts if doing so would * exceed the capacity of the buffer. * @param buf The buffer to append to. * @param data The data to append. * @return The original buffer. */ function append(buffer memory buf, uint8 data) internal pure { if(buf.buf.length + 1 > buf.capacity) { resize(buf, buf.capacity * 2); } assembly { // Memory address of the buffer data let bufptr := mload(buf) // Length of existing buffer data let buflen := mload(bufptr) // Address = buffer address + buffer length + sizeof(buffer length) let dest := add(add(bufptr, buflen), 32) mstore8(dest, data) // Update buffer length mstore(bufptr, add(buflen, 1)) } } /** * @dev Appends a byte to the end of the buffer. Reverts if doing so would * exceed the capacity of the buffer. * @param buf The buffer to append to. * @param data The data to append. * @return The original buffer. */ function appendInt(buffer memory buf, uint data, uint len) internal pure returns(buffer memory) { if(len + buf.buf.length > buf.capacity) { resize(buf, max(buf.capacity, len) * 2); } uint mask = 256 ** len - 1; assembly { // Memory address of the buffer data let bufptr := mload(buf) // Length of existing buffer data let buflen := mload(bufptr) // Address = buffer address + buffer length + sizeof(buffer length) + len let dest := add(add(bufptr, buflen), len) mstore(dest, or(and(mload(dest), not(mask)), data)) // Update buffer length mstore(bufptr, add(buflen, len)) } return buf; } } library CBOR { using Buffer for Buffer.buffer; uint8 private constant MAJOR_TYPE_INT = 0; uint8 private constant MAJOR_TYPE_NEGATIVE_INT = 1; uint8 private constant MAJOR_TYPE_BYTES = 2; uint8 private constant MAJOR_TYPE_STRING = 3; uint8 private constant MAJOR_TYPE_ARRAY = 4; uint8 private constant MAJOR_TYPE_MAP = 5; uint8 private constant MAJOR_TYPE_CONTENT_FREE = 7; function encodeType(Buffer.buffer memory buf, uint8 major, uint value) private pure { if(value <= 23) { buf.append(uint8((major << 5) | value)); } else if(value <= 0xFF) { buf.append(uint8((major << 5) | 24)); buf.appendInt(value, 1); } else if(value <= 0xFFFF) { buf.append(uint8((major << 5) | 25)); buf.appendInt(value, 2); } else if(value <= 0xFFFFFFFF) { buf.append(uint8((major << 5) | 26)); buf.appendInt(value, 4); } else if(value <= 0xFFFFFFFFFFFFFFFF) { buf.append(uint8((major << 5) | 27)); buf.appendInt(value, 8); } } function encodeIndefiniteLengthType(Buffer.buffer memory buf, uint8 major) private pure { buf.append(uint8((major << 5) | 31)); } function encodeUInt(Buffer.buffer memory buf, uint value) internal pure { encodeType(buf, MAJOR_TYPE_INT, value); } function encodeInt(Buffer.buffer memory buf, int value) internal pure { if(value >= 0) { encodeType(buf, MAJOR_TYPE_INT, uint(value)); } else { encodeType(buf, MAJOR_TYPE_NEGATIVE_INT, uint(-1 - value)); } } function encodeBytes(Buffer.buffer memory buf, bytes value) internal pure { encodeType(buf, MAJOR_TYPE_BYTES, value.length); buf.append(value); } function encodeString(Buffer.buffer memory buf, string value) internal pure { encodeType(buf, MAJOR_TYPE_STRING, bytes(value).length); buf.append(bytes(value)); } function startArray(Buffer.buffer memory buf) internal pure { encodeIndefiniteLengthType(buf, MAJOR_TYPE_ARRAY); } function startMap(Buffer.buffer memory buf) internal pure { encodeIndefiniteLengthType(buf, MAJOR_TYPE_MAP); } function endSequence(Buffer.buffer memory buf) internal pure { encodeIndefiniteLengthType(buf, MAJOR_TYPE_CONTENT_FREE); } } /* End solidity-cborutils */ contract usingOraclize { uint constant day = 60*60*24; uint constant week = 60*60*24*7; uint constant month = 60*60*24*30; byte constant proofType_NONE = 0x00; byte constant proofType_TLSNotary = 0x10; byte constant proofType_Android = 0x20; byte constant proofType_Ledger = 0x30; byte constant proofType_Native = 0xF0; byte constant proofStorage_IPFS = 0x01; uint8 constant networkID_auto = 0; uint8 constant networkID_mainnet = 1; uint8 constant networkID_testnet = 2; uint8 constant networkID_morden = 2; uint8 constant networkID_consensys = 161; OraclizeAddrResolverI OAR; OraclizeI oraclize; modifier oraclizeAPI { if((address(OAR)==0)||(getCodeSize(address(OAR))==0)) oraclize_setNetwork(networkID_auto); if(address(oraclize) != OAR.getAddress()) oraclize = OraclizeI(OAR.getAddress()); _; } modifier coupon(string code){ oraclize = OraclizeI(OAR.getAddress()); _; } function oraclize_setNetwork(uint8 networkID) internal returns(bool){ return oraclize_setNetwork(); networkID; // silence the warning and remain backwards compatible } function oraclize_setNetwork() internal returns(bool){ if (getCodeSize(0x1d3B2638a7cC9f2CB3D298A3DA7a90B67E5506ed)>0){ //mainnet OAR = OraclizeAddrResolverI(0x1d3B2638a7cC9f2CB3D298A3DA7a90B67E5506ed); oraclize_setNetworkName("eth_mainnet"); return true; } if (getCodeSize(0xc03A2615D5efaf5F49F60B7BB6583eaec212fdf1)>0){ //ropsten testnet OAR = OraclizeAddrResolverI(0xc03A2615D5efaf5F49F60B7BB6583eaec212fdf1); oraclize_setNetworkName("eth_ropsten3"); return true; } if (getCodeSize(0xB7A07BcF2Ba2f2703b24C0691b5278999C59AC7e)>0){ //kovan testnet OAR = OraclizeAddrResolverI(0xB7A07BcF2Ba2f2703b24C0691b5278999C59AC7e); oraclize_setNetworkName("eth_kovan"); return true; } if (getCodeSize(0x146500cfd35B22E4A392Fe0aDc06De1a1368Ed48)>0){ //rinkeby testnet OAR = OraclizeAddrResolverI(0x146500cfd35B22E4A392Fe0aDc06De1a1368Ed48); oraclize_setNetworkName("eth_rinkeby"); return true; } if (getCodeSize(0x6f485C8BF6fc43eA212E93BBF8ce046C7f1cb475)>0){ //ethereum-bridge OAR = OraclizeAddrResolverI(0x6f485C8BF6fc43eA212E93BBF8ce046C7f1cb475); return true; } if (getCodeSize(0x20e12A1F859B3FeaE5Fb2A0A32C18F5a65555bBF)>0){ //ether.camp ide OAR = OraclizeAddrResolverI(0x20e12A1F859B3FeaE5Fb2A0A32C18F5a65555bBF); return true; } if (getCodeSize(0x51efaF4c8B3C9AfBD5aB9F4bbC82784Ab6ef8fAA)>0){ //browser-solidity OAR = OraclizeAddrResolverI(0x51efaF4c8B3C9AfBD5aB9F4bbC82784Ab6ef8fAA); return true; } return false; } function __callback(bytes32 myid, string result) public { __callback(myid, result, new bytes(0)); } function __callback(bytes32 myid, string result, bytes proof) public { return; myid; result; proof; // Silence compiler warnings } function oraclize_getPrice(string datasource) oraclizeAPI internal returns (uint){ return oraclize.getPrice(datasource); } function oraclize_getPrice(string datasource, uint gaslimit) oraclizeAPI internal returns (uint){ return oraclize.getPrice(datasource, gaslimit); } function oraclize_query(string datasource, string arg) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource); if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price return oraclize.query.value(price)(0, datasource, arg); } function oraclize_query(uint timestamp, string datasource, string arg) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource); if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price return oraclize.query.value(price)(timestamp, datasource, arg); } function oraclize_query(uint timestamp, string datasource, string arg, uint gaslimit) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource, gaslimit); if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price return oraclize.query_withGasLimit.value(price)(timestamp, datasource, arg, gaslimit); } function oraclize_query(string datasource, string arg, uint gaslimit) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource, gaslimit); if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price return oraclize.query_withGasLimit.value(price)(0, datasource, arg, gaslimit); } function oraclize_query(string datasource, string arg1, string arg2) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource); if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price return oraclize.query2.value(price)(0, datasource, arg1, arg2); } function oraclize_query(uint timestamp, string datasource, string arg1, string arg2) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource); if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price return oraclize.query2.value(price)(timestamp, datasource, arg1, arg2); } function oraclize_query(uint timestamp, string datasource, string arg1, string arg2, uint gaslimit) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource, gaslimit); if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price return oraclize.query2_withGasLimit.value(price)(timestamp, datasource, arg1, arg2, gaslimit); } function oraclize_query(string datasource, string arg1, string arg2, uint gaslimit) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource, gaslimit); if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price return oraclize.query2_withGasLimit.value(price)(0, datasource, arg1, arg2, gaslimit); } function oraclize_query(string datasource, string[] argN) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource); if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price bytes memory args = stra2cbor(argN); return oraclize.queryN.value(price)(0, datasource, args); } function oraclize_query(uint timestamp, string datasource, string[] argN) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource); if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price bytes memory args = stra2cbor(argN); return oraclize.queryN.value(price)(timestamp, datasource, args); } function oraclize_query(uint timestamp, string datasource, string[] argN, uint gaslimit) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource, gaslimit); if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price bytes memory args = stra2cbor(argN); return oraclize.queryN_withGasLimit.value(price)(timestamp, datasource, args, gaslimit); } function oraclize_query(string datasource, string[] argN, uint gaslimit) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource, gaslimit); if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price bytes memory args = stra2cbor(argN); return oraclize.queryN_withGasLimit.value(price)(0, datasource, args, gaslimit); } function oraclize_query(string datasource, string[1] args) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](1); dynargs[0] = args[0]; return oraclize_query(datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, string[1] args) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](1); dynargs[0] = args[0]; return oraclize_query(timestamp, datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, string[1] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](1); dynargs[0] = args[0]; return oraclize_query(timestamp, datasource, dynargs, gaslimit); } function oraclize_query(string datasource, string[1] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](1); dynargs[0] = args[0]; return oraclize_query(datasource, dynargs, gaslimit); } function oraclize_query(string datasource, string[2] args) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](2); dynargs[0] = args[0]; dynargs[1] = args[1]; return oraclize_query(datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, string[2] args) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](2); dynargs[0] = args[0]; dynargs[1] = args[1]; return oraclize_query(timestamp, datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, string[2] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](2); dynargs[0] = args[0]; dynargs[1] = args[1]; return oraclize_query(timestamp, datasource, dynargs, gaslimit); } function oraclize_query(string datasource, string[2] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](2); dynargs[0] = args[0]; dynargs[1] = args[1]; return oraclize_query(datasource, dynargs, gaslimit); } function oraclize_query(string datasource, string[3] args) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](3); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; return oraclize_query(datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, string[3] args) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](3); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; return oraclize_query(timestamp, datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, string[3] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](3); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; return oraclize_query(timestamp, datasource, dynargs, gaslimit); } function oraclize_query(string datasource, string[3] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](3); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; return oraclize_query(datasource, dynargs, gaslimit); } function oraclize_query(string datasource, string[4] args) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](4); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; return oraclize_query(datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, string[4] args) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](4); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; return oraclize_query(timestamp, datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, string[4] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](4); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; return oraclize_query(timestamp, datasource, dynargs, gaslimit); } function oraclize_query(string datasource, string[4] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](4); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; return oraclize_query(datasource, dynargs, gaslimit); } function oraclize_query(string datasource, string[5] args) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](5); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; dynargs[4] = args[4]; return oraclize_query(datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, string[5] args) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](5); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; dynargs[4] = args[4]; return oraclize_query(timestamp, datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, string[5] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](5); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; dynargs[4] = args[4]; return oraclize_query(timestamp, datasource, dynargs, gaslimit); } function oraclize_query(string datasource, string[5] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](5); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; dynargs[4] = args[4]; return oraclize_query(datasource, dynargs, gaslimit); } function oraclize_query(string datasource, bytes[] argN) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource); if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price bytes memory args = ba2cbor(argN); return oraclize.queryN.value(price)(0, datasource, args); } function oraclize_query(uint timestamp, string datasource, bytes[] argN) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource); if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price bytes memory args = ba2cbor(argN); return oraclize.queryN.value(price)(timestamp, datasource, args); } function oraclize_query(uint timestamp, string datasource, bytes[] argN, uint gaslimit) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource, gaslimit); if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price bytes memory args = ba2cbor(argN); return oraclize.queryN_withGasLimit.value(price)(timestamp, datasource, args, gaslimit); } function oraclize_query(string datasource, bytes[] argN, uint gaslimit) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource, gaslimit); if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price bytes memory args = ba2cbor(argN); return oraclize.queryN_withGasLimit.value(price)(0, datasource, args, gaslimit); } function oraclize_query(string datasource, bytes[1] args) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](1); dynargs[0] = args[0]; return oraclize_query(datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, bytes[1] args) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](1); dynargs[0] = args[0]; return oraclize_query(timestamp, datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, bytes[1] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](1); dynargs[0] = args[0]; return oraclize_query(timestamp, datasource, dynargs, gaslimit); } function oraclize_query(string datasource, bytes[1] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](1); dynargs[0] = args[0]; return oraclize_query(datasource, dynargs, gaslimit); } function oraclize_query(string datasource, bytes[2] args) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](2); dynargs[0] = args[0]; dynargs[1] = args[1]; return oraclize_query(datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, bytes[2] args) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](2); dynargs[0] = args[0]; dynargs[1] = args[1]; return oraclize_query(timestamp, datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, bytes[2] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](2); dynargs[0] = args[0]; dynargs[1] = args[1]; return oraclize_query(timestamp, datasource, dynargs, gaslimit); } function oraclize_query(string datasource, bytes[2] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](2); dynargs[0] = args[0]; dynargs[1] = args[1]; return oraclize_query(datasource, dynargs, gaslimit); } function oraclize_query(string datasource, bytes[3] args) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](3); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; return oraclize_query(datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, bytes[3] args) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](3); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; return oraclize_query(timestamp, datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, bytes[3] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](3); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; return oraclize_query(timestamp, datasource, dynargs, gaslimit); } function oraclize_query(string datasource, bytes[3] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](3); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; return oraclize_query(datasource, dynargs, gaslimit); } function oraclize_query(string datasource, bytes[4] args) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](4); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; return oraclize_query(datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, bytes[4] args) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](4); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; return oraclize_query(timestamp, datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, bytes[4] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](4); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; return oraclize_query(timestamp, datasource, dynargs, gaslimit); } function oraclize_query(string datasource, bytes[4] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](4); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; return oraclize_query(datasource, dynargs, gaslimit); } function oraclize_query(string datasource, bytes[5] args) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](5); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; dynargs[4] = args[4]; return oraclize_query(datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, bytes[5] args) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](5); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; dynargs[4] = args[4]; return oraclize_query(timestamp, datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, bytes[5] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](5); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; dynargs[4] = args[4]; return oraclize_query(timestamp, datasource, dynargs, gaslimit); } function oraclize_query(string datasource, bytes[5] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](5); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; dynargs[4] = args[4]; return oraclize_query(datasource, dynargs, gaslimit); } function oraclize_cbAddress() oraclizeAPI internal returns (address){ return oraclize.cbAddress(); } function oraclize_setProof(byte proofP) oraclizeAPI internal { return oraclize.setProofType(proofP); } function oraclize_setCustomGasPrice(uint gasPrice) oraclizeAPI internal { return oraclize.setCustomGasPrice(gasPrice); } function oraclize_randomDS_getSessionPubKeyHash() oraclizeAPI internal returns (bytes32){ return oraclize.randomDS_getSessionPubKeyHash(); } function getCodeSize(address _addr) view internal returns(uint _size) { assembly { _size := extcodesize(_addr) } } function parseAddr(string _a) internal pure returns (address){ bytes memory tmp = bytes(_a); uint160 iaddr = 0; uint160 b1; uint160 b2; for (uint i=2; i<2+2*20; i+=2){ iaddr *= 256; b1 = uint160(tmp[i]); b2 = uint160(tmp[i+1]); if ((b1 >= 97)&&(b1 <= 102)) b1 -= 87; else if ((b1 >= 65)&&(b1 <= 70)) b1 -= 55; else if ((b1 >= 48)&&(b1 <= 57)) b1 -= 48; if ((b2 >= 97)&&(b2 <= 102)) b2 -= 87; else if ((b2 >= 65)&&(b2 <= 70)) b2 -= 55; else if ((b2 >= 48)&&(b2 <= 57)) b2 -= 48; iaddr += (b1*16+b2); } return address(iaddr); } function strCompare(string _a, string _b) internal pure returns (int) { bytes memory a = bytes(_a); bytes memory b = bytes(_b); uint minLength = a.length; if (b.length < minLength) minLength = b.length; for (uint i = 0; i < minLength; i ++) if (a[i] < b[i]) return -1; else if (a[i] > b[i]) return 1; if (a.length < b.length) return -1; else if (a.length > b.length) return 1; else return 0; } function indexOf(string _haystack, string _needle) internal pure returns (int) { bytes memory h = bytes(_haystack); bytes memory n = bytes(_needle); if(h.length < 1 || n.length < 1 || (n.length > h.length)) return -1; else if(h.length > (2**128 -1)) return -1; else { uint subindex = 0; for (uint i = 0; i < h.length; i ++) { if (h[i] == n[0]) { subindex = 1; while(subindex < n.length && (i + subindex) < h.length && h[i + subindex] == n[subindex]) { subindex++; } if(subindex == n.length) return int(i); } } return -1; } } function strConcat(string _a, string _b, string _c, string _d, string _e) internal pure returns (string) { bytes memory _ba = bytes(_a); bytes memory _bb = bytes(_b); bytes memory _bc = bytes(_c); bytes memory _bd = bytes(_d); bytes memory _be = bytes(_e); string memory abcde = new string(_ba.length + _bb.length + _bc.length + _bd.length + _be.length); bytes memory babcde = bytes(abcde); uint k = 0; for (uint i = 0; i < _ba.length; i++) babcde[k++] = _ba[i]; for (i = 0; i < _bb.length; i++) babcde[k++] = _bb[i]; for (i = 0; i < _bc.length; i++) babcde[k++] = _bc[i]; for (i = 0; i < _bd.length; i++) babcde[k++] = _bd[i]; for (i = 0; i < _be.length; i++) babcde[k++] = _be[i]; return string(babcde); } function strConcat(string _a, string _b, string _c, string _d) internal pure returns (string) { return strConcat(_a, _b, _c, _d, ""); } function strConcat(string _a, string _b, string _c) internal pure returns (string) { return strConcat(_a, _b, _c, "", ""); } function strConcat(string _a, string _b) internal pure returns (string) { return strConcat(_a, _b, "", "", ""); } // parseInt function parseInt(string _a) internal pure returns (uint) { return parseInt(_a, 0); } // parseInt(parseFloat*10^_b) function parseInt(string _a, uint _b) internal pure returns (uint) { bytes memory bresult = bytes(_a); uint mint = 0; bool decimals = false; for (uint i=0; i<bresult.length; i++){ if ((bresult[i] >= 48)&&(bresult[i] <= 57)){ if (decimals){ if (_b == 0) break; else _b--; } mint *= 10; mint += uint(bresult[i]) - 48; } else if (bresult[i] == 46) decimals = true; } if (_b > 0) mint *= 10**_b; return mint; } function uint2str(uint i) internal pure returns (string){ if (i == 0) return "0"; uint j = i; uint len; while (j != 0){ len++; j /= 10; } bytes memory bstr = new bytes(len); uint k = len - 1; while (i != 0){ bstr[k--] = byte(48 + i % 10); i /= 10; } return string(bstr); } using CBOR for Buffer.buffer; function stra2cbor(string[] arr) internal pure returns (bytes) { Buffer.buffer memory buf; Buffer.init(buf, 1024); buf.startArray(); for (uint i = 0; i < arr.length; i++) { buf.encodeString(arr[i]); } buf.endSequence(); return buf.buf; } function ba2cbor(bytes[] arr) internal pure returns (bytes) { Buffer.buffer memory buf; Buffer.init(buf, 1024); buf.startArray(); for (uint i = 0; i < arr.length; i++) { buf.encodeBytes(arr[i]); } buf.endSequence(); return buf.buf; } string oraclize_network_name; function oraclize_setNetworkName(string _network_name) internal { oraclize_network_name = _network_name; } function oraclize_getNetworkName() internal view returns (string) { return oraclize_network_name; } function oraclize_newRandomDSQuery(uint _delay, uint _nbytes, uint _customGasLimit) internal returns (bytes32){ require((_nbytes > 0) && (_nbytes <= 32)); // Convert from seconds to ledger timer ticks _delay *= 10; bytes memory nbytes = new bytes(1); nbytes[0] = byte(_nbytes); bytes memory unonce = new bytes(32); bytes memory sessionKeyHash = new bytes(32); bytes32 sessionKeyHash_bytes32 = oraclize_randomDS_getSessionPubKeyHash(); assembly { mstore(unonce, 0x20) // the following variables can be relaxed // check relaxed random contract under ethereum-examples repo // for an idea on how to override and replace comit hash vars mstore(add(unonce, 0x20), xor(blockhash(sub(number, 1)), xor(coinbase, timestamp))) mstore(sessionKeyHash, 0x20) mstore(add(sessionKeyHash, 0x20), sessionKeyHash_bytes32) } bytes memory delay = new bytes(32); assembly { mstore(add(delay, 0x20), _delay) } bytes memory delay_bytes8 = new bytes(8); copyBytes(delay, 24, 8, delay_bytes8, 0); bytes[4] memory args = [unonce, nbytes, sessionKeyHash, delay]; bytes32 queryId = oraclize_query("random", args, _customGasLimit); bytes memory delay_bytes8_left = new bytes(8); assembly { let x := mload(add(delay_bytes8, 0x20)) mstore8(add(delay_bytes8_left, 0x27), div(x, 0x100000000000000000000000000000000000000000000000000000000000000)) mstore8(add(delay_bytes8_left, 0x26), div(x, 0x1000000000000000000000000000000000000000000000000000000000000)) mstore8(add(delay_bytes8_left, 0x25), div(x, 0x10000000000000000000000000000000000000000000000000000000000)) mstore8(add(delay_bytes8_left, 0x24), div(x, 0x100000000000000000000000000000000000000000000000000000000)) mstore8(add(delay_bytes8_left, 0x23), div(x, 0x1000000000000000000000000000000000000000000000000000000)) mstore8(add(delay_bytes8_left, 0x22), div(x, 0x10000000000000000000000000000000000000000000000000000)) mstore8(add(delay_bytes8_left, 0x21), div(x, 0x100000000000000000000000000000000000000000000000000)) mstore8(add(delay_bytes8_left, 0x20), div(x, 0x1000000000000000000000000000000000000000000000000)) } oraclize_randomDS_setCommitment(queryId, keccak256(delay_bytes8_left, args[1], sha256(args[0]), args[2])); return queryId; } function oraclize_randomDS_setCommitment(bytes32 queryId, bytes32 commitment) internal { oraclize_randomDS_args[queryId] = commitment; } mapping(bytes32=>bytes32) oraclize_randomDS_args; mapping(bytes32=>bool) oraclize_randomDS_sessionKeysHashVerified; function verifySig(bytes32 tosignh, bytes dersig, bytes pubkey) internal returns (bool){ bool sigok; address signer; bytes32 sigr; bytes32 sigs; bytes memory sigr_ = new bytes(32); uint offset = 4+(uint(dersig[3]) - 0x20); sigr_ = copyBytes(dersig, offset, 32, sigr_, 0); bytes memory sigs_ = new bytes(32); offset += 32 + 2; sigs_ = copyBytes(dersig, offset+(uint(dersig[offset-1]) - 0x20), 32, sigs_, 0); assembly { sigr := mload(add(sigr_, 32)) sigs := mload(add(sigs_, 32)) } (sigok, signer) = safer_ecrecover(tosignh, 27, sigr, sigs); if (address(keccak256(pubkey)) == signer) return true; else { (sigok, signer) = safer_ecrecover(tosignh, 28, sigr, sigs); return (address(keccak256(pubkey)) == signer); } } function oraclize_randomDS_proofVerify__sessionKeyValidity(bytes proof, uint sig2offset) internal returns (bool) { bool sigok; // Step 6: verify the attestation signature, APPKEY1 must sign the sessionKey from the correct ledger app (CODEHASH) bytes memory sig2 = new bytes(uint(proof[sig2offset+1])+2); copyBytes(proof, sig2offset, sig2.length, sig2, 0); bytes memory appkey1_pubkey = new bytes(64); copyBytes(proof, 3+1, 64, appkey1_pubkey, 0); bytes memory tosign2 = new bytes(1+65+32); tosign2[0] = byte(1); //role copyBytes(proof, sig2offset-65, 65, tosign2, 1); bytes memory CODEHASH = hex"fd94fa71bc0ba10d39d464d0d8f465efeef0a2764e3887fcc9df41ded20f505c"; copyBytes(CODEHASH, 0, 32, tosign2, 1+65); sigok = verifySig(sha256(tosign2), sig2, appkey1_pubkey); if (sigok == false) return false; // Step 7: verify the APPKEY1 provenance (must be signed by Ledger) bytes memory LEDGERKEY = hex"7fb956469c5c9b89840d55b43537e66a98dd4811ea0a27224272c2e5622911e8537a2f8e86a46baec82864e98dd01e9ccc2f8bc5dfc9cbe5a91a290498dd96e4"; bytes memory tosign3 = new bytes(1+65); tosign3[0] = 0xFE; copyBytes(proof, 3, 65, tosign3, 1); bytes memory sig3 = new bytes(uint(proof[3+65+1])+2); copyBytes(proof, 3+65, sig3.length, sig3, 0); sigok = verifySig(sha256(tosign3), sig3, LEDGERKEY); return sigok; } modifier oraclize_randomDS_proofVerify(bytes32 _queryId, string _result, bytes _proof) { // Step 1: the prefix has to match 'LP\x01' (Ledger Proof version 1) require((_proof[0] == "L") && (_proof[1] == "P") && (_proof[2] == 1)); bool proofVerified = oraclize_randomDS_proofVerify__main(_proof, _queryId, bytes(_result), oraclize_getNetworkName()); require(proofVerified); _; } function oraclize_randomDS_proofVerify__returnCode(bytes32 _queryId, string _result, bytes _proof) internal returns (uint8){ // Step 1: the prefix has to match 'LP\x01' (Ledger Proof version 1) if ((_proof[0] != "L")||(_proof[1] != "P")||(_proof[2] != 1)) return 1; bool proofVerified = oraclize_randomDS_proofVerify__main(_proof, _queryId, bytes(_result), oraclize_getNetworkName()); if (proofVerified == false) return 2; return 0; } function matchBytes32Prefix(bytes32 content, bytes prefix, uint n_random_bytes) internal pure returns (bool){ bool match_ = true; require(prefix.length == n_random_bytes); for (uint256 i=0; i< n_random_bytes; i++) { if (content[i] != prefix[i]) match_ = false; } return match_; } function oraclize_randomDS_proofVerify__main(bytes proof, bytes32 queryId, bytes result, string context_name) internal returns (bool){ // Step 2: the unique keyhash has to match with the sha256 of (context name + queryId) uint ledgerProofLength = 3+65+(uint(proof[3+65+1])+2)+32; bytes memory keyhash = new bytes(32); copyBytes(proof, ledgerProofLength, 32, keyhash, 0); if (!(keccak256(keyhash) == keccak256(sha256(context_name, queryId)))) return false; bytes memory sig1 = new bytes(uint(proof[ledgerProofLength+(32+8+1+32)+1])+2); copyBytes(proof, ledgerProofLength+(32+8+1+32), sig1.length, sig1, 0); // Step 3: we assume sig1 is valid (it will be verified during step 5) and we verify if 'result' is the prefix of sha256(sig1) if (!matchBytes32Prefix(sha256(sig1), result, uint(proof[ledgerProofLength+32+8]))) return false; // Step 4: commitment match verification, keccak256(delay, nbytes, unonce, sessionKeyHash) == commitment in storage. // This is to verify that the computed args match with the ones specified in the query. bytes memory commitmentSlice1 = new bytes(8+1+32); copyBytes(proof, ledgerProofLength+32, 8+1+32, commitmentSlice1, 0); bytes memory sessionPubkey = new bytes(64); uint sig2offset = ledgerProofLength+32+(8+1+32)+sig1.length+65; copyBytes(proof, sig2offset-64, 64, sessionPubkey, 0); bytes32 sessionPubkeyHash = sha256(sessionPubkey); if (oraclize_randomDS_args[queryId] == keccak256(commitmentSlice1, sessionPubkeyHash)){ //unonce, nbytes and sessionKeyHash match delete oraclize_randomDS_args[queryId]; } else return false; // Step 5: validity verification for sig1 (keyhash and args signed with the sessionKey) bytes memory tosign1 = new bytes(32+8+1+32); copyBytes(proof, ledgerProofLength, 32+8+1+32, tosign1, 0); if (!verifySig(sha256(tosign1), sig1, sessionPubkey)) return false; // verify if sessionPubkeyHash was verified already, if not.. let's do it! if (oraclize_randomDS_sessionKeysHashVerified[sessionPubkeyHash] == false){ oraclize_randomDS_sessionKeysHashVerified[sessionPubkeyHash] = oraclize_randomDS_proofVerify__sessionKeyValidity(proof, sig2offset); } return oraclize_randomDS_sessionKeysHashVerified[sessionPubkeyHash]; } // the following function has been written by Alex Beregszaszi (@axic), use it under the terms of the MIT license function copyBytes(bytes from, uint fromOffset, uint length, bytes to, uint toOffset) internal pure returns (bytes) { uint minLength = length + toOffset; // Buffer too small require(to.length >= minLength); // Should be a better way? // NOTE: the offset 32 is added to skip the `size` field of both bytes variables uint i = 32 + fromOffset; uint j = 32 + toOffset; while (i < (32 + fromOffset + length)) { assembly { let tmp := mload(add(from, i)) mstore(add(to, j), tmp) } i += 32; j += 32; } return to; } // the following function has been written by Alex Beregszaszi (@axic), use it under the terms of the MIT license // Duplicate Solidity's ecrecover, but catching the CALL return value function safer_ecrecover(bytes32 hash, uint8 v, bytes32 r, bytes32 s) internal returns (bool, address) { // We do our own memory management here. Solidity uses memory offset // 0x40 to store the current end of memory. We write past it (as // writes are memory extensions), but don't update the offset so // Solidity will reuse it. The memory used here is only needed for // this context. // FIXME: inline assembly can't access return values bool ret; address addr; assembly { let size := mload(0x40) mstore(size, hash) mstore(add(size, 32), v) mstore(add(size, 64), r) mstore(add(size, 96), s) // NOTE: we can reuse the request memory because we deal with // the return code ret := call(3000, 1, 0, size, 128, size, 32) addr := mload(size) } return (ret, addr); } // the following function has been written by Alex Beregszaszi (@axic), use it under the terms of the MIT license function ecrecovery(bytes32 hash, bytes sig) internal returns (bool, address) { bytes32 r; bytes32 s; uint8 v; if (sig.length != 65) return (false, 0); // The signature format is a compact form of: // {bytes32 r}{bytes32 s}{uint8 v} // Compact means, uint8 is not padded to 32 bytes. assembly { r := mload(add(sig, 32)) s := mload(add(sig, 64)) // Here we are loading the last 32 bytes. We exploit the fact that // 'mload' will pad with zeroes if we overread. // There is no 'mload8' to do this, but that would be nicer. v := byte(0, mload(add(sig, 96))) // Alternative solution: // 'byte' is not working due to the Solidity parser, so lets // use the second best option, 'and' // v := and(mload(add(sig, 65)), 255) } // albeit non-transactional signatures are not specified by the YP, one would expect it // to match the YP range of [27, 28] // // geth uses [0, 1] and some clients have followed. This might change, see: // https://github.com/ethereum/go-ethereum/issues/2053 if (v < 27) v += 27; if (v != 27 && v != 28) return (false, 0); return safer_ecrecover(hash, v, r, s); } } // </ORACLIZE_API> // 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/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: contracts\BethingWorldCup.sol /** * @title BethingWorldCup * @author Bething.io - [email protected] * * @dev A parimutuel betting pool for the FIFA World Cup 2018. Players can place multiple bets on one or more teams, * and the total pool amount is then shared amongst all winning bets. Outcome is determine via a Wolfram Alpha Oracle. */ contract BethingWorldCup is Ownable, usingOraclize { using SafeMath for uint256; // ============ Events ============ event BetPlaced(address indexed better, uint256 betAmount); event PayoutClaimed(address indexed better, uint256 payoutAmount); event RefundClaimed(address indexed better, uint256 refundAmount); event CommissionPaid(address indexed bookie, uint256 commissionAmount); event Donated(address indexed charity, uint256 donatedAmount); event WinningTeamQuerySent(string query); event WinningTeamDetermined(bytes32 id, string winningTeam, bytes proof); // ============ Constants ============ // GiveDirectly charity address (https://givedirectly.org/give-now?crypto=eth) address public constant CHARITY = 0xc7464dbcA260A8faF033460622B23467Df5AEA42; // Minimum bet amount uint256 public constant MIN_BET_AMOUNT = 0.01 ether; // Commission rate to be paid to the bookie uint256 public constant COMMISSION_RATE = 4; // 4% // Percentage to be donated to charity uint256 public constant DONATION_RATE = 1; // 1% // Time from which betting is disabled (5 mins before kick-off) uint256 public BETS_CLOSING_TIME = 1531666500; // 15 Jul 2018 - 14:55 UTC // Interval before we try to query Wolfram Alpha to determine the winner of the event uint256 public PAYOUT_DELAY_INTERVAL = 24 hours; // Time from which payouts are enabled provided the winning team has been determined uint256 public PAYOUT_TIME = BETS_CLOSING_TIME + PAYOUT_DELAY_INTERVAL; // Time from which refunds are disabled provided the winning team has NOT been determined uint256 public REFUND_TIME = BETS_CLOSING_TIME + 7 days; // 22 Jul 2018 - 14:55 UTC // Total number of teams uint256 public constant TOTAL_TEAMS = 2; // Teams participating in the competition string[TOTAL_TEAMS] public TEAMS = [ "France", "Croatia" ]; // ============ State Variables ============ // Total number of bets uint256 public totalBets; // Total amount of bets placed on the betting pool uint256 public totalBetAmount; // Total amount of bets placed on each team uint256[TOTAL_TEAMS] public teamTotalBetAmount; // Bet amounts for a given player mapping(address => uint256[TOTAL_TEAMS]) public betterBetAmounts; // Mapping to determine if a payout has already been claimed for a given address to prevent reentrancy mapping(address => bool) public payoutClaimed; // Mapping to determine if a refund has already been claimed for a given address to prevent reentrancy mapping(address => bool) public refundClaimed; // Indicates if refunds are enable which can happen if it is not possible to determine the winning team bool private refundsEnabled; // Winning team uint256 private winningTeam; // Winning team name string public winningTeamName; // Indicates if the winning team has been correctly determined bool private winningTeamDetermined; // Total payout amount for bets on the winning team uint256 public totalPayoutAmount; // ============ Modifiers ============ /** * @dev Reverts if not in betting time range. */ modifier whenNotClosed() { require(!hasClosed()); _; } /** * @dev Reverts if it is not possible for the sender to refund the original bet. */ modifier whenCanClaimRefund() { require(canClaimRefund(msg.sender)); _; } /** * @dev Reverts if it is not possible for the sender to claim the payout. */ modifier whenCanClaimPayout() { require(canClaimPayout(msg.sender)); _; } /** * @dev Reverts if team is not valid. */ modifier isValidTeam(uint256 team) { require(team <= TOTAL_TEAMS); _; } // ============ Constructor ============ /** * @dev Constructor. */ function BethingWorldCup() public payable { queryWinningTeam(PAYOUT_TIME - now); } /** * @dev fallback function. */ function () external payable onlyOwner {} // ============ State-Changing Functions ============ /** * @dev Places a bet for a given team. */ function bet(uint256 team) external payable whenNotClosed isValidTeam(team) { address better = msg.sender; uint256 betAmount = msg.value; require(betAmount >= MIN_BET_AMOUNT); betterBetAmounts[better][team] = betterBetAmounts[better][team].add(betAmount); totalBetAmount = totalBetAmount.add(betAmount); teamTotalBetAmount[team] = teamTotalBetAmount[team].add(betAmount); totalBets++; BetPlaced(better, betAmount); } /** * @dev Places a bet for a given team. */ function claimPayout() external whenCanClaimPayout { address better = msg.sender; uint256 betterWinningTeamBetAmount = betterBetAmounts[better][winningTeam]; uint256 winningTeamTotalBetAmount = teamTotalBetAmount[winningTeam]; uint256 betterPayoutAmount = betterWinningTeamBetAmount.mul(totalPayoutAmount).div(winningTeamTotalBetAmount); payoutClaimed[better] = true; better.transfer(betterPayoutAmount); PayoutClaimed(better, betterPayoutAmount); } /** * @dev Refunds total bet amount iff it was not possible to determine the winner. */ function claimRefund() external whenCanClaimRefund { address better = msg.sender; uint256 refundAmount = 0; for (uint256 i = 0; i < TEAMS.length; i++) { refundAmount = refundAmount.add(betterBetAmounts[better][i]); } assert(refundAmount > 0); refundClaimed[better] = true; better.transfer(refundAmount); RefundClaimed(better, refundAmount); } /** * @dev Schedules a WolframAlpha query to Oraclize to determine the winner of the competition. */ function queryWinningTeam(uint256 delay) private { oraclize_query(delay, "WolframAlpha", "FIFA World Cup 2018 Winner"); WinningTeamQuerySent("FIFA World Cup 2018 Winner"); } /** * @dev Callback from Oraclize with the name of the winning team. */ function __callback(bytes32 id, string result, bytes proof) public { require(msg.sender == oraclize_cbAddress()); require(!winningTeamDetermined); require(!refundsEnabled); // Determine the winning team based on the query result from Wolfram Alpha for (uint256 i = 0; i < TEAMS.length; i++) { if (keccak256(TEAMS[i]) == keccak256(result)) { winningTeamDetermined = true; winningTeamName = result; winningTeam = i; break; } } if (winningTeamDetermined) { // If a winning team is determined, calculate total payout amount to allow betters to claim their payout calculateTotalPayoutAmountAndCommission(); WinningTeamDetermined(id, winningTeamName, proof); } else { if (now >= REFUND_TIME) { // If we are past the refund time, we allow betters to ask for a refund of their original bets refundsEnabled = true; } else { // Otherwise, reschedule another attempt to determine the winner for the next day queryWinningTeam(PAYOUT_DELAY_INTERVAL); } } } /** * @dev Allow owner to suicide the contract after a year. */ function kill() public onlyOwner { require(now > (BETS_CLOSING_TIME + 1 years)); selfdestruct(owner); } // ============ Public Constant Functions ============ /** * @dev Checks whether the period in which the betting is open has already elapsed. * @return Whether betting period has elapsed */ function hasClosed() public view returns (bool) { return now > BETS_CLOSING_TIME; } /** * @dev Checks whether the sender is eligible for claiming a refund. * @return Whether sender is eligible to claim a refund */ function canClaimRefund(address sender) public view returns (bool) { return ( refundsEnabled && !refundClaimed[sender] ); } /** * @dev Checks whether the sender is eligible for claiming a payout. * @return Whether sender is eligible to claim a payout */ function canClaimPayout(address sender) public view returns (bool) { return ( winningTeamDetermined && !payoutClaimed[sender] && betterBetAmounts[sender][winningTeam] > 0 ); } // ============ Private Functions ============ /* * @dev Calculates the total payout amount, commission, and donation amounts. */ function calculateTotalPayoutAmountAndCommission() private { uint256 commissionAmount = totalBetAmount.mul(COMMISSION_RATE).div(100); uint256 donationAmount = totalBetAmount.mul(DONATION_RATE).div(100); totalPayoutAmount = totalBetAmount.sub(commissionAmount).sub(donationAmount); owner.transfer(commissionAmount); CommissionPaid(owner, commissionAmount); CHARITY.transfer(donationAmount); Donated(CHARITY, donationAmount); } }
Calculates the total payout amount, commission, and donation amounts./
function calculateTotalPayoutAmountAndCommission() private { uint256 commissionAmount = totalBetAmount.mul(COMMISSION_RATE).div(100); uint256 donationAmount = totalBetAmount.mul(DONATION_RATE).div(100); totalPayoutAmount = totalBetAmount.sub(commissionAmount).sub(donationAmount); owner.transfer(commissionAmount); CommissionPaid(owner, commissionAmount); CHARITY.transfer(donationAmount); Donated(CHARITY, donationAmount); }
13,826,700
// SPDX-License-Identifier: MIT pragma solidity 0.8.13; // @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ // @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ // @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ // @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ // @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ // @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ // @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@&&BBBBBBBGG&@@@@@@@@@&&&&&&@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ // @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@&P!: :[email protected]@@@&P7^. .^?G&@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ // @@@@@@@@@@@@@@@@@@@@@@@@@@@@&J. :#@@@#7. :Y&@@@@@@@@@@@@@@@@@@@@@@@@@@@@ // @@@@@@@@@@@@@@@@@@@@@@@@@@&! [email protected]@@B: !&@@@@@@@@@@@@@@@@@@@@@@@@@@ // @@@@@@@@@@@@@@@@@@@@@@@@@P [email protected]@@~ [email protected]@@@@@@@@@@@@@@@@@@@@@@@@ // @@@@@@@@@@@@@@@@@@@@@@@@J [email protected]@&. [email protected]@@@@@@@@@@@@@@@@@@@@@@@ // @@@@@@@@@@@@@@@@@@@@@@@G [email protected]@@. [email protected]@@@@@@@@@@@@@@@@@@@@@@ // @@@@@@@@@@@@@@@@@@@@@@@. &@@Y #@@@@@@@@@@@@@@@@@@@@@@ // @@@@@@@@@@@@@@@@@@@@@@& [email protected]@@&##########&&&&&&&&&&&#############@@@@@@@@@@@@@@@@@@@@@@@ // @@@@@@@@@@@@@@@@@@@@@@& [email protected]@@@@@@@@@@@@@#B######&&@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ // @@@@@@@@@@@@@@@@@@@@@@@. &@@@@@@@@@@@@@B~ .:!5&@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ // @@@@@@@@@@@@@@@@@@@@@@@B [email protected]@@@@@@@@@@@@@@&! .7#@@@@@@@@@@@@@@@@@@@@@@@@@@@@ // @@@@@@@@@@@@@@@@@@@@@@@@Y [email protected]@@@@@@@@@@@@@@@B. ^#@@@@@@@@@@@@@@@@@@@@@@@@@@ // @@@@@@@@@@@@@@@@@@@@@@@@@G [email protected]@@@@@@@@@@@@@@@@: [email protected]@@@@@@@@@@@@@@@@@@@@@@@@ // @@@@@@@@@@@@@@@@@@@@@@@@@@@? [email protected]@@@@@@@@@@@@@@@@. ^@@@@@@@@@@@@@@@@@@@@@@@@ // @@@@@@@@@@@@@@@@@@@@@@@@@@@@@5: [email protected]@@@@@@@@@@@@@@B [email protected]@@@@@@@@@@@@@@@@@@@@@@ // @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@&G7^. :[email protected]@@@@@@@@@@@@@: #@@@@@@@@@@@@@@@@@@@@@@ // @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@&#######BB&@@@@@@@@@@@@@7 [email protected]@@@@@@@@@@@@@@@@@@@@@ // @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@? [email protected]@@@@@@@@@@@@@@@@@@@@@ // @@@@@@@@@@@@@@@@@@@@@@@. ^@@@: [email protected]@@@@@@@@@@@@@@@@@@@@@ // @@@@@@@@@@@@@@@@@@@@@@@Y [email protected]@# ^@@@@@@@@@@@@@@@@@@@@@@@ // @@@@@@@@@@@@@@@@@@@@@@@@! [email protected]@@: [email protected]@@@@@@@@@@@@@@@@@@@@@@@ // @@@@@@@@@@@@@@@@@@@@@@@@@Y [email protected]@@^ [email protected]@@@@@@@@@@@@@@@@@@@@@@@@ // @@@@@@@@@@@@@@@@@@@@@@@@@@&~ !&@@&. :[email protected]@@@@@@@@@@@@@@@@@@@@@@@@@ // @@@@@@@@@@@@@@@@@@@@@@@@@@@@&?. .J&@@@? [email protected]@@@@@@@@@@@@@@@@@@@@@@@@@@@ // @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@#Y~. :!5&@@@#7 .^[email protected]@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ // @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@&#BGGGB#&@@@@@@@@BPGGGGGGB#&@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ // @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ // @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ // @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ // @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ // @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ // @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ // @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ import "@openzeppelin/contracts/access/AccessControl.sol"; import "@openzeppelin/contracts/utils/cryptography/MerkleProof.sol"; import "@openzeppelin/contracts/utils/math/Math.sol"; import "./common/SaleCommon.sol"; contract ETHSale is AccessControl, SaleCommon { struct Sale { uint256 id; uint256 volume; uint256 presale; uint256 starttime; // to start immediately, set starttime = 0 uint256 endtime; bool active; bytes32 merkleRoot; // Merkle root of the entrylist Merkle tree, 0x00 for non-merkle sale uint256 maxQuantity; uint256 price; // in Wei, where 10^18 Wei = 1 ETH uint256 startTokenIndex; uint256 maxPLOTs; uint256 mintedPLOTs; } Sale[] public sales; mapping(uint256 => mapping(address => uint256)) public minted; // sale ID => account => quantity /// @notice Constructor /// @param _plot Storyverse Plot contract constructor(address _plot) SaleCommon(_plot) {} /// @notice Get the current sale /// @return Current sale function currentSale() public view returns (Sale memory) { require(sales.length > 0, "no current sale"); return sales[sales.length - 1]; } /// @notice Get the current sale ID /// @return Current sale ID function currentSaleId() public view returns (uint256) { require(sales.length > 0, "no current sale"); return sales.length - 1; } /// @notice Checks if the provided token ID parameters are likely to overlap a previous or current sale /// @param _startTokenIndex Token index to start the sale from /// @param _maxPLOTs Maximum number of PLOTs that can be minted in this sale /// @return valid_ If the current token ID range paramters are likely safe function isSafeTokenIdRange(uint256 _startTokenIndex, uint256 _maxPLOTs) external view returns (bool valid_) { return _isSafeTokenIdRange(_startTokenIndex, _maxPLOTs, sales.length); } function _checkSafeTokenIdRange( uint256 _startTokenIndex, uint256 _maxPLOTs, uint256 _maxSaleId ) internal view { // If _maxSaleId is passed in as the current sale ID, then // the check will skip the current sale ID in _isSafeTokenIdRange() // since in that case _maxSaleId == sales.length - 1 require( _isSafeTokenIdRange(_startTokenIndex, _maxPLOTs, _maxSaleId), "overlapping token ID range" ); } function _isSafeTokenIdRange( uint256 _startTokenIndex, uint256 _maxPLOTs, uint256 _maxSaleId ) internal view returns (bool valid_) { if (_maxPLOTs == 0) { return true; } for (uint256 i = 0; i < _maxSaleId; i++) { // if no minted PLOTs in sale, ignore if (sales[i].mintedPLOTs == 0) { continue; } uint256 saleStartTokenIndex = sales[i].startTokenIndex; uint256 saleMintedPLOTs = sales[i].mintedPLOTs; if (_startTokenIndex < saleStartTokenIndex) { // start index is less than the sale's start token index, so ensure // it doesn't extend into the sale's range if max PLOTs are minted if (_startTokenIndex + _maxPLOTs - 1 >= saleStartTokenIndex) { return false; } } else { // start index greater than or equal to the sale's start token index, so ensure // it starts after the sale's start token index + the number of PLOTs minted if (_startTokenIndex <= saleStartTokenIndex + saleMintedPLOTs - 1) { return false; } } } return true; } /// @notice Adds a new sale /// @param _volume Volume of the sale /// @param _presale Presale of the sale /// @param _starttime Start time of the sale /// @param _endtime End time of the sale /// @param _active Whether the sale is active /// @param _merkleRoot Merkle root of the entry list Merkle tree, 0x00 for non-merkle sale /// @param _maxQuantity Maximum number of PLOTs per account that can be sold /// @param _price Price of each PLOT /// @param _startTokenIndex Token index to start the sale from /// @param _maxPLOTs Maximum number of PLOTs that can be minted in this sale function addSale( uint256 _volume, uint256 _presale, uint256 _starttime, uint256 _endtime, bool _active, bytes32 _merkleRoot, uint256 _maxQuantity, uint256 _price, uint256 _startTokenIndex, uint256 _maxPLOTs ) public onlyRole(DEFAULT_ADMIN_ROLE) { uint256 saleId = sales.length; checkTokenParameters(_volume, _presale, _startTokenIndex); _checkSafeTokenIdRange(_startTokenIndex, _maxPLOTs, saleId); Sale memory sale = Sale({ id: saleId, volume: _volume, presale: _presale, starttime: _starttime, endtime: _endtime, active: _active, merkleRoot: _merkleRoot, maxQuantity: _maxQuantity, price: _price, startTokenIndex: _startTokenIndex, maxPLOTs: _maxPLOTs, mintedPLOTs: 0 }); sales.push(sale); emit SaleAdded(msg.sender, saleId); } /// @notice Updates the current sale /// @param _volume Volume of the sale /// @param _presale Presale of the sale /// @param _starttime Start time of the sale /// @param _endtime End time of the sale /// @param _active Whether the sale is active /// @param _merkleRoot Merkle root of the entry list Merkle tree, 0x00 for non-merkle sale /// @param _maxQuantity Maximum number of PLOTs per account that can be sold /// @param _price Price of each PLOT /// @param _startTokenIndex Token index to start the sale from /// @param _maxPLOTs Maximum number of PLOTs that can be minted in this sale function updateSale( uint256 _volume, uint256 _presale, uint256 _starttime, uint256 _endtime, bool _active, bytes32 _merkleRoot, uint256 _maxQuantity, uint256 _price, uint256 _startTokenIndex, uint256 _maxPLOTs ) external onlyRole(DEFAULT_ADMIN_ROLE) { uint256 saleId = currentSaleId(); checkTokenParameters(_volume, _presale, _startTokenIndex); _checkSafeTokenIdRange(_startTokenIndex, _maxPLOTs, saleId); Sale memory sale = Sale({ id: saleId, volume: _volume, presale: _presale, starttime: _starttime, endtime: _endtime, active: _active, merkleRoot: _merkleRoot, maxQuantity: _maxQuantity, price: _price, startTokenIndex: _startTokenIndex, maxPLOTs: _maxPLOTs, mintedPLOTs: sales[saleId].mintedPLOTs }); sales[saleId] = sale; emit SaleUpdated(msg.sender, saleId); } /// @notice Updates the volume of the current sale /// @param _volume Volume of the sale function updateSaleVolume(uint256 _volume) external onlyRole(DEFAULT_ADMIN_ROLE) { uint256 saleId = currentSaleId(); checkTokenParameters(_volume, sales[saleId].presale, sales[saleId].startTokenIndex); sales[saleId].volume = _volume; emit SaleUpdated(msg.sender, saleId); } /// @notice Updates the presale of the current sale /// @param _presale Presale of the sale function updateSalePresale(uint256 _presale) external onlyRole(DEFAULT_ADMIN_ROLE) { uint256 saleId = currentSaleId(); checkTokenParameters(sales[saleId].volume, _presale, sales[saleId].startTokenIndex); sales[saleId].presale = _presale; emit SaleUpdated(msg.sender, saleId); } /// @notice Updates the start time of the current sale /// @param _starttime Start time of the sale function updateSaleStarttime(uint256 _starttime) external onlyRole(DEFAULT_ADMIN_ROLE) { uint256 saleId = currentSaleId(); sales[saleId].starttime = _starttime; emit SaleUpdated(msg.sender, saleId); } /// @notice Updates the end time of the current sale /// @param _endtime End time of the sale function updateSaleEndtime(uint256 _endtime) external onlyRole(DEFAULT_ADMIN_ROLE) { uint256 saleId = currentSaleId(); sales[saleId].endtime = _endtime; emit SaleUpdated(msg.sender, saleId); } /// @notice Updates the active status of the current sale /// @param _active Whether the sale is active function updateSaleActive(bool _active) external onlyRole(DEFAULT_ADMIN_ROLE) { uint256 saleId = currentSaleId(); sales[saleId].active = _active; emit SaleUpdated(msg.sender, saleId); } /// @notice Updates the merkle root of the current sale /// @param _merkleRoot Merkle root of the entry list Merkle tree, 0x00 for non-merkle sale function updateSaleMerkleRoot(bytes32 _merkleRoot) external onlyRole(DEFAULT_ADMIN_ROLE) { uint256 saleId = currentSaleId(); sales[saleId].merkleRoot = _merkleRoot; emit SaleUpdated(msg.sender, saleId); } /// @notice Updates the max quantity of the current sale /// @param _maxQuantity Maximum number of PLOTs per account that can be sold function updateSaleMaxQuantity(uint256 _maxQuantity) external onlyRole(DEFAULT_ADMIN_ROLE) { uint256 saleId = currentSaleId(); sales[saleId].maxQuantity = _maxQuantity; emit SaleUpdated(msg.sender, saleId); } /// @notice Updates the price of each PLOT for the current sale /// @param _price Price of each PLOT function updateSalePrice(uint256 _price) external onlyRole(DEFAULT_ADMIN_ROLE) { uint256 saleId = currentSaleId(); sales[saleId].price = _price; emit SaleUpdated(msg.sender, saleId); } /// @notice Updates the start token index of the current sale /// @param _startTokenIndex Token index to start the sale from function updateSaleStartTokenIndex(uint256 _startTokenIndex) external onlyRole(DEFAULT_ADMIN_ROLE) { uint256 saleId = currentSaleId(); _checkSafeTokenIdRange(_startTokenIndex, sales[saleId].maxPLOTs, saleId); checkTokenParameters(sales[saleId].volume, sales[saleId].presale, _startTokenIndex); sales[saleId].startTokenIndex = _startTokenIndex; emit SaleUpdated(msg.sender, saleId); } /// @notice Updates the of the current sale /// @param _maxPLOTs Maximum number of PLOTs that can be minted in this sale function updateSaleMaxPLOTs(uint256 _maxPLOTs) external onlyRole(DEFAULT_ADMIN_ROLE) { uint256 saleId = currentSaleId(); _checkSafeTokenIdRange(sales[saleId].startTokenIndex, _maxPLOTs, saleId); sales[saleId].maxPLOTs = _maxPLOTs; emit SaleUpdated(msg.sender, saleId); } function _mintTo( address _to, uint256 _volume, uint256 _presale, uint256 _startTokenIndex, uint256 _quantity ) internal { require(_quantity > 0, "quantity must be greater than 0"); for (uint256 i = 0; i < _quantity; i++) { uint256 tokenIndex = _startTokenIndex + i; uint256 tokenId = buildTokenId(_volume, _presale, tokenIndex); IStoryversePlot(plot).safeMint(_to, tokenId); } emit Minted(msg.sender, _to, _quantity, msg.value); } /// @notice Mints new tokens in exchange for ETH /// @param _to Owner of the newly minted token /// @param _quantity Quantity of tokens to mint function mintTo(address _to, uint256 _quantity) external payable nonReentrant { Sale memory sale = currentSale(); // only proceed if no merkle root is set require(sale.merkleRoot == bytes32(0), "merkle sale requires valid proof"); // check sale validity require(sale.active, "sale is inactive"); require(block.timestamp >= sale.starttime, "sale has not started"); require(block.timestamp < sale.endtime, "sale has ended"); // validate payment and authorized quantity require(msg.value == sale.price * _quantity, "incorrect payment for quantity and price"); require( minted[sale.id][msg.sender] + _quantity <= sale.maxQuantity, "exceeds allowed quantity" ); // check sale supply require(sale.mintedPLOTs + _quantity <= sale.maxPLOTs, "insufficient supply"); sales[sale.id].mintedPLOTs += _quantity; minted[sale.id][msg.sender] += _quantity; _mintTo( _to, sale.volume, sale.presale, sale.startTokenIndex + sale.mintedPLOTs, _quantity ); } /// @notice Mints new tokens in exchange for ETH based on the sale's entry list /// @param _proof Merkle proof to validate the caller is on the sale's entry list /// @param _maxQuantity Max quantity that the caller can mint /// @param _to Owner of the newly minted token /// @param _quantity Quantity of tokens to mint function entryListMintTo( bytes32[] calldata _proof, uint256 _maxQuantity, address _to, uint256 _quantity ) external payable nonReentrant { Sale memory sale = currentSale(); // validate merkle proof bytes32 leaf = keccak256(abi.encodePacked(msg.sender, _maxQuantity)); require(MerkleProof.verify(_proof, sale.merkleRoot, leaf), "invalid proof"); // check sale validity require(sale.active, "sale is inactive"); require(block.timestamp >= sale.starttime, "sale has not started"); require(block.timestamp < sale.endtime, "sale has ended"); // validate payment and authorized quantity require(msg.value == sale.price * _quantity, "incorrect payment for quantity and price"); require( minted[sale.id][msg.sender] + _quantity <= Math.max(sale.maxQuantity, _maxQuantity), "exceeds allowed quantity" ); // check sale supply require(sale.mintedPLOTs + _quantity <= sale.maxPLOTs, "insufficient supply"); sales[sale.id].mintedPLOTs += _quantity; minted[sale.id][msg.sender] += _quantity; _mintTo( _to, sale.volume, sale.presale, sale.startTokenIndex + sale.mintedPLOTs, _quantity ); } /// @notice Administrative mint function within the constraints of the current sale, skipping some checks /// @param _to Owner of the newly minted token /// @param _quantity Quantity of tokens to mint function adminSaleMintTo(address _to, uint256 _quantity) external onlyRole(MINTER_ROLE) { Sale memory sale = currentSale(); // check sale supply require(sale.mintedPLOTs + _quantity <= sale.maxPLOTs, "insufficient supply"); sales[sale.id].mintedPLOTs += _quantity; minted[sale.id][msg.sender] += _quantity; _mintTo( _to, sale.volume, sale.presale, sale.startTokenIndex + sale.mintedPLOTs, _quantity ); } /// @notice Administrative mint function /// @param _to Owner of the newly minted token /// @param _quantity Quantity of tokens to mint function adminMintTo( address _to, uint256 _volume, uint256 _presale, uint256 _startTokenIndex, uint256 _quantity ) external onlyRole(DEFAULT_ADMIN_ROLE) { // add a sale (clobbering any current sale) to ensure token ranges // are respected and recorded addSale( _volume, _presale, block.timestamp, block.timestamp, false, bytes32(0), 0, 2**256 - 1, _startTokenIndex, _quantity ); // record the sale as fully minted sales[sales.length - 1].mintedPLOTs = _quantity; _mintTo(_to, _volume, _presale, _startTokenIndex, _quantity); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.5.0) (access/AccessControl.sol) pragma solidity ^0.8.0; import "./IAccessControl.sol"; import "../utils/Context.sol"; import "../utils/Strings.sol"; import "../utils/introspection/ERC165.sol"; /** * @dev Contract module that allows children to implement role-based access * control mechanisms. This is a lightweight version that doesn't allow enumerating role * members except through off-chain means by accessing the contract event logs. Some * applications may benefit from on-chain enumerability, for those cases see * {AccessControlEnumerable}. * * Roles are referred to by their `bytes32` identifier. These should be exposed * in the external API and be unique. The best way to achieve this is by * using `public constant` hash digests: * * ``` * bytes32 public constant MY_ROLE = keccak256("MY_ROLE"); * ``` * * Roles can be used to represent a set of permissions. To restrict access to a * function call, use {hasRole}: * * ``` * function foo() public { * require(hasRole(MY_ROLE, msg.sender)); * ... * } * ``` * * Roles can be granted and revoked dynamically via the {grantRole} and * {revokeRole} functions. Each role has an associated admin role, and only * accounts that have a role's admin role can call {grantRole} and {revokeRole}. * * By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means * that only accounts with this role will be able to grant or revoke other * roles. More complex role relationships can be created by using * {_setRoleAdmin}. * * WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to * grant and revoke this role. Extra precautions should be taken to secure * accounts that have been granted it. */ abstract contract AccessControl is Context, IAccessControl, ERC165 { struct RoleData { mapping(address => bool) members; bytes32 adminRole; } mapping(bytes32 => RoleData) private _roles; bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00; /** * @dev Modifier that checks that an account has a specific role. Reverts * with a standardized message including the required role. * * The format of the revert reason is given by the following regular expression: * * /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/ * * _Available since v4.1._ */ modifier onlyRole(bytes32 role) { _checkRole(role, _msgSender()); _; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IAccessControl).interfaceId || super.supportsInterface(interfaceId); } /** * @dev Returns `true` if `account` has been granted `role`. */ function hasRole(bytes32 role, address account) public view virtual override returns (bool) { return _roles[role].members[account]; } /** * @dev Revert with a standard message if `account` is missing `role`. * * The format of the revert reason is given by the following regular expression: * * /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/ */ function _checkRole(bytes32 role, address account) internal view virtual { if (!hasRole(role, account)) { revert( string( abi.encodePacked( "AccessControl: account ", Strings.toHexString(uint160(account), 20), " is missing role ", Strings.toHexString(uint256(role), 32) ) ) ); } } /** * @dev Returns the admin role that controls `role`. See {grantRole} and * {revokeRole}. * * To change a role's admin, use {_setRoleAdmin}. */ function getRoleAdmin(bytes32 role) public view virtual override returns (bytes32) { return _roles[role].adminRole; } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function grantRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) { _grantRole(role, account); } /** * @dev Revokes `role` from `account`. * * If `account` had been granted `role`, emits a {RoleRevoked} event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function revokeRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) { _revokeRole(role, account); } /** * @dev Revokes `role` from the calling account. * * Roles are often managed via {grantRole} and {revokeRole}: this function's * purpose is to provide a mechanism for accounts to lose their privileges * if they are compromised (such as when a trusted device is misplaced). * * If the calling account had been revoked `role`, emits a {RoleRevoked} * event. * * Requirements: * * - the caller must be `account`. */ function renounceRole(bytes32 role, address account) public virtual override { require(account == _msgSender(), "AccessControl: can only renounce roles for self"); _revokeRole(role, account); } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. Note that unlike {grantRole}, this function doesn't perform any * checks on the calling account. * * [WARNING] * ==== * This function should only be called from the constructor when setting * up the initial roles for the system. * * Using this function in any other way is effectively circumventing the admin * system imposed by {AccessControl}. * ==== * * NOTE: This function is deprecated in favor of {_grantRole}. */ function _setupRole(bytes32 role, address account) internal virtual { _grantRole(role, account); } /** * @dev Sets `adminRole` as ``role``'s admin role. * * Emits a {RoleAdminChanged} event. */ function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual { bytes32 previousAdminRole = getRoleAdmin(role); _roles[role].adminRole = adminRole; emit RoleAdminChanged(role, previousAdminRole, adminRole); } /** * @dev Grants `role` to `account`. * * Internal function without access restriction. */ function _grantRole(bytes32 role, address account) internal virtual { if (!hasRole(role, account)) { _roles[role].members[account] = true; emit RoleGranted(role, account, _msgSender()); } } /** * @dev Revokes `role` from `account`. * * Internal function without access restriction. */ function _revokeRole(bytes32 role, address account) internal virtual { if (hasRole(role, account)) { _roles[role].members[account] = false; emit RoleRevoked(role, account, _msgSender()); } } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.5.0) (utils/cryptography/MerkleProof.sol) pragma solidity ^0.8.0; /** * @dev These functions deal with verification of Merkle Trees proofs. * * The proofs can be generated using the JavaScript library * https://github.com/miguelmota/merkletreejs[merkletreejs]. * Note: the hashing algorithm should be keccak256 and pair sorting should be enabled. * * See `test/utils/cryptography/MerkleProof.test.js` for some examples. */ library MerkleProof { /** * @dev Returns true if a `leaf` can be proved to be a part of a Merkle tree * defined by `root`. For this, a `proof` must be provided, containing * sibling hashes on the branch from the leaf to the root of the tree. Each * pair of leaves and each pair of pre-images are assumed to be sorted. */ function verify( bytes32[] memory proof, bytes32 root, bytes32 leaf ) internal pure returns (bool) { return processProof(proof, leaf) == root; } /** * @dev Returns the rebuilt hash obtained by traversing a Merklee tree up * from `leaf` using `proof`. A `proof` is valid if and only if the rebuilt * hash matches the root of the tree. When processing the proof, the pairs * of leafs & pre-images are assumed to be sorted. * * _Available since v4.4._ */ function processProof(bytes32[] memory proof, bytes32 leaf) internal pure returns (bytes32) { bytes32 computedHash = leaf; for (uint256 i = 0; i < proof.length; i++) { bytes32 proofElement = proof[i]; if (computedHash <= proofElement) { // Hash(current computed hash + current element of the proof) computedHash = _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) } } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.5.0) (utils/math/Math.sol) pragma solidity ^0.8.0; /** * @dev Standard math utilities missing in the Solidity language. */ library Math { /** * @dev Returns the largest of two numbers. */ function max(uint256 a, uint256 b) internal pure returns (uint256) { return a >= b ? a : b; } /** * @dev Returns the smallest of two numbers. */ function min(uint256 a, uint256 b) internal pure returns (uint256) { return a < b ? a : b; } /** * @dev Returns the average of two numbers. The result is rounded towards * zero. */ function average(uint256 a, uint256 b) internal pure returns (uint256) { // (a + b) / 2 can overflow. return (a & b) + (a ^ b) / 2; } /** * @dev Returns the ceiling of the division of two numbers. * * This differs from standard division with `/` in that it rounds up instead * of rounding down. */ function ceilDiv(uint256 a, uint256 b) internal pure returns (uint256) { // (a + b - 1) / b can overflow on addition, so we distribute. return a / b + (a % b == 0 ? 0 : 1); } } // SPDX-License-Identifier: Unlicensed pragma solidity 0.8.13; import "@openzeppelin/contracts/access/AccessControl.sol"; import "@openzeppelin/contracts/security/ReentrancyGuard.sol"; import "../interfaces/IStoryversePlot.sol"; contract SaleCommon is AccessControl, ReentrancyGuard { bytes32 public constant MINTER_ROLE = keccak256("MINTER_ROLE"); address public plot; /// @notice Emitted when a new sale is added to the contract /// @param who Admin that created the sale /// @param saleId Sale ID, will be the current sale event SaleAdded(address who, uint256 saleId); /// @notice Emitted when the current sale is updated /// @param who Admin that updated the sale /// @param saleId Sale ID, will be the current sale event SaleUpdated(address who, uint256 saleId); /// @notice Emitted when new tokens are sold and minted /// @param who Purchaser (payer) for the tokens /// @param to Owner of the newly minted tokens /// @param quantity Quantity of tokens minted /// @param amount Amount paid in Wei event Minted(address who, address to, uint256 quantity, uint256 amount); /// @notice Emitted when funds are withdrawn from the contract /// @param to Recipient of the funds /// @param amount Amount sent in Wei event FundsWithdrawn(address to, uint256 amount); /// @notice Constructor /// @param _plot Storyverse Plot contract constructor(address _plot) { _grantRole(DEFAULT_ADMIN_ROLE, msg.sender); _grantRole(MINTER_ROLE, msg.sender); plot = _plot; } function checkTokenParameters( uint256 _volume, uint256 _presale, uint256 _tokenIndex ) internal pure { require(_volume > 0 && _volume < 2**10, "invalid volume"); require(_presale < 2**2, "invalid presale"); require(_tokenIndex < 2**32, "invalid token index"); } function buildTokenId( uint256 _volume, uint256 _presale, uint256 _tokenIndex ) public view returns (uint256 tokenId_) { checkTokenParameters(_volume, _presale, _tokenIndex); uint256 superSecretSpice = uint256( keccak256( abi.encodePacked( (0x4574c8c75d6e88acd28f7e467dac97b5c60c3838d9dad993900bdf402152228e ^ uint256(blockhash(block.number - 1))) + _tokenIndex ) ) ) & 0xffffffff; tokenId_ = (_volume << 245) | (_presale << 243) | (superSecretSpice << 211) | _tokenIndex; return tokenId_; } /// @notice Decode a token ID into its component parts /// @param _tokenId Token ID /// @return volume_ Volume of the sale /// @return presale_ Presale of the sale /// @return superSecretSpice_ Super secret spice /// @return tokenIndex_ Token index function decodeTokenId(uint256 _tokenId) external pure returns ( uint256 volume_, uint256 presale_, uint256 superSecretSpice_, uint256 tokenIndex_ ) { volume_ = (_tokenId >> 245) & 0x3ff; presale_ = (_tokenId >> 243) & 0x3; superSecretSpice_ = (_tokenId >> 211) & 0xffffffff; tokenIndex_ = _tokenId & 0xffffffff; return (volume_, presale_, superSecretSpice_, tokenIndex_); } /// @notice Withdraw funds from the contract /// @param _to Recipient of the funds /// @param _amount Amount sent, in Wei function withdrawFunds(address payable _to, uint256 _amount) external onlyRole(DEFAULT_ADMIN_ROLE) nonReentrant { require(_amount <= address(this).balance, "not enough funds"); _to.transfer(_amount); emit FundsWithdrawn(_to, _amount); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (access/IAccessControl.sol) pragma solidity ^0.8.0; /** * @dev External interface of AccessControl declared to support ERC165 detection. */ interface IAccessControl { /** * @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole` * * `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite * {RoleAdminChanged} not being emitted signaling this. * * _Available since v3.1._ */ event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole); /** * @dev Emitted when `account` is granted `role`. * * `sender` is the account that originated the contract call, an admin role * bearer except when using {AccessControl-_setupRole}. */ event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Emitted when `account` is revoked `role`. * * `sender` is the account that originated the contract call: * - if using `revokeRole`, it is the admin role bearer * - if using `renounceRole`, it is the role bearer (i.e. `account`) */ event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Returns `true` if `account` has been granted `role`. */ function hasRole(bytes32 role, address account) external view returns (bool); /** * @dev Returns the admin role that controls `role`. See {grantRole} and * {revokeRole}. * * To change a role's admin, use {AccessControl-_setRoleAdmin}. */ function getRoleAdmin(bytes32 role) external view returns (bytes32); /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function grantRole(bytes32 role, address account) external; /** * @dev Revokes `role` from `account`. * * If `account` had been granted `role`, emits a {RoleRevoked} event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function revokeRole(bytes32 role, address account) external; /** * @dev Revokes `role` from the calling account. * * Roles are often managed via {grantRole} and {revokeRole}: this function's * purpose is to provide a mechanism for accounts to lose their privileges * if they are compromised (such as when a trusted device is misplaced). * * If the calling account had been granted `role`, emits a {RoleRevoked} * event. * * Requirements: * * - the caller must be `account`. */ function renounceRole(bytes32 role, address account) external; } // SPDX-License-Identifier: MIT // 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 (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 (security/ReentrancyGuard.sol) pragma solidity ^0.8.0; /** * @dev Contract module that helps prevent reentrant calls to a function. * * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier * available, which can be applied to functions to make sure there are no nested * (reentrant) calls to them. * * Note that because there is a single `nonReentrant` guard, functions marked as * `nonReentrant` may not call one another. This can be worked around by making * those functions `private`, and then adding `external` `nonReentrant` entry * points to them. * * TIP: If you would like to learn more about reentrancy and alternative ways * to protect against it, check out our blog post * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul]. */ abstract contract ReentrancyGuard { // Booleans are more expensive than uint256 or any type that takes up a full // word because each write operation emits an extra SLOAD to first read the // slot's contents, replace the bits taken up by the boolean, and then write // back. This is the compiler's defense against contract upgrades and // pointer aliasing, and it cannot be disabled. // The values being non-zero value makes deployment a bit more expensive, // but in exchange the refund on every call to nonReentrant will be lower in // amount. Since refunds are capped to a percentage of the total // transaction's gas, it is best to keep them low in cases like this one, to // increase the likelihood of the full refund coming into effect. uint256 private constant _NOT_ENTERED = 1; uint256 private constant _ENTERED = 2; uint256 private _status; constructor() { _status = _NOT_ENTERED; } /** * @dev Prevents a contract from calling itself, directly or indirectly. * Calling a `nonReentrant` function from another `nonReentrant` * function is not supported. It is possible to prevent this from happening * by making the `nonReentrant` function external, and making it call a * `private` function that does the actual work. */ modifier nonReentrant() { // On the first call to nonReentrant, _notEntered will be true require(_status != _ENTERED, "ReentrancyGuard: reentrant call"); // Any calls to nonReentrant after this point will fail _status = _ENTERED; _; // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) _status = _NOT_ENTERED; } } // SPDX-License-Identifier: Unlicensed pragma solidity ~0.8.13; import "@openzeppelin/contracts-upgradeable/interfaces/IERC2981Upgradeable.sol"; import "@openzeppelin/contracts-upgradeable/token/ERC721/extensions/IERC721MetadataUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/access/IAccessControlUpgradeable.sol"; import "@imtbl/imx-contracts/contracts/IMintable.sol"; import "./IExtensionManager.sol"; interface IStoryversePlot is IERC2981Upgradeable, IERC721MetadataUpgradeable, IAccessControlUpgradeable, IMintable { /// @notice Emitted when a new extension manager is set /// @param who Admin that set the extension manager /// @param extensionManager New extension manager contract event ExtensionManagerSet(address indexed who, address indexed extensionManager); /// @notice Emitted when a new Immutable X is set /// @param who Admin that set the extension manager /// @param imx New Immutable X address event IMXSet(address indexed who, address indexed imx); /// @notice Emitted when a new token is minted and a blueprint is set /// @param to Owner of the newly minted token /// @param tokenId Token ID that was minted /// @param blueprint Blueprint extracted from the blob event AssetMinted(address to, uint256 tokenId, bytes blueprint); /// @notice Emitted when the new base URI is set /// @param who Admin that set the base URI event BaseURISet(address indexed who); /// @notice Emitted when funds are withdrawn from the contract /// @param to Recipient of the funds /// @param amount Amount sent in Wei event FundsWithdrawn(address to, uint256 amount); /// @notice Get the base URI /// @return uri_ Base URI function baseURI() external returns (string memory uri_); /// @notice Get the extension manager /// @return extensionManager_ Extension manager function extensionManager() external returns (IExtensionManager extensionManager_); /// @notice Get the Immutable X address /// @return imx_ Immutable X address function imx() external returns (address imx_); /// @notice Get the blueprint for a token ID /// @param _tokenId Token ID /// @return blueprint_ Blueprint function blueprints(uint256 _tokenId) external returns (bytes memory blueprint_); /// @notice Sets a new extension manager /// @param _extensionManager New extension manager function setExtensionManager(address _extensionManager) external; /// @notice Mint a new token /// @param _to Owner of the newly minted token /// @param _tokenId Token ID function safeMint(address _to, uint256 _tokenId) external; /// @notice Sets a base URI /// @param _uri Base URI function setBaseURI(string calldata _uri) external; /// @notice Get PLOT data for the token ID /// @param _tokenId Token ID /// @param _in Input data /// @return out_ Output data function getPLOTData(uint256 _tokenId, bytes memory _in) external returns (bytes memory out_); /// @notice Sets PLOT data for the token ID /// @param _tokenId Token ID /// @param _in Input data /// @return out_ Output data function setPLOTData(uint256 _tokenId, bytes memory _in) external returns (bytes memory out_); /// @notice Pays for PLOT data of the token ID /// @param _tokenId Token ID /// @param _in Input data /// @return out_ Output data function payPLOTData(uint256 _tokenId, bytes memory _in) external payable returns (bytes memory out_); /// @notice Get data /// @param _in Input data /// @return out_ Output data function getData(bytes memory _in) external returns (bytes memory out_); /// @notice Sets data /// @param _in Input data /// @return out_ Output data function setData(bytes memory _in) external returns (bytes memory out_); /// @notice Pays for data /// @param _in Input data /// @return out_ Output data function payData(bytes memory _in) external payable returns (bytes memory out_); /// @notice Transfers the ownership of the contract /// @param newOwner New owner of the contract function transferOwnership(address newOwner) external; /// @notice Sets the Immutable X address /// @param _imx New Immutable X function setIMX(address _imx) external; /// @notice Withdraw funds from the contract /// @param _to Recipient of the funds /// @param _amount Amount sent, in Wei function withdrawFunds(address payable _to, uint256 _amount) external; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.5.0) (interfaces/IERC2981.sol) pragma solidity ^0.8.0; import "../utils/introspection/IERC165Upgradeable.sol"; /** * @dev Interface for the NFT Royalty Standard. * * A standardized way to retrieve royalty payment information for non-fungible tokens (NFTs) to enable universal * support for royalty payments across all NFT marketplaces and ecosystem participants. * * _Available since v4.5._ */ interface IERC2981Upgradeable is IERC165Upgradeable { /** * @dev Returns how much royalty is owed and to whom, based on a sale price that may be denominated in any unit of * exchange. The royalty amount is denominated and should be payed in that same unit of exchange. */ function royaltyInfo(uint256 tokenId, uint256 salePrice) external view returns (address receiver, uint256 royaltyAmount); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/IERC721Metadata.sol) pragma solidity ^0.8.0; import "../IERC721Upgradeable.sol"; /** * @title ERC-721 Non-Fungible Token Standard, optional metadata extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721MetadataUpgradeable is IERC721Upgradeable { /** * @dev Returns the token collection name. */ function name() external view returns (string memory); /** * @dev Returns the token collection symbol. */ function symbol() external view returns (string memory); /** * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token. */ function tokenURI(uint256 tokenId) external view returns (string memory); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (access/IAccessControl.sol) pragma solidity ^0.8.0; /** * @dev External interface of AccessControl declared to support ERC165 detection. */ interface IAccessControlUpgradeable { /** * @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole` * * `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite * {RoleAdminChanged} not being emitted signaling this. * * _Available since v3.1._ */ event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole); /** * @dev Emitted when `account` is granted `role`. * * `sender` is the account that originated the contract call, an admin role * bearer except when using {AccessControl-_setupRole}. */ event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Emitted when `account` is revoked `role`. * * `sender` is the account that originated the contract call: * - if using `revokeRole`, it is the admin role bearer * - if using `renounceRole`, it is the role bearer (i.e. `account`) */ event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Returns `true` if `account` has been granted `role`. */ function hasRole(bytes32 role, address account) external view returns (bool); /** * @dev Returns the admin role that controls `role`. See {grantRole} and * {revokeRole}. * * To change a role's admin, use {AccessControl-_setRoleAdmin}. */ function getRoleAdmin(bytes32 role) external view returns (bytes32); /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function grantRole(bytes32 role, address account) external; /** * @dev Revokes `role` from `account`. * * If `account` had been granted `role`, emits a {RoleRevoked} event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function revokeRole(bytes32 role, address account) external; /** * @dev Revokes `role` from the calling account. * * Roles are often managed via {grantRole} and {revokeRole}: this function's * purpose is to provide a mechanism for accounts to lose their privileges * if they are compromised (such as when a trusted device is misplaced). * * If the calling account had been granted `role`, emits a {RoleRevoked} * event. * * Requirements: * * - the caller must be `account`. */ function renounceRole(bytes32 role, address account) external; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.4; interface IMintable { function mintFor( address to, uint256 quantity, bytes calldata mintingBlob ) external; } // SPDX-License-Identifier: Unlicensed pragma solidity ~0.8.13; interface IExtensionManager { function beforeTokenTransfer( address _from, address _to, uint256 _tokenId ) external; function afterTokenTransfer( address _from, address _to, uint256 _tokenId ) external; function beforeTokenApprove(address _to, uint256 _tokenId) external; function afterTokenApprove(address _to, uint256 _tokenId) external; function beforeApproveAll(address _operator, bool _approved) external; function afterApproveAll(address _operator, bool _approved) external; function tokenURI(uint256 _tokenId) external view returns (string memory uri_); function royaltyInfo(uint256 _tokenId, uint256 _salePrice) external view returns (address royaltyReceiver_, uint256 royaltyAmount_); function getPLOTData(uint256 _tokenId, bytes memory _in) external view returns (bytes memory out_); function setPLOTData(uint256 _tokenId, bytes memory _in) external returns (bytes memory out_); function payPLOTData(uint256 _tokenId, bytes memory _in) external payable returns (bytes memory out_); function getData(bytes memory _in) external view returns (bytes memory out_); function setData(bytes memory _in) external returns (bytes memory out_); function payData(bytes memory _in) external payable returns (bytes memory out_); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol) pragma solidity ^0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165Upgradeable { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721.sol) pragma solidity ^0.8.0; import "../../utils/introspection/IERC165Upgradeable.sol"; /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721Upgradeable is IERC165Upgradeable { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes calldata data ) external; }
Updates the start token index of the current sale _startTokenIndex Token index to start the sale from
function updateSaleStartTokenIndex(uint256 _startTokenIndex) external onlyRole(DEFAULT_ADMIN_ROLE) { uint256 saleId = currentSaleId(); _checkSafeTokenIdRange(_startTokenIndex, sales[saleId].maxPLOTs, saleId); checkTokenParameters(sales[saleId].volume, sales[saleId].presale, _startTokenIndex); sales[saleId].startTokenIndex = _startTokenIndex; emit SaleUpdated(msg.sender, saleId); }
541,912
pragma solidity ^0.4.18; // ---------------------------------------------------------------------------- // Safe maths // ---------------------------------------------------------------------------- library _SafeMath { function add(uint a, uint b) internal pure returns (uint c) { c = a + b; require(c >= a); } function sub(uint a, uint b) internal pure returns (uint c) { require(b <= a); c = a - b; } function mul(uint a, uint b) internal pure returns (uint c) { c = a * b; require(a == 0 || c / a == b); } function div(uint a, uint b) internal pure returns (uint c) { require(b > 0); c = a / b; } } // ---------------------------------------------------------------------------- // contract WhiteListAccess // ---------------------------------------------------------------------------- contract WhiteListAccess { function WhiteListAccess() public { owner = msg.sender; whitelist[owner] = true; whitelist[address(this)] = true; } address public owner; mapping (address => bool) whitelist; modifier onlyOwner {require(msg.sender == owner); _;} modifier onlyWhitelisted {require(whitelist[msg.sender]); _;} function addToWhiteList(address trusted) public onlyOwner() { whitelist[trusted] = true; } function removeFromWhiteList(address untrusted) public onlyOwner() { whitelist[untrusted] = false; } } // ---------------------------------------------------------------------------- // ERC Token Standard #20 Interface // https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md // ---------------------------------------------------------------------------- contract _ERC20Interface { function totalSupply() public constant returns (uint); function balanceOf(address tokenOwner) public constant returns (uint balance); function allowance(address tokenOwner, address spender) public constant returns (uint remaining); function transfer(address to, uint tokens) public returns (bool success); function approve(address spender, uint tokens) public returns (bool success); function transferFrom(address from, address to, uint tokens) public returns (bool success); event Transfer(address indexed from, address indexed to, uint tokens); event Approval(address indexed tokenOwner, address indexed spender, uint tokens); } // ---------------------------------------------------------------------------- // ERC20 Token, with the addition of symbol, name and decimals and an // initial fixed supply of 0 units. // The units will be created by demand using the create function reservated for trusted contract's address // ---------------------------------------------------------------------------- contract _Token is WhiteListAccess, _ERC20Interface { using _SafeMath for uint; uint8 public decimals; uint public totSupply; string public symbol; string public name; mapping(address => uint) public balances; mapping(address => mapping(address => uint)) public allowed; // ------------------------------------------------------------------------ // Constructor // ------------------------------------------------------------------------ function _Token(string _name, string _sym) public { symbol = _sym; name = _name; decimals = 0; totSupply = 0; } // ------------------------------------------------------------------------ // Total supply // ------------------------------------------------------------------------ function totalSupply() public constant returns (uint) { return totSupply; } // ------------------------------------------------------------------------ // Get the _token balance for account `_tokenOwner` // ------------------------------------------------------------------------ function balanceOf(address _tokenOwner) public constant returns (uint balance) { return balances[_tokenOwner]; } // ------------------------------------------------------------------------ // Transfer the balance from token owner's account to `to` account // - Owner's account must have sufficient balance to transfer // - 0 value transfers are allowed // ------------------------------------------------------------------------ function transfer(address to, uint tokens) public returns (bool success) { require(!freezed); balances[msg.sender] = balances[msg.sender].sub(tokens); balances[to] = balances[to].add(tokens); Transfer(msg.sender, to, tokens); return true; } // ------------------------------------------------------------------------ // Token owner can approve for `spender` to transferFrom(...) `tokens` // from the token owner's account // // https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md // recommends that there are no checks for the approval double-spend attack // as this should be implemented in user interfaces // ------------------------------------------------------------------------ function approve(address spender, uint tokens) public returns (bool success) { allowed[msg.sender][spender] = tokens; Approval(msg.sender, spender, tokens); return true; } function desapprove(address spender) public returns (bool success) { allowed[msg.sender][spender] = 0; return true; } // ------------------------------------------------------------------------ // Transfer `tokens` from the `from` account to the `to` account // // The calling account must already have sufficient tokens approve(...)-d // for spending from the `from` account and // - From account must have sufficient balance to transfer // - Spender must have sufficient allowance to transfer // - 0 value transfers are allowed // ------------------------------------------------------------------------ function transferFrom(address from, address to, uint tokens) public returns (bool success) { require(!freezed); balances[from] = balances[from].sub(tokens); allowed[from][msg.sender] = allowed[from][msg.sender].sub(tokens); balances[to] = balances[to].add(tokens); Transfer(from, to, tokens); return true; } // ------------------------------------------------------------------------ // Returns the amount of tokens approved by the owner that can be // transferred to the spender's account // ------------------------------------------------------------------------ function allowance(address tokenOwner, address spender) public constant returns (uint remaining) { return allowed[tokenOwner][spender]; } // ------------------------------------------------------------------------ // Don't accept ETH // ------------------------------------------------------------------------ function () public payable { revert(); } // ------------------------------------------------------------------------ // FLC API // ------------------------------------------------------------------------ bool freezed; function create(uint units) public onlyWhitelisted() { totSupply = totSupply + units; balances[msg.sender] = balances[msg.sender] + units; } function freeze() public onlyWhitelisted() { freezed = true; } function unfreeze() public onlyWhitelisted() { freezed = false; } // recover tokens sent accidentally function _withdrawal(address _token) public { uint _balance = _ERC20Interface(_token).balanceOf(address(this)); if (_balance > 0) { _ERC20Interface(_token).transfer(owner, _balance); } owner.transfer(this.balance); } } contract FourLeafClover is _Token("Four Leaf Clover", "FLC") { function FourLeafClover() public {} }
recover tokens sent accidentally
function _withdrawal(address _token) public { uint _balance = _ERC20Interface(_token).balanceOf(address(this)); if (_balance > 0) { _ERC20Interface(_token).transfer(owner, _balance); } owner.transfer(this.balance); }
6,090,677
// 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 "../../../solidity-utils/contracts/helpers/WordCodec.sol"; import "../BasePoolAuthorization.sol"; import "../interfaces/IBasePoolController.sol"; import "../interfaces/IControlledPool.sol"; /** * @dev Pool controller that serves as the owner of a Balancer pool, and is in turn owned by * an account empowered to make calls on this contract, which are forwarded to the underlyling pool. * * While the owner of the underlying Balancer pool is immutable, ownership of this pool controller * can be transferred, if the corresponding permission is set to allow this operation. To prevent * accidentally setting the manager to an invalid address (and irrevocably losing control of the pool), * transferring ownership is a two-step process. * * If the changeSwapFee permission is enabled, the manager can call setSwapFeePercentage, or delegate * this right to a different address. */ contract BasePoolController is IBasePoolController { using WordCodec for bytes32; // There are three basic pool rights: one for transferring ownership, one for changing the swap fee, // and the last for associating arbitrary metadata with the pool. The remaining BasePool privileged // function (setAssetManagerPoolConfig) has no associated permission. It doesn't make sense to // restrict that, as a fixed configuration would prevent rebalancing and potentially lead to loss // of funds. struct BasePoolRights { bool canTransferOwnership; bool canChangeSwapFee; bool canUpdateMetadata; } // The address empowered to call permissioned functions. address private _manager; // Target of a proposed transfer of ownership. Will be non-zero if there is a transfer pending. // This address must call claimOwnership to complete the transfer. address private _managerCandidate; // Address allowed to call `setSwapFeePercentage`. Initially set to the owner (or 0 if fees are fixed) address private _swapFeeController; // Address of the underlying pool. address public pool; // Immutable controller state - the first 16 bits are reserved as a bitmap for permission flags // (3 used in this base class), and the remaining 240 bits can be used by derived classes to store // any other immutable data. // // [ | 16 bits for permission flags ] // [ 240 bits | 13 bits | 1 bit | 1 bit | 1 bit ] // [ unused | reserved | metadata | swap fee | transfer ] // |MSB LSB| bytes32 internal immutable _controllerState; uint256 private constant _TRANSFER_OWNERSHIP_OFFSET = 0; uint256 private constant _CHANGE_SWAP_FEE_OFFSET = 1; uint256 private constant _UPDATE_METADATA_OFFSET = 2; // Optional metadata associated with this controller (or the pool bound to it) bytes private _metadata; // Event declarations event OwnershipTransferred(address indexed previousManager, address indexed newManager); event SwapFeeControllerChanged(address indexed oldSwapFeeController, address indexed newSwapFeeController); event MetadataUpdated(bytes metadata); // Modifiers // Add this modifier to all functions that call the underlying pool. modifier withBoundPool { _ensurePoolIsBound(); _; } /** * @dev Reverts if called by any account other than the manager. */ modifier onlyManager() { _require(getManager() == msg.sender, Errors.CALLER_IS_NOT_OWNER); _; } /** * @dev Set permissions and the initial manager for the pool controller. We are "trusting" the manager to be * a valid address on deployment, as does BasePool. Transferring ownership to a new manager after deployment * employs a safe, two-step process. */ constructor(bytes32 controllerState, address manager) { _controllerState = controllerState; _manager = manager; // If the swap fee is not fixed, it can be delegated (initially, to the manager). if (controllerState.decodeBool(_CHANGE_SWAP_FEE_OFFSET)) { _swapFeeController = manager; } } /** * @dev Encode the BaseController portion of the controllerState. This is mainly useful for * derived classes to call during construction. */ function encodePermissions(BasePoolRights memory rights) public pure returns (bytes32) { bytes32 permissions; return permissions .insertBool(rights.canTransferOwnership, _TRANSFER_OWNERSHIP_OFFSET) .insertBool(rights.canChangeSwapFee, _CHANGE_SWAP_FEE_OFFSET) .insertBool(rights.canUpdateMetadata, _UPDATE_METADATA_OFFSET); } /** * @dev Getter for the current manager. */ function getManager() public view returns (address) { return _manager; } /** * @dev Returns the manager candidate, which will be non-zero if there is a pending ownership transfer. */ function getManagerCandidate() external view returns (address) { return _managerCandidate; } /** * @dev Getter for the current swap fee controller (0 if fees are fixed). */ function getSwapFeeController() public view returns (address) { return _swapFeeController; } /** * @dev Getter for the transferOwnership permission. */ function canTransferOwnership() public view returns (bool) { return _controllerState.decodeBool(_TRANSFER_OWNERSHIP_OFFSET); } /** * @dev Getter for the canChangeSwapFee permission. */ function canChangeSwapFee() public view returns (bool) { return _controllerState.decodeBool(_CHANGE_SWAP_FEE_OFFSET); } /** * @dev Getter for the canUpdateMetadata permission. */ function canUpdateMetadata() public view returns (bool) { return _controllerState.decodeBool(_UPDATE_METADATA_OFFSET); } /** * @dev The underlying pool owner is immutable, so its address must be known when the pool is deployed. * This means the controller needs to be deployed first. Yet the controller also needs to know the address * of the pool it is controlling. * * We could either pass in a pool factory and have the controller deploy the pool, or have an initialize * function to set the pool address after deployment. This decoupled mechanism seems cleaner. * * It means the pool address must be in storage vs immutable, but this is acceptable for infrequent admin * operations. */ function initialize(address poolAddress) external virtual override { // This can only be called once - and the owner of the pool must be this contract _require( pool == address(0) && BasePoolAuthorization(poolAddress).getOwner() == address(this), Errors.INVALID_INITIALIZATION ); pool = poolAddress; } /** * @dev Stores the proposed new manager in `_managerCandidate`. To prevent accidental transfer to an invalid * address, the candidate address must call `claimOwnership` to complete the transfer. * * Can only be called by the current manager. */ function transferOwnership(address newManager) external onlyManager { _require(canTransferOwnership(), Errors.UNAUTHORIZED_OPERATION); _managerCandidate = newManager; } /** * @dev This must be called by the manager candidate to complete the transferwnership operation. * This "claimable" mechanism prevents accidental transfer of ownership to an invalid address. * * To keep this function simple and focused, transferring ownership does not affect the swapFeeController. * Sometimes the new owner might want to retain the "old" swap fee controller (e.g., if it was * delegated to Gauntlet). Other times an owner may want to take control of fees from the previous * owner. In the latter case, the new owner should call `setSwapFeeController`. */ function claimOwnership() external { address candidate = _managerCandidate; _require(candidate == msg.sender, Errors.SENDER_NOT_ALLOWED); emit OwnershipTransferred(_manager, candidate); _manager = candidate; // Setting the candidate to zero prevents calling this repeatedly and generating multiple redundant events, // and also allows checking (perhaps by a UI) whether there is a pending transfer. _managerCandidate = address(0); } /** * @dev Change the address allowed to call setSwapFeePercentage. */ function setSwapFeeController(address newSwapFeeController) external onlyManager { emit SwapFeeControllerChanged(getSwapFeeController(), newSwapFeeController); _swapFeeController = newSwapFeeController; } /** * @dev Pass a call to BasePool's setSwapFeePercentage through to the underlying pool, if allowed. */ function setSwapFeePercentage(uint256 swapFeePercentage) external virtual override withBoundPool { _require(canChangeSwapFee(), Errors.UNAUTHORIZED_OPERATION); _require(getSwapFeeController() == msg.sender, Errors.SENDER_NOT_ALLOWED); IControlledPool(pool).setSwapFeePercentage(swapFeePercentage); } /** * @dev Pass a call to BasePool's setAssetManagerPoolConfig through to the underlying pool. This does not * need to be permissioned: any pool with asset managers must allow the owner to configure them. */ function setAssetManagerPoolConfig(IERC20 token, bytes memory poolConfig) external virtual override onlyManager withBoundPool { IControlledPool(pool).setAssetManagerPoolConfig(token, poolConfig); } /** * @dev Getter for the optional metadata. */ function getMetadata() public view returns (bytes memory) { return _metadata; } /** * @dev Setter for the admin to set/update the metadata */ function updateMetadata(bytes memory metadata) external onlyManager { _require(canUpdateMetadata(), Errors.UNAUTHORIZED_OPERATION); _metadata = metadata; emit MetadataUpdated(metadata); } function _ensurePoolIsBound() private view { _require(pool != address(0), Errors.UNINITIALIZED_POOL_CONTROLLER); } }
Getter for the optional metadata./
function getMetadata() public view returns (bytes memory) { return _metadata; }
12,760,426
pragma solidity ^0.4.11; /* * 'LOOK' token sale contract * * Refer to https://lookscoin.com/ for more information. * * Developer: LookRev * */ /* * ERC20 Token Standard */ contract ERC20 { function totalSupply() constant returns (uint256 supply); function balanceOf(address _who) constant returns (uint256 balance); function transfer(address _to, uint256 _value) returns (bool ok); function transferFrom(address _from, address _to, uint256 _value) returns (bool ok); function approve(address _spender, uint256 _value) returns (bool ok); function allowance(address _owner, address _spender) constant returns (uint256 remaining); event Transfer(address indexed _from, address indexed _to, uint256 _value); event Approval(address indexed _owner, address indexed _spender, uint256 _value); } /** * Provides methods to safely add, subtract and multiply uint256 numbers. */ contract SafeMath { uint256 constant private MAX_UINT256 = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF; /** * Add two uint256 values, revert in case of overflow. * * @param a first value to add * @param b second value to add * @return a + b */ function safeAdd(uint256 a, uint256 b) internal returns (uint256) { require (a <= MAX_UINT256 - b); uint256 c = a + b; assert(c >= a); return c; } /** * Subtract one uint256 value from another, throw in case of underflow. * * @param a value to subtract from * @param b value to subtract * @return a - b */ function safeSub(uint256 a, uint256 b) internal returns (uint256) { assert(a >= b); return a - b; } /** * Multiply two uint256 values, throw in case of overflow. * * @param a first value to multiply * @param b second value to multiply * @return a * b */ function safeMul(uint256 a, uint256 b) internal returns (uint256) { if (a == 0 || b == 0) return 0; require (a <= MAX_UINT256 / b); return a * b; } } /* Provides support and utilities for contract ownership */ contract Ownable { address owner; address newOwner; function Ownable() { owner = msg.sender; } /** * Allows execution by the owner only. */ modifier onlyOwner { require(msg.sender == owner); _; } /** * Transferring the contract ownership to the new owner. * * @param _newOwner new contractor owner */ function transferOwnership(address _newOwner) onlyOwner { if (_newOwner != address(0)) { newOwner = _newOwner; } } /** * Accept the contract ownership by the new owner. * */ function acceptOwnership() { require(msg.sender == newOwner); OwnershipTransferred(owner, newOwner); owner = newOwner; newOwner = 0x0; } event OwnershipTransferred(address indexed _from, address indexed _to); } /** * Standard Token Smart Contract that could be used as a base contract for * ERC-20 token contracts. */ contract StandardToken is ERC20, Ownable, SafeMath { /** * Mapping from addresses of token holders to the numbers of tokens belonging * to these token holders. */ mapping (address => uint256) balances; /** * Mapping from addresses of token holders to the mapping of addresses of * spenders to the allowances set by these token holders to these spenders. */ mapping (address => mapping (address => uint256)) allowed; /** * Create new Standard Token contract. */ function StandardToken() { // Do nothing } /** * 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) constant returns (uint256 balance) { return balances[_owner]; } /** * Transfer given number of tokens from message sender to given recipient. * * @param _to address to transfer tokens to the owner of * @param _amount 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 _amount) returns (bool success) { // avoid wasting gas on 0 token transfers if(_amount <= 0) return false; if (msg.sender == _to) return false; if (balances[msg.sender] < _amount) return false; if (balances[_to] + _amount > balances[_to]) { balances[msg.sender] = safeSub(balances[msg.sender],_amount); balances[_to] = safeAdd(balances[_to],_amount); Transfer(msg.sender, _to, _amount); return true; } return false; } /** * 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 _amount 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 _amount) returns (bool success) { // avoid wasting gas on 0 token transfers if(_amount <= 0) return false; if(_from == _to) return false; if (balances[_from] < _amount) return false; if (_amount > allowed[_from][msg.sender]) return false; balances[_from] = safeSub(balances[_from],_amount); allowed[_from][msg.sender] = safeSub(allowed[_from][msg.sender],_amount); balances[_to] = safeAdd(balances[_to],_amount); Transfer(_from, _to, _amount); return false; } /** * 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 _amount number of tokens to allow to transfer * @return true if token transfer was successfully approved, false otherwise */ function approve(address _spender, uint256 _amount) returns (bool success) { // To change the approve amount you first have to reduce the addresses` // allowance to zero by calling `approve(_spender, 0)` if it is not // already 0 to mitigate the race condition described here: // https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 if ((_amount != 0) && (allowed[msg.sender][_spender] != 0)) { return false; } if (balances[msg.sender] < _amount) { return false; } allowed[msg.sender][_spender] = _amount; Approval(msg.sender, _spender, _amount); return true; } /** * 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) constant returns (uint256 remaining) { return allowed[_owner][_spender]; } } /** * LOOK Token Sale Contract * * The token sale controller, allows contributing ether in exchange for LOOK coins. * The price (exchange rate with ETH) remains fixed for the entire duration of the token sale. * VIP ranking is recorded at the time when the token holding address first meet VIP holding level. * VIP ranking is valid for the lifetime of a token wallet address, as long as it meets VIP holding level. * VIP ranking is used to calculate priority when competing with other bids for the * same product or service on the platform. * Higher VIP ranking (with earlier timestamp) has higher priority. * Higher VIP ranking address can outbid other lower ranking addresses once per selling window or promotion period. * Usage of the LOOK token, VIP ranking and bid priority will be described on token website. * */ contract LooksCoin is StandardToken { /** * Address of the owner of this smart contract. */ address wallet = 0x0; /** * Mapping for VIP rank for qualified token holders * Higher VIP ranking (with earlier timestamp) has higher bidding priority when competing * for the same item on platform. * Higher VIP ranking address can outbid other lower ranking addresses once per selling window or promotion period. * Usage of the VIP ranking and bid priority will be described on token website. */ mapping (address => uint256) viprank; /** * Minimium contribution to record a VIP block * Token holding address needs at least 10 ETH worth of LOOK tokens to be ranked as VIP */ uint256 public VIP_MINIMUM = 1000000; /** * Initial number of tokens. */ uint256 constant INITIAL_TOKENS_COUNT = 20000000000; /** * Total number of tokens ins circulation. */ uint256 tokensCount; // initial price in wei (numerator) uint256 public constant TOKEN_PRICE_N = 1e13; // initial price in wei (denominator) uint256 public constant TOKEN_PRICE_D = 1; // 1 ETH = 100000 LOOK coins /** * Create new LOOK token Smart Contract, make message sender to be the * owner of smart contract, issue given number of tokens and give them to * message sender. */ function LooksCoin() payable { owner = msg.sender; wallet = msg.sender; tokensCount = INITIAL_TOKENS_COUNT; balances[owner] = tokensCount; } /** * Get name of this token. * * @return name of this token */ function name() constant returns (string name) { return "LOOK"; } /** * Get symbol of this token. * * @return symbol of this token */ function symbol() constant returns (string symbol) { return "LOOK"; } /** * Get number of decimals for this token. * * @return number of decimals for this token */ function decimals() constant returns (uint8 decimals) { return 0; } /** * Get total number of tokens in circulation. * * @return total number of tokens in circulation */ function totalSupply() constant returns (uint256 supply) { return tokensCount; } /** * Set new wallet address for the smart contract. * May only be called by smart contract owner. * * @param _wallet new wallet address of the smart contract */ function setWallet(address _wallet) onlyOwner { wallet = _wallet; WalletUpdated(wallet); } event WalletUpdated(address newWallet); /** * Get VIP rank of a given owner. * VIP ranking is valid for the lifetime of a token wallet address, as long as it meets VIP holding level. * * @param participant address to get the vip rank * @return vip rank of the owner of given address */ function getVIPRank(address participant) constant returns (uint256 rank) { if (balances[participant] < VIP_MINIMUM) { return 0; } return viprank[participant]; } // fallback function() payable { buyToken(); } /** * Accept ethers and other currencies to buy tokens during the token sale */ function buyToken() public payable returns (uint256 amount) { // Calculate number of tokens for contributed ETH uint256 tokens = safeMul(msg.value, TOKEN_PRICE_D) / TOKEN_PRICE_N; // Add tokens purchased to account's balance and total supply balances[msg.sender] = safeAdd(balances[msg.sender],tokens); tokensCount = safeAdd(tokensCount,tokens); // Log the tokens purchased Transfer(0x0, msg.sender, tokens); // - buyer = participant // - ethers = msg.value // - participantTokenBalance = balances[participant] // - tokens = tokens // - totalTokensCount = tokensCount TokensBought(msg.sender, msg.value, balances[msg.sender], tokens, tokensCount); // Contribution timestamp is recorded for VIP rank // Recorded timestamp for VIP ranking should always be earlier than the current time if (balances[msg.sender] >= VIP_MINIMUM && viprank[msg.sender] == 0) { viprank[msg.sender] = now; } // Transfer the contributed ethers to the crowdsale wallet assert(wallet.send(msg.value)); return tokens; } event TokensBought(address indexed buyer, uint256 ethers, uint256 participantTokenBalance, uint256 tokens, uint256 totalTokensCount); /** * Transfer given number of tokens from message sender to given recipient. * * @param _to address to transfer tokens to the owner of * @param _amount 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 _amount) returns (bool success) { return StandardToken.transfer(_to, _amount); } /** * 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 _amount 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 _amount) returns (bool success) { return StandardToken.transferFrom(_from, _to, _amount); } /** * Burn given number of tokens belonging to message sender. * * @param _amount number of tokens to burn * @return true on success, false on error */ function burnTokens(uint256 _amount) returns (bool success) { if (_amount <= 0) return false; if (_amount > tokensCount) return false; if (_amount > balances[msg.sender]) return false; balances[msg.sender] = safeSub(balances[msg.sender],_amount); tokensCount = safeSub(tokensCount,_amount); Transfer(msg.sender, 0x0, _amount); return true; } }
Add two uint256 values, revert in case of overflow. a first value to add b second value to add return a + b/
function safeAdd(uint256 a, uint256 b) internal returns (uint256) { require (a <= MAX_UINT256 - b); uint256 c = a + b; assert(c >= a); return c; }
15,809,673
/** *Submitted for verification at Etherscan.io on 2021-03-31 */ /** Copyright 2020 PoolTogether Inc. This file is part of PoolTogether. PoolTogether 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 under version 3 of the License. PoolTogether 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 PoolTogether. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.5.12; contract GemLike { function allowance(address, address) public returns (uint); function approve(address, uint) public; function transfer(address, uint) public returns (bool); function transferFrom(address, address, uint) public returns (bool); } contract ValueLike { function peek() public returns (uint, bool); } contract SaiTubLike { function skr() public view returns (GemLike); function gem() public view returns (GemLike); function gov() public view returns (GemLike); function sai() public view returns (GemLike); function pep() public view returns (ValueLike); function vox() public view returns (VoxLike); function bid(uint) public view returns (uint); function ink(bytes32) public view returns (uint); function tag() public view returns (uint); function tab(bytes32) public returns (uint); function rap(bytes32) public returns (uint); function draw(bytes32, uint) public; function shut(bytes32) public; function exit(uint) public; function give(bytes32, address) public; } contract VoxLike { function par() public returns (uint); } contract JoinLike { function ilk() public returns (bytes32); function gem() public returns (GemLike); function dai() public returns (GemLike); function join(address, uint) public; function exit(address, uint) public; } contract VatLike { function ilks(bytes32) public view returns (uint, uint, uint, uint, uint); function hope(address) public; function frob(bytes32, address, address, address, int, int) public; } contract ManagerLike { function vat() public view returns (address); function urns(uint) public view returns (address); function open(bytes32, address) public returns (uint); function frob(uint, int, int) public; function give(uint, address) public; function move(uint, address, uint) public; } contract OtcLike { function getPayAmount(address, address, uint) public view returns (uint); function buyAllAmount(address, uint, address, uint) public; } /** Copyright 2020 PoolTogether Inc. This file is part of PoolTogether. PoolTogether 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 under version 3 of the License. PoolTogether 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 PoolTogether. If not, see <https://www.gnu.org/licenses/>. */ /** Copyright 2020 PoolTogether Inc. This file is part of PoolTogether. PoolTogether 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 under version 3 of the License. PoolTogether 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 PoolTogether. If not, see <https://www.gnu.org/licenses/>. */ /** * @dev Interface of the global ERC1820 Registry, as defined in the * https://eips.ethereum.org/EIPS/eip-1820[EIP]. Accounts may register * implementers for interfaces in this registry, as well as query support. * * Implementers may be shared by multiple accounts, and can also implement more * than a single interface for each account. Contracts can implement interfaces * for themselves, but externally-owned accounts (EOA) must delegate this to a * contract. * * {IERC165} interfaces can also be queried via the registry. * * For an in-depth explanation and source code analysis, see the EIP text. */ interface IERC1820Registry { /** * @dev Sets `newManager` as the manager for `account`. A manager of an * account is able to set interface implementers for it. * * By default, each account is its own manager. Passing a value of `0x0` in * `newManager` will reset the manager to this initial state. * * Emits a {ManagerChanged} event. * * Requirements: * * - the caller must be the current manager for `account`. */ function setManager(address account, address newManager) external; /** * @dev Returns the manager for `account`. * * See {setManager}. */ function getManager(address account) external view returns (address); /** * @dev Sets the `implementer` contract as `account`'s implementer for * `interfaceHash`. * * `account` being the zero address is an alias for the caller's address. * The zero address can also be used in `implementer` to remove an old one. * * See {interfaceHash} to learn how these are created. * * Emits an {InterfaceImplementerSet} event. * * Requirements: * * - the caller must be the current manager for `account`. * - `interfaceHash` must not be an {IERC165} interface id (i.e. it must not * end in 28 zeroes). * - `implementer` must implement {IERC1820Implementer} and return true when * queried for support, unless `implementer` is the caller. See * {IERC1820Implementer-canImplementInterfaceForAddress}. */ function setInterfaceImplementer(address account, bytes32 interfaceHash, address implementer) external; /** * @dev Returns the implementer of `interfaceHash` for `account`. If no such * implementer is registered, returns the zero address. * * If `interfaceHash` is an {IERC165} interface id (i.e. it ends with 28 * zeroes), `account` will be queried for support of it. * * `account` being the zero address is an alias for the caller's address. */ function getInterfaceImplementer(address account, bytes32 interfaceHash) external view returns (address); /** * @dev Returns the interface hash for an `interfaceName`, as defined in the * corresponding * https://eips.ethereum.org/EIPS/eip-1820#interface-name[section of the EIP]. */ function interfaceHash(string calldata interfaceName) external pure returns (bytes32); /** * @notice Updates the cache with whether the contract implements an ERC165 interface or not. * @param account Address of the contract for which to update the cache. * @param interfaceId ERC165 interface for which to update the cache. */ function updateERC165Cache(address account, bytes4 interfaceId) external; /** * @notice Checks whether a contract implements an ERC165 interface or not. * If the result is not cached a direct lookup on the contract address is performed. * If the result is not cached or the cached value is out-of-date, the cache MUST be updated manually by calling * {updateERC165Cache} with the contract address. * @param account Address of the contract to check. * @param interfaceId ERC165 interface to check. * @return True if `account` implements `interfaceId`, false otherwise. */ function implementsERC165Interface(address account, bytes4 interfaceId) external view returns (bool); /** * @notice Checks whether a contract implements an ERC165 interface or not without using nor updating the cache. * @param account Address of the contract to check. * @param interfaceId ERC165 interface to check. * @return True if `account` implements `interfaceId`, false otherwise. */ function implementsERC165InterfaceNoCache(address account, bytes4 interfaceId) external view returns (bool); event InterfaceImplementerSet(address indexed account, bytes32 indexed interfaceHash, address indexed implementer); event ManagerChanged(address indexed account, address indexed newManager); } /** * @dev Interface of the ERC20 standard as defined in the EIP. Does not include * the optional functions; to access them see {ERC20Detailed}. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. * * _Available since v2.4.0._ */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. * * _Available since v2.4.0._ */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { // Solidity only automatically asserts when dividing by 0 require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. * * _Available since v2.4.0._ */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } /** * @title 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. uint256 cs; assembly { cs := extcodesize(address) } return cs == 0; } // Reserved storage space to allow for layout changes in the future. uint256[50] private ______gap; } /** * @dev Contract module that helps prevent reentrant calls to a function. * * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier * available, which can be applied to functions to make sure there are no nested * (reentrant) calls to them. * * Note that because there is a single `nonReentrant` guard, functions marked as * `nonReentrant` may not call one another. This can be worked around by making * those functions `private`, and then adding `external` `nonReentrant` entry * points to them. */ contract ReentrancyGuard is Initializable { // counter to allow mutex lock with only one SSTORE operation uint256 private _guardCounter; function initialize() public initializer { // The counter starts at one to prevent changing it from zero to a non-zero // value, which is a more expensive operation. _guardCounter = 1; } /** * @dev Prevents a contract from calling itself, directly or indirectly. * Calling a `nonReentrant` function from another `nonReentrant` * function is not supported. It is possible to prevent this from happening * by making the `nonReentrant` function external, and make it call a * `private` function that does the actual work. */ modifier nonReentrant() { _guardCounter += 1; uint256 localCounter = _guardCounter; _; require(localCounter == _guardCounter, "ReentrancyGuard: reentrant call"); } uint256[50] private ______gap; } /** * @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]; } } /** Copyright 2020 PoolTogether Inc. This file is part of PoolTogether. PoolTogether 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 under version 3 of the License. PoolTogether 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 PoolTogether. If not, see <https://www.gnu.org/licenses/>. */ contract ICErc20 { address public underlying; function mint(uint256 mintAmount) external returns (uint); function redeemUnderlying(uint256 redeemAmount) external returns (uint); function balanceOfUnderlying(address owner) external returns (uint); function getCash() external view returns (uint); function supplyRatePerBlock() external view returns (uint); } /** Copyright 2020 PoolTogether Inc. This file is part of PoolTogether. PoolTogether 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 under version 3 of the License. PoolTogether 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 PoolTogether. If not, see <https://www.gnu.org/licenses/>. */ /** Copyright 2020 PoolTogether Inc. This file is part of PoolTogether. PoolTogether 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 under version 3 of the License. PoolTogether 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 PoolTogether. If not, see <https://www.gnu.org/licenses/>. */ /** * @author Brendan Asselstine * @notice A library that uses entropy to select a random number within a bound. Compensates for modulo bias. * @dev Thanks to https://medium.com/hownetworks/dont-waste-cycles-with-modulo-bias-35b6fdafcf94 */ library UniformRandomNumber { /// @notice Select a random number without modulo bias using a random seed and upper bound /// @param _entropy The seed for randomness /// @param _upperBound The upper bound of the desired number /// @return A random number less than the _upperBound function uniform(uint256 _entropy, uint256 _upperBound) internal pure returns (uint256) { require(_upperBound > 0, "UniformRand/min-bound"); uint256 min = -_upperBound % _upperBound; uint256 random = _entropy; while (true) { if (random >= min) { break; } random = uint256(keccak256(abi.encodePacked(random))); } return random % _upperBound; } } /** * @reviewers: [@clesaege, @unknownunknown1, @ferittuncer] * @auditors: [] * @bounties: [<14 days 10 ETH max payout>] * @deployments: [] */ /** * @title SortitionSumTreeFactory * @author Enrique Piqueras - <[email protected]> * @dev A factory of trees that keep track of staked values for sortition. */ library SortitionSumTreeFactory { /* Structs */ struct SortitionSumTree { uint K; // The maximum number of childs per node. // We use this to keep track of vacant positions in the tree after removing a leaf. This is for keeping the tree as balanced as possible without spending gas on moving nodes around. uint[] stack; uint[] nodes; // Two-way mapping of IDs to node indexes. Note that node index 0 is reserved for the root node, and means the ID does not have a node. mapping(bytes32 => uint) IDsToNodeIndexes; mapping(uint => bytes32) nodeIndexesToIDs; } /* Storage */ struct SortitionSumTrees { mapping(bytes32 => SortitionSumTree) sortitionSumTrees; } /* internal */ /** * @dev Create a sortition sum tree at the specified key. * @param _key The key of the new tree. * @param _K The number of children each node in the tree should have. */ function createTree(SortitionSumTrees storage self, bytes32 _key, uint _K) internal { SortitionSumTree storage tree = self.sortitionSumTrees[_key]; require(tree.K == 0, "Tree already exists."); require(_K > 1, "K must be greater than one."); tree.K = _K; tree.stack.length = 0; tree.nodes.length = 0; tree.nodes.push(0); } /** * @dev Set a value of a tree. * @param _key The key of the tree. * @param _value The new value. * @param _ID The ID of the value. * `O(log_k(n))` where * `k` is the maximum number of childs per node in the tree, * and `n` is the maximum number of nodes ever appended. */ function set(SortitionSumTrees storage self, bytes32 _key, uint _value, bytes32 _ID) internal { SortitionSumTree storage tree = self.sortitionSumTrees[_key]; uint treeIndex = tree.IDsToNodeIndexes[_ID]; if (treeIndex == 0) { // No existing node. if (_value != 0) { // Non zero value. // Append. // Add node. if (tree.stack.length == 0) { // No vacant spots. // Get the index and append the value. treeIndex = tree.nodes.length; tree.nodes.push(_value); // Potentially append a new node and make the parent a sum node. if (treeIndex != 1 && (treeIndex - 1) % tree.K == 0) { // Is first child. uint parentIndex = treeIndex / tree.K; bytes32 parentID = tree.nodeIndexesToIDs[parentIndex]; uint newIndex = treeIndex + 1; tree.nodes.push(tree.nodes[parentIndex]); delete tree.nodeIndexesToIDs[parentIndex]; tree.IDsToNodeIndexes[parentID] = newIndex; tree.nodeIndexesToIDs[newIndex] = parentID; } } else { // Some vacant spot. // Pop the stack and append the value. treeIndex = tree.stack[tree.stack.length - 1]; tree.stack.length--; tree.nodes[treeIndex] = _value; } // Add label. tree.IDsToNodeIndexes[_ID] = treeIndex; tree.nodeIndexesToIDs[treeIndex] = _ID; updateParents(self, _key, treeIndex, true, _value); } } else { // Existing node. if (_value == 0) { // Zero value. // Remove. // Remember value and set to 0. uint value = tree.nodes[treeIndex]; tree.nodes[treeIndex] = 0; // Push to stack. tree.stack.push(treeIndex); // Clear label. delete tree.IDsToNodeIndexes[_ID]; delete tree.nodeIndexesToIDs[treeIndex]; updateParents(self, _key, treeIndex, false, value); } else if (_value != tree.nodes[treeIndex]) { // New, non zero value. // Set. bool plusOrMinus = tree.nodes[treeIndex] <= _value; uint plusOrMinusValue = plusOrMinus ? _value - tree.nodes[treeIndex] : tree.nodes[treeIndex] - _value; tree.nodes[treeIndex] = _value; updateParents(self, _key, treeIndex, plusOrMinus, plusOrMinusValue); } } } /* internal Views */ /** * @dev Query the leaves of a tree. Note that if `startIndex == 0`, the tree is empty and the root node will be returned. * @param _key The key of the tree to get the leaves from. * @param _cursor The pagination cursor. * @param _count The number of items to return. * @return The index at which leaves start, the values of the returned leaves, and whether there are more for pagination. * `O(n)` where * `n` is the maximum number of nodes ever appended. */ function queryLeafs( SortitionSumTrees storage self, bytes32 _key, uint _cursor, uint _count ) internal view returns(uint startIndex, uint[] memory values, bool hasMore) { SortitionSumTree storage tree = self.sortitionSumTrees[_key]; // Find the start index. for (uint i = 0; i < tree.nodes.length; i++) { if ((tree.K * i) + 1 >= tree.nodes.length) { startIndex = i; break; } } // Get the values. uint loopStartIndex = startIndex + _cursor; values = new uint[](loopStartIndex + _count > tree.nodes.length ? tree.nodes.length - loopStartIndex : _count); uint valuesIndex = 0; for (uint j = loopStartIndex; j < tree.nodes.length; j++) { if (valuesIndex < _count) { values[valuesIndex] = tree.nodes[j]; valuesIndex++; } else { hasMore = true; break; } } } /** * @dev Draw an ID from a tree using a number. Note that this function reverts if the sum of all values in the tree is 0. * @param _key The key of the tree. * @param _drawnNumber The drawn number. * @return The drawn ID. * `O(k * log_k(n))` where * `k` is the maximum number of childs per node in the tree, * and `n` is the maximum number of nodes ever appended. */ function draw(SortitionSumTrees storage self, bytes32 _key, uint _drawnNumber) internal view returns(bytes32 ID) { SortitionSumTree storage tree = self.sortitionSumTrees[_key]; uint treeIndex = 0; uint currentDrawnNumber = _drawnNumber % tree.nodes[0]; while ((tree.K * treeIndex) + 1 < tree.nodes.length) // While it still has children. for (uint i = 1; i <= tree.K; i++) { // Loop over children. uint nodeIndex = (tree.K * treeIndex) + i; uint nodeValue = tree.nodes[nodeIndex]; if (currentDrawnNumber >= nodeValue) currentDrawnNumber -= nodeValue; // Go to the next child. else { // Pick this child. treeIndex = nodeIndex; break; } } ID = tree.nodeIndexesToIDs[treeIndex]; } /** @dev Gets a specified ID's associated value. * @param _key The key of the tree. * @param _ID The ID of the value. * @return The associated value. */ function stakeOf(SortitionSumTrees storage self, bytes32 _key, bytes32 _ID) internal view returns(uint value) { SortitionSumTree storage tree = self.sortitionSumTrees[_key]; uint treeIndex = tree.IDsToNodeIndexes[_ID]; if (treeIndex == 0) value = 0; else value = tree.nodes[treeIndex]; } function total(SortitionSumTrees storage self, bytes32 _key) internal view returns (uint) { SortitionSumTree storage tree = self.sortitionSumTrees[_key]; if (tree.nodes.length == 0) { return 0; } else { return tree.nodes[0]; } } /* Private */ /** * @dev Update all the parents of a node. * @param _key The key of the tree to update. * @param _treeIndex The index of the node to start from. * @param _plusOrMinus Wether to add (true) or substract (false). * @param _value The value to add or substract. * `O(log_k(n))` where * `k` is the maximum number of childs per node in the tree, * and `n` is the maximum number of nodes ever appended. */ function updateParents(SortitionSumTrees storage self, bytes32 _key, uint _treeIndex, bool _plusOrMinus, uint _value) private { SortitionSumTree storage tree = self.sortitionSumTrees[_key]; uint parentIndex = _treeIndex; while (parentIndex != 0) { parentIndex = (parentIndex - 1) / tree.K; tree.nodes[parentIndex] = _plusOrMinus ? tree.nodes[parentIndex] + _value : tree.nodes[parentIndex] - _value; } } } /** * @author Brendan Asselstine * @notice Tracks committed and open balances for addresses. Affords selection of an address by indexing all committed balances. * * Balances are tracked in Draws. There is always one open Draw. Deposits are always added to the open Draw. * When a new draw is opened, the previous opened draw is committed. * * The committed balance for an address is the total of their balances for committed Draws. * An address's open balance is their balance in the open Draw. */ library DrawManager { using SortitionSumTreeFactory for SortitionSumTreeFactory.SortitionSumTrees; using SafeMath for uint256; /** * The ID to use for the selection tree. */ bytes32 public constant TREE_OF_DRAWS = "TreeOfDraws"; uint8 public constant MAX_BRANCHES_PER_NODE = 10; /** * Stores information for all draws. */ struct State { /** * Each Draw stores it's address balances in a sortitionSumTree. Draw trees are indexed using the Draw index. * There is one root sortitionSumTree that stores all of the draw totals. The root tree is indexed using the constant TREE_OF_DRAWS. */ SortitionSumTreeFactory.SortitionSumTrees sortitionSumTrees; /** * Stores the consolidated draw index that an address deposited to. */ mapping(address => uint256) consolidatedDrawIndices; /** * Stores the last Draw index that an address deposited to. */ mapping(address => uint256) latestDrawIndices; /** * Stores a mapping of Draw index => Draw total */ mapping(uint256 => uint256) __deprecated__drawTotals; /** * The current open Draw index */ uint256 openDrawIndex; /** * The total of committed balances */ uint256 __deprecated__committedSupply; } /** * @notice Opens the next Draw and commits the previous open Draw (if any). * @param self The drawState this library is attached to * @return The index of the new open Draw */ function openNextDraw(State storage self) public returns (uint256) { if (self.openDrawIndex == 0) { // If there is no previous draw, we must initialize self.sortitionSumTrees.createTree(TREE_OF_DRAWS, MAX_BRANCHES_PER_NODE); } else { // else add current draw to sortition sum trees bytes32 drawId = bytes32(self.openDrawIndex); uint256 drawTotal = openSupply(self); self.sortitionSumTrees.set(TREE_OF_DRAWS, drawTotal, drawId); } // now create a new draw uint256 drawIndex = self.openDrawIndex.add(1); self.sortitionSumTrees.createTree(bytes32(drawIndex), MAX_BRANCHES_PER_NODE); self.openDrawIndex = drawIndex; return drawIndex; } /** * @notice Deposits the given amount into the current open draw by the given user. * @param self The DrawManager state * @param _addr The address to deposit for * @param _amount The amount to deposit */ function deposit(State storage self, address _addr, uint256 _amount) public requireOpenDraw(self) onlyNonZero(_addr) { bytes32 userId = bytes32(uint256(_addr)); uint256 openDrawIndex = self.openDrawIndex; // update the current draw uint256 currentAmount = self.sortitionSumTrees.stakeOf(bytes32(openDrawIndex), userId); currentAmount = currentAmount.add(_amount); drawSet(self, openDrawIndex, currentAmount, _addr); uint256 consolidatedDrawIndex = self.consolidatedDrawIndices[_addr]; uint256 latestDrawIndex = self.latestDrawIndices[_addr]; // if this is the user's first draw, set it if (consolidatedDrawIndex == 0) { self.consolidatedDrawIndices[_addr] = openDrawIndex; // otherwise, if the consolidated draw is not this draw } else if (consolidatedDrawIndex != openDrawIndex) { // if a second draw does not exist if (latestDrawIndex == 0) { // set the second draw to the current draw self.latestDrawIndices[_addr] = openDrawIndex; // otherwise if a second draw exists but is not the current one } else if (latestDrawIndex != openDrawIndex) { // merge it into the first draw, and update the second draw index to this one uint256 consolidatedAmount = self.sortitionSumTrees.stakeOf(bytes32(consolidatedDrawIndex), userId); uint256 latestAmount = self.sortitionSumTrees.stakeOf(bytes32(latestDrawIndex), userId); drawSet(self, consolidatedDrawIndex, consolidatedAmount.add(latestAmount), _addr); drawSet(self, latestDrawIndex, 0, _addr); self.latestDrawIndices[_addr] = openDrawIndex; } } } /** * @notice Deposits into a user's committed balance, thereby bypassing the open draw. * @param self The DrawManager state * @param _addr The address of the user for whom to deposit * @param _amount The amount to deposit */ function depositCommitted(State storage self, address _addr, uint256 _amount) public requireCommittedDraw(self) onlyNonZero(_addr) { bytes32 userId = bytes32(uint256(_addr)); uint256 consolidatedDrawIndex = self.consolidatedDrawIndices[_addr]; // if they have a committed balance if (consolidatedDrawIndex != 0 && consolidatedDrawIndex != self.openDrawIndex) { uint256 consolidatedAmount = self.sortitionSumTrees.stakeOf(bytes32(consolidatedDrawIndex), userId); drawSet(self, consolidatedDrawIndex, consolidatedAmount.add(_amount), _addr); } else { // they must not have any committed balance self.latestDrawIndices[_addr] = consolidatedDrawIndex; self.consolidatedDrawIndices[_addr] = self.openDrawIndex.sub(1); drawSet(self, self.consolidatedDrawIndices[_addr], _amount, _addr); } } /** * @notice Withdraws a user's committed and open draws. * @param self The DrawManager state * @param _addr The address whose balance to withdraw */ function withdraw(State storage self, address _addr) public requireOpenDraw(self) onlyNonZero(_addr) { uint256 consolidatedDrawIndex = self.consolidatedDrawIndices[_addr]; uint256 latestDrawIndex = self.latestDrawIndices[_addr]; if (consolidatedDrawIndex != 0) { drawSet(self, consolidatedDrawIndex, 0, _addr); delete self.consolidatedDrawIndices[_addr]; } if (latestDrawIndex != 0) { drawSet(self, latestDrawIndex, 0, _addr); delete self.latestDrawIndices[_addr]; } } /** * @notice Withdraw's from a user's open balance * @param self The DrawManager state * @param _addr The user to withdrawn from * @param _amount The amount to withdraw */ function withdrawOpen(State storage self, address _addr, uint256 _amount) public requireOpenDraw(self) onlyNonZero(_addr) { bytes32 userId = bytes32(uint256(_addr)); uint256 openTotal = self.sortitionSumTrees.stakeOf(bytes32(self.openDrawIndex), userId); require(_amount <= openTotal, "DrawMan/exceeds-open"); uint256 remaining = openTotal.sub(_amount); drawSet(self, self.openDrawIndex, remaining, _addr); } /** * @notice Withdraw's from a user's committed balance. Fails if the user attempts to take more than available. * @param self The DrawManager state * @param _addr The user to withdraw from * @param _amount The amount to withdraw. */ function withdrawCommitted(State storage self, address _addr, uint256 _amount) public requireCommittedDraw(self) onlyNonZero(_addr) { bytes32 userId = bytes32(uint256(_addr)); uint256 consolidatedDrawIndex = self.consolidatedDrawIndices[_addr]; uint256 latestDrawIndex = self.latestDrawIndices[_addr]; uint256 consolidatedAmount = 0; uint256 latestAmount = 0; uint256 total = 0; if (latestDrawIndex != 0 && latestDrawIndex != self.openDrawIndex) { latestAmount = self.sortitionSumTrees.stakeOf(bytes32(latestDrawIndex), userId); total = total.add(latestAmount); } if (consolidatedDrawIndex != 0 && consolidatedDrawIndex != self.openDrawIndex) { consolidatedAmount = self.sortitionSumTrees.stakeOf(bytes32(consolidatedDrawIndex), userId); total = total.add(consolidatedAmount); } // If the total is greater than zero, then consolidated *must* have the committed balance // However, if the total is zero then the consolidated balance may be the open balance if (total == 0) { return; } require(_amount <= total, "Pool/exceed"); uint256 remaining = total.sub(_amount); // if there was a second amount that needs to be updated if (remaining > consolidatedAmount) { uint256 secondRemaining = remaining.sub(consolidatedAmount); drawSet(self, latestDrawIndex, secondRemaining, _addr); } else if (latestAmount > 0) { // else delete the second amount if it exists delete self.latestDrawIndices[_addr]; drawSet(self, latestDrawIndex, 0, _addr); } // if the consolidated amount needs to be destroyed if (remaining == 0) { delete self.consolidatedDrawIndices[_addr]; drawSet(self, consolidatedDrawIndex, 0, _addr); } else if (remaining < consolidatedAmount) { drawSet(self, consolidatedDrawIndex, remaining, _addr); } } /** * @notice Returns the total balance for an address, including committed balances and the open balance. */ function balanceOf(State storage drawState, address _addr) public view returns (uint256) { return committedBalanceOf(drawState, _addr).add(openBalanceOf(drawState, _addr)); } /** * @notice Returns the total committed balance for an address. * @param self The DrawManager state * @param _addr The address whose committed balance should be returned * @return The total committed balance */ function committedBalanceOf(State storage self, address _addr) public view returns (uint256) { uint256 balance = 0; uint256 consolidatedDrawIndex = self.consolidatedDrawIndices[_addr]; uint256 latestDrawIndex = self.latestDrawIndices[_addr]; if (consolidatedDrawIndex != 0 && consolidatedDrawIndex != self.openDrawIndex) { balance = self.sortitionSumTrees.stakeOf(bytes32(consolidatedDrawIndex), bytes32(uint256(_addr))); } if (latestDrawIndex != 0 && latestDrawIndex != self.openDrawIndex) { balance = balance.add(self.sortitionSumTrees.stakeOf(bytes32(latestDrawIndex), bytes32(uint256(_addr)))); } return balance; } /** * @notice Returns the open balance for an address * @param self The DrawManager state * @param _addr The address whose open balance should be returned * @return The open balance */ function openBalanceOf(State storage self, address _addr) public view returns (uint256) { if (self.openDrawIndex == 0) { return 0; } else { return self.sortitionSumTrees.stakeOf(bytes32(self.openDrawIndex), bytes32(uint256(_addr))); } } /** * @notice Returns the open Draw balance for the DrawManager * @param self The DrawManager state * @return The open draw total balance */ function openSupply(State storage self) public view returns (uint256) { return self.sortitionSumTrees.total(bytes32(self.openDrawIndex)); } /** * @notice Returns the committed balance for the DrawManager * @param self The DrawManager state * @return The total committed balance */ function committedSupply(State storage self) public view returns (uint256) { return self.sortitionSumTrees.total(TREE_OF_DRAWS); } /** * @notice Updates the Draw balance for an address. * @param self The DrawManager state * @param _drawIndex The Draw index * @param _amount The new balance * @param _addr The address whose balance should be updated */ function drawSet(State storage self, uint256 _drawIndex, uint256 _amount, address _addr) internal { bytes32 drawId = bytes32(_drawIndex); bytes32 userId = bytes32(uint256(_addr)); uint256 oldAmount = self.sortitionSumTrees.stakeOf(drawId, userId); if (oldAmount != _amount) { // If the amount has changed // Update the Draw's balance for that address self.sortitionSumTrees.set(drawId, _amount, userId); // if the draw is committed if (_drawIndex != self.openDrawIndex) { // Get the new draw total uint256 newDrawTotal = self.sortitionSumTrees.total(drawId); // update the draw in the committed tree self.sortitionSumTrees.set(TREE_OF_DRAWS, newDrawTotal, drawId); } } } /** * @notice Selects an address by indexing into the committed tokens using the passed token. * If there is no committed supply, the zero address is returned. * @param self The DrawManager state * @param _token The token index to select * @return The selected address */ function draw(State storage self, uint256 _token) public view returns (address) { // If there is no one to select, just return the zero address if (committedSupply(self) == 0) { return address(0); } require(_token < committedSupply(self), "Pool/ineligible"); bytes32 drawIndex = self.sortitionSumTrees.draw(TREE_OF_DRAWS, _token); uint256 drawSupply = self.sortitionSumTrees.total(drawIndex); uint256 drawToken = _token % drawSupply; return address(uint256(self.sortitionSumTrees.draw(drawIndex, drawToken))); } /** * @notice Selects an address using the entropy as an index into the committed tokens * The entropy is passed into the UniformRandomNumber library to remove modulo bias. * @param self The DrawManager state * @param _entropy The random entropy to use * @return The selected address */ function drawWithEntropy(State storage self, bytes32 _entropy) public view returns (address) { uint256 bound = committedSupply(self); address selected; if (bound == 0) { selected = address(0); } else { selected = draw(self, UniformRandomNumber.uniform(uint256(_entropy), bound)); } return selected; } modifier requireOpenDraw(State storage self) { require(self.openDrawIndex > 0, "Pool/no-open"); _; } modifier requireCommittedDraw(State storage self) { require(self.openDrawIndex > 1, "Pool/no-commit"); _; } modifier onlyNonZero(address _addr) { require(_addr != address(0), "Pool/not-zero"); _; } } /** * @title FixidityLib * @author Gadi Guy, Alberto Cuesta Canada * @notice This library provides fixed point arithmetic with protection against * overflow. * All operations are done with int256 and the operands must have been created * with any of the newFrom* functions, which shift the comma digits() to the * right and check for limits. * When using this library be sure of using maxNewFixed() as the upper limit for * creation of fixed point numbers. Use maxFixedMul(), maxFixedDiv() and * maxFixedAdd() if you want to be certain that those operations don't * overflow. */ library FixidityLib { /** * @notice Number of positions that the comma is shifted to the right. */ function digits() public pure returns(uint8) { return 24; } /** * @notice This is 1 in the fixed point units used in this library. * @dev Test fixed1() equals 10^digits() * Hardcoded to 24 digits. */ function fixed1() public pure returns(int256) { return 1000000000000000000000000; } /** * @notice The amount of decimals lost on each multiplication operand. * @dev Test mulPrecision() equals sqrt(fixed1) * Hardcoded to 24 digits. */ function mulPrecision() public pure returns(int256) { return 1000000000000; } /** * @notice Maximum value that can be represented in an int256 * @dev Test maxInt256() equals 2^255 -1 */ function maxInt256() public pure returns(int256) { return 57896044618658097711785492504343953926634992332820282019728792003956564819967; } /** * @notice Minimum value that can be represented in an int256 * @dev Test minInt256 equals (2^255) * (-1) */ function minInt256() public pure returns(int256) { return -57896044618658097711785492504343953926634992332820282019728792003956564819968; } /** * @notice Maximum value that can be converted to fixed point. Optimize for * @dev deployment. * Test maxNewFixed() equals maxInt256() / fixed1() * Hardcoded to 24 digits. */ function maxNewFixed() public pure returns(int256) { return 57896044618658097711785492504343953926634992332820282; } /** * @notice Minimum value that can be converted to fixed point. Optimize for * deployment. * @dev Test minNewFixed() equals -(maxInt256()) / fixed1() * Hardcoded to 24 digits. */ function minNewFixed() public pure returns(int256) { return -57896044618658097711785492504343953926634992332820282; } /** * @notice Maximum value that can be safely used as an addition operator. * @dev Test maxFixedAdd() equals maxInt256()-1 / 2 * Test add(maxFixedAdd(),maxFixedAdd()) equals maxFixedAdd() + maxFixedAdd() * Test add(maxFixedAdd()+1,maxFixedAdd()) throws * Test add(-maxFixedAdd(),-maxFixedAdd()) equals -maxFixedAdd() - maxFixedAdd() * Test add(-maxFixedAdd(),-maxFixedAdd()-1) throws */ function maxFixedAdd() public pure returns(int256) { return 28948022309329048855892746252171976963317496166410141009864396001978282409983; } /** * @notice Maximum negative value that can be safely in a subtraction. * @dev Test maxFixedSub() equals minInt256() / 2 */ function maxFixedSub() public pure returns(int256) { return -28948022309329048855892746252171976963317496166410141009864396001978282409984; } /** * @notice Maximum value that can be safely used as a multiplication operator. * @dev Calculated as sqrt(maxInt256()*fixed1()). * Be careful with your sqrt() implementation. I couldn't find a calculator * that would give the exact square root of maxInt256*fixed1 so this number * is below the real number by no more than 3*10**28. It is safe to use as * a limit for your multiplications, although powers of two of numbers over * this value might still work. * Test multiply(maxFixedMul(),maxFixedMul()) equals maxFixedMul() * maxFixedMul() * Test multiply(maxFixedMul(),maxFixedMul()+1) throws * Test multiply(-maxFixedMul(),maxFixedMul()) equals -maxFixedMul() * maxFixedMul() * Test multiply(-maxFixedMul(),maxFixedMul()+1) throws * Hardcoded to 24 digits. */ function maxFixedMul() public pure returns(int256) { return 240615969168004498257251713877715648331380787511296; } /** * @notice Maximum value that can be safely used as a dividend. * @dev divide(maxFixedDiv,newFixedFraction(1,fixed1())) = maxInt256(). * Test maxFixedDiv() equals maxInt256()/fixed1() * Test divide(maxFixedDiv(),multiply(mulPrecision(),mulPrecision())) = maxFixedDiv()*(10^digits()) * Test divide(maxFixedDiv()+1,multiply(mulPrecision(),mulPrecision())) throws * Hardcoded to 24 digits. */ function maxFixedDiv() public pure returns(int256) { return 57896044618658097711785492504343953926634992332820282; } /** * @notice Maximum value that can be safely used as a divisor. * @dev Test maxFixedDivisor() equals fixed1()*fixed1() - Or 10**(digits()*2) * Test divide(10**(digits()*2 + 1),10**(digits()*2)) = returns 10*fixed1() * Test divide(10**(digits()*2 + 1),10**(digits()*2 + 1)) = throws * Hardcoded to 24 digits. */ function maxFixedDivisor() public pure returns(int256) { return 1000000000000000000000000000000000000000000000000; } /** * @notice Converts an int256 to fixed point units, equivalent to multiplying * by 10^digits(). * @dev Test newFixed(0) returns 0 * Test newFixed(1) returns fixed1() * Test newFixed(maxNewFixed()) returns maxNewFixed() * fixed1() * Test newFixed(maxNewFixed()+1) fails */ function newFixed(int256 x) public pure returns (int256) { require(x <= maxNewFixed()); require(x >= minNewFixed()); return x * fixed1(); } /** * @notice Converts an int256 in the fixed point representation of this * library to a non decimal. All decimal digits will be truncated. */ function fromFixed(int256 x) public pure returns (int256) { return x / fixed1(); } /** * @notice Converts an int256 which is already in some fixed point * representation to a different fixed precision representation. * Both the origin and destination precisions must be 38 or less digits. * Origin values with a precision higher than the destination precision * will be truncated accordingly. * @dev * Test convertFixed(1,0,0) returns 1; * Test convertFixed(1,1,1) returns 1; * Test convertFixed(1,1,0) returns 0; * Test convertFixed(1,0,1) returns 10; * Test convertFixed(10,1,0) returns 1; * Test convertFixed(10,0,1) returns 100; * Test convertFixed(100,1,0) returns 10; * Test convertFixed(100,0,1) returns 1000; * Test convertFixed(1000,2,0) returns 10; * Test convertFixed(1000,0,2) returns 100000; * Test convertFixed(1000,2,1) returns 100; * Test convertFixed(1000,1,2) returns 10000; * Test convertFixed(maxInt256,1,0) returns maxInt256/10; * Test convertFixed(maxInt256,0,1) throws * Test convertFixed(maxInt256,38,0) returns maxInt256/(10**38); * Test convertFixed(1,0,38) returns 10**38; * Test convertFixed(maxInt256,39,0) throws * Test convertFixed(1,0,39) throws */ function convertFixed(int256 x, uint8 _originDigits, uint8 _destinationDigits) public pure returns (int256) { require(_originDigits <= 38 && _destinationDigits <= 38); uint8 decimalDifference; if ( _originDigits > _destinationDigits ){ decimalDifference = _originDigits - _destinationDigits; return x/(uint128(10)**uint128(decimalDifference)); } else if ( _originDigits < _destinationDigits ){ decimalDifference = _destinationDigits - _originDigits; // Cast uint8 -> uint128 is safe // Exponentiation is safe: // _originDigits and _destinationDigits limited to 38 or less // decimalDifference = abs(_destinationDigits - _originDigits) // decimalDifference < 38 // 10**38 < 2**128-1 require(x <= maxInt256()/uint128(10)**uint128(decimalDifference)); require(x >= minInt256()/uint128(10)**uint128(decimalDifference)); return x*(uint128(10)**uint128(decimalDifference)); } // _originDigits == digits()) return x; } /** * @notice Converts an int256 which is already in some fixed point * representation to that of this library. The _originDigits parameter is the * precision of x. Values with a precision higher than FixidityLib.digits() * will be truncated accordingly. */ function newFixed(int256 x, uint8 _originDigits) public pure returns (int256) { return convertFixed(x, _originDigits, digits()); } /** * @notice Converts an int256 in the fixed point representation of this * library to a different representation. The _destinationDigits parameter is the * precision of the output x. Values with a precision below than * FixidityLib.digits() will be truncated accordingly. */ function fromFixed(int256 x, uint8 _destinationDigits) public pure returns (int256) { return convertFixed(x, digits(), _destinationDigits); } /** * @notice Converts two int256 representing a fraction to fixed point units, * equivalent to multiplying dividend and divisor by 10^digits(). * @dev * Test newFixedFraction(maxFixedDiv()+1,1) fails * Test newFixedFraction(1,maxFixedDiv()+1) fails * Test newFixedFraction(1,0) fails * Test newFixedFraction(0,1) returns 0 * Test newFixedFraction(1,1) returns fixed1() * Test newFixedFraction(maxFixedDiv(),1) returns maxFixedDiv()*fixed1() * Test newFixedFraction(1,fixed1()) returns 1 * Test newFixedFraction(1,fixed1()-1) returns 0 */ function newFixedFraction( int256 numerator, int256 denominator ) public pure returns (int256) { require(numerator <= maxNewFixed()); require(denominator <= maxNewFixed()); require(denominator != 0); int256 convertedNumerator = newFixed(numerator); int256 convertedDenominator = newFixed(denominator); return divide(convertedNumerator, convertedDenominator); } /** * @notice Returns the integer part of a fixed point number. * @dev * Test integer(0) returns 0 * Test integer(fixed1()) returns fixed1() * Test integer(newFixed(maxNewFixed())) returns maxNewFixed()*fixed1() * Test integer(-fixed1()) returns -fixed1() * Test integer(newFixed(-maxNewFixed())) returns -maxNewFixed()*fixed1() */ function integer(int256 x) public pure returns (int256) { return (x / fixed1()) * fixed1(); // Can't overflow } /** * @notice Returns the fractional part of a fixed point number. * In the case of a negative number the fractional is also negative. * @dev * Test fractional(0) returns 0 * Test fractional(fixed1()) returns 0 * Test fractional(fixed1()-1) returns 10^24-1 * Test fractional(-fixed1()) returns 0 * Test fractional(-fixed1()+1) returns -10^24-1 */ function fractional(int256 x) public pure returns (int256) { return x - (x / fixed1()) * fixed1(); // Can't overflow } /** * @notice Converts to positive if negative. * Due to int256 having one more negative number than positive numbers * abs(minInt256) reverts. * @dev * Test abs(0) returns 0 * Test abs(fixed1()) returns -fixed1() * Test abs(-fixed1()) returns fixed1() * Test abs(newFixed(maxNewFixed())) returns maxNewFixed()*fixed1() * Test abs(newFixed(minNewFixed())) returns -minNewFixed()*fixed1() */ function abs(int256 x) public pure returns (int256) { if (x >= 0) { return x; } else { int256 result = -x; assert (result > 0); return result; } } /** * @notice x+y. If any operator is higher than maxFixedAdd() it * might overflow. * In solidity maxInt256 + 1 = minInt256 and viceversa. * @dev * Test add(maxFixedAdd(),maxFixedAdd()) returns maxInt256()-1 * Test add(maxFixedAdd()+1,maxFixedAdd()+1) fails * Test add(-maxFixedSub(),-maxFixedSub()) returns minInt256() * Test add(-maxFixedSub()-1,-maxFixedSub()-1) fails * Test add(maxInt256(),maxInt256()) fails * Test add(minInt256(),minInt256()) fails */ function add(int256 x, int256 y) public pure returns (int256) { int256 z = x + y; if (x > 0 && y > 0) assert(z > x && z > y); if (x < 0 && y < 0) assert(z < x && z < y); return z; } /** * @notice x-y. You can use add(x,-y) instead. * @dev Tests covered by add(x,y) */ function subtract(int256 x, int256 y) public pure returns (int256) { return add(x,-y); } /** * @notice x*y. If any of the operators is higher than maxFixedMul() it * might overflow. * @dev * Test multiply(0,0) returns 0 * Test multiply(maxFixedMul(),0) returns 0 * Test multiply(0,maxFixedMul()) returns 0 * Test multiply(maxFixedMul(),fixed1()) returns maxFixedMul() * Test multiply(fixed1(),maxFixedMul()) returns maxFixedMul() * Test all combinations of (2,-2), (2, 2.5), (2, -2.5) and (0.5, -0.5) * Test multiply(fixed1()/mulPrecision(),fixed1()*mulPrecision()) * Test multiply(maxFixedMul()-1,maxFixedMul()) equals multiply(maxFixedMul(),maxFixedMul()-1) * Test multiply(maxFixedMul(),maxFixedMul()) returns maxInt256() // Probably not to the last digits * Test multiply(maxFixedMul()+1,maxFixedMul()) fails * Test multiply(maxFixedMul(),maxFixedMul()+1) fails */ function multiply(int256 x, int256 y) public pure returns (int256) { if (x == 0 || y == 0) return 0; if (y == fixed1()) return x; if (x == fixed1()) return y; // Separate into integer and fractional parts // x = x1 + x2, y = y1 + y2 int256 x1 = integer(x) / fixed1(); int256 x2 = fractional(x); int256 y1 = integer(y) / fixed1(); int256 y2 = fractional(y); // (x1 + x2) * (y1 + y2) = (x1 * y1) + (x1 * y2) + (x2 * y1) + (x2 * y2) int256 x1y1 = x1 * y1; if (x1 != 0) assert(x1y1 / x1 == y1); // Overflow x1y1 // x1y1 needs to be multiplied back by fixed1 // solium-disable-next-line mixedcase int256 fixed_x1y1 = x1y1 * fixed1(); if (x1y1 != 0) assert(fixed_x1y1 / x1y1 == fixed1()); // Overflow x1y1 * fixed1 x1y1 = fixed_x1y1; int256 x2y1 = x2 * y1; if (x2 != 0) assert(x2y1 / x2 == y1); // Overflow x2y1 int256 x1y2 = x1 * y2; if (x1 != 0) assert(x1y2 / x1 == y2); // Overflow x1y2 x2 = x2 / mulPrecision(); y2 = y2 / mulPrecision(); int256 x2y2 = x2 * y2; if (x2 != 0) assert(x2y2 / x2 == y2); // Overflow x2y2 // result = fixed1() * x1 * y1 + x1 * y2 + x2 * y1 + x2 * y2 / fixed1(); int256 result = x1y1; result = add(result, x2y1); // Add checks for overflow result = add(result, x1y2); // Add checks for overflow result = add(result, x2y2); // Add checks for overflow return result; } /** * @notice 1/x * @dev * Test reciprocal(0) fails * Test reciprocal(fixed1()) returns fixed1() * Test reciprocal(fixed1()*fixed1()) returns 1 // Testing how the fractional is truncated * Test reciprocal(2*fixed1()*fixed1()) returns 0 // Testing how the fractional is truncated */ function reciprocal(int256 x) public pure returns (int256) { require(x != 0); return (fixed1()*fixed1()) / x; // Can't overflow } /** * @notice x/y. If the dividend is higher than maxFixedDiv() it * might overflow. You can use multiply(x,reciprocal(y)) instead. * There is a loss of precision on division for the lower mulPrecision() decimals. * @dev * Test divide(fixed1(),0) fails * Test divide(maxFixedDiv(),1) = maxFixedDiv()*(10^digits()) * Test divide(maxFixedDiv()+1,1) throws * Test divide(maxFixedDiv(),maxFixedDiv()) returns fixed1() */ function divide(int256 x, int256 y) public pure returns (int256) { if (y == fixed1()) return x; require(y != 0); require(y <= maxFixedDivisor()); return multiply(x, reciprocal(y)); } } /** * @title Blocklock * @author Brendan Asselstine * @notice A time lock with a cooldown period. When locked, the contract will remain locked until it is unlocked manually * or the lock duration expires. After the contract is unlocked, it cannot be locked until the cooldown duration expires. */ library Blocklock { using SafeMath for uint256; struct State { uint256 lockedAt; uint256 unlockedAt; uint256 lockDuration; uint256 cooldownDuration; } /** * @notice Sets the duration of the lock. This how long the lock lasts before it expires and automatically unlocks. * @param self The Blocklock state * @param lockDuration The duration, in blocks, that the lock should last. */ function setLockDuration(State storage self, uint256 lockDuration) public { require(lockDuration > 0, "Blocklock/lock-min"); self.lockDuration = lockDuration; } /** * @notice Sets the cooldown duration in blocks. This is the number of blocks that must pass before being able to * lock again. The cooldown duration begins when the lock duration expires, or when it is unlocked manually. * @param self The Blocklock state * @param cooldownDuration The duration of the cooldown, in blocks. */ function setCooldownDuration(State storage self, uint256 cooldownDuration) public { require(cooldownDuration > 0, "Blocklock/cool-min"); self.cooldownDuration = cooldownDuration; } /** * @notice Returns whether the state is locked at the given block number. * @param self The Blocklock state * @param blockNumber The current block number. */ function isLocked(State storage self, uint256 blockNumber) public view returns (bool) { uint256 endAt = lockEndAt(self); return ( self.lockedAt != 0 && blockNumber >= self.lockedAt && blockNumber < endAt ); } /** * @notice Locks the state at the given block number. * @param self The Blocklock state * @param blockNumber The block number to use as the lock start time */ function lock(State storage self, uint256 blockNumber) public { require(canLock(self, blockNumber), "Blocklock/no-lock"); self.lockedAt = blockNumber; } /** * @notice Manually unlocks the lock. * @param self The Blocklock state * @param blockNumber The block number at which the lock is being unlocked. */ function unlock(State storage self, uint256 blockNumber) public { self.unlockedAt = blockNumber; } /** * @notice Returns whether the Blocklock can be locked at the given block number * @param self The Blocklock state * @param blockNumber The block number to check against * @return True if we can lock at the given block number, false otherwise. */ function canLock(State storage self, uint256 blockNumber) public view returns (bool) { uint256 endAt = lockEndAt(self); return ( self.lockedAt == 0 || blockNumber >= endAt.add(self.cooldownDuration) ); } function cooldownEndAt(State storage self) internal view returns (uint256) { return lockEndAt(self).add(self.cooldownDuration); } function lockEndAt(State storage self) internal view returns (uint256) { uint256 endAt = self.lockedAt.add(self.lockDuration); // if we unlocked early if (self.unlockedAt >= self.lockedAt && self.unlockedAt < endAt) { endAt = self.unlockedAt; } return endAt; } } /** Copyright 2020 PoolTogether Inc. This file is part of PoolTogether. PoolTogether 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 under version 3 of the License. PoolTogether 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 PoolTogether. If not, see <https://www.gnu.org/licenses/>. */ /** * @dev Interface of the ERC777Token standard as defined in the EIP. * * This contract uses the * https://eips.ethereum.org/EIPS/eip-1820[ERC1820 registry standard] to let * token holders and recipients react to token movements by using setting implementers * for the associated interfaces in said registry. See {IERC1820Registry} and * {ERC1820Implementer}. */ interface IERC777 { /** * @dev Returns the name of the token. */ function name() external view returns (string memory); /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() external view returns (string memory); /** * @dev Returns the smallest part of the token that is not divisible. This * means all token operations (creation, movement and destruction) must have * amounts that are a multiple of this number. * * For most token contracts, this value will equal 1. */ function granularity() external view returns (uint256); /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by an account (`owner`). */ function balanceOf(address owner) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * If send or receive hooks are registered for the caller and `recipient`, * the corresponding functions will be called with `data` and empty * `operatorData`. See {IERC777Sender} and {IERC777Recipient}. * * Emits a {Sent} event. * * Requirements * * - the caller must have at least `amount` tokens. * - `recipient` cannot be the zero address. * - if `recipient` is a contract, it must implement the {IERC777Recipient} * interface. */ function send(address recipient, uint256 amount, bytes calldata data) external; /** * @dev Destroys `amount` tokens from the caller's account, reducing the * total supply. * * If a send hook is registered for the caller, the corresponding function * will be called with `data` and empty `operatorData`. See {IERC777Sender}. * * Emits a {Burned} event. * * Requirements * * - the caller must have at least `amount` tokens. */ function burn(uint256 amount, bytes calldata data) external; /** * @dev Returns true if an account is an operator of `tokenHolder`. * Operators can send and burn tokens on behalf of their owners. All * accounts are their own operator. * * See {operatorSend} and {operatorBurn}. */ function isOperatorFor(address operator, address tokenHolder) external view returns (bool); /** * @dev Make an account an operator of the caller. * * See {isOperatorFor}. * * Emits an {AuthorizedOperator} event. * * Requirements * * - `operator` cannot be calling address. */ function authorizeOperator(address operator) external; /** * @dev Make an account an operator of the caller. * * See {isOperatorFor} and {defaultOperators}. * * Emits a {RevokedOperator} event. * * Requirements * * - `operator` cannot be calling address. */ function revokeOperator(address operator) external; /** * @dev Returns the list of default operators. These accounts are operators * for all token holders, even if {authorizeOperator} was never called on * them. * * This list is immutable, but individual holders may revoke these via * {revokeOperator}, in which case {isOperatorFor} will return false. */ function defaultOperators() external view returns (address[] memory); /** * @dev Moves `amount` tokens from `sender` to `recipient`. The caller must * be an operator of `sender`. * * If send or receive hooks are registered for `sender` and `recipient`, * the corresponding functions will be called with `data` and * `operatorData`. See {IERC777Sender} and {IERC777Recipient}. * * Emits a {Sent} event. * * Requirements * * - `sender` cannot be the zero address. * - `sender` must have at least `amount` tokens. * - the caller must be an operator for `sender`. * - `recipient` cannot be the zero address. * - if `recipient` is a contract, it must implement the {IERC777Recipient} * interface. */ function operatorSend( address sender, address recipient, uint256 amount, bytes calldata data, bytes calldata operatorData ) external; /** * @dev Destoys `amount` tokens from `account`, reducing the total supply. * The caller must be an operator of `account`. * * If a send hook is registered for `account`, the corresponding function * will be called with `data` and `operatorData`. See {IERC777Sender}. * * Emits a {Burned} event. * * Requirements * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. * - the caller must be an operator for `account`. */ function operatorBurn( address account, uint256 amount, bytes calldata data, bytes calldata operatorData ) external; event Sent( address indexed operator, address indexed from, address indexed to, uint256 amount, bytes data, bytes operatorData ); event Minted(address indexed operator, address indexed to, uint256 amount, bytes data, bytes operatorData); event Burned(address indexed operator, address indexed from, uint256 amount, bytes data, bytes operatorData); event AuthorizedOperator(address indexed operator, address indexed tokenHolder); event RevokedOperator(address indexed operator, address indexed tokenHolder); } /** * @dev Interface of the ERC777TokensSender standard as defined in the EIP. * * {IERC777} Token holders can be notified of operations performed on their * tokens by having a contract implement this interface (contract holders can be * their own implementer) and registering it on the * https://eips.ethereum.org/EIPS/eip-1820[ERC1820 global registry]. * * See {IERC1820Registry} and {ERC1820Implementer}. */ interface IERC777Sender { /** * @dev Called by an {IERC777} token contract whenever a registered holder's * (`from`) tokens are about to be moved or destroyed. The type of operation * is conveyed by `to` being the zero address or not. * * This call occurs _before_ the token contract's state is updated, so * {IERC777-balanceOf}, etc., can be used to query the pre-operation state. * * This function may revert to prevent the operation from being executed. */ function tokensToSend( address operator, address from, address to, uint256 amount, bytes calldata userData, bytes calldata operatorData ) external; } /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * This test is non-exhaustive, and there may be false-negatives: during the * execution of a contract's constructor, its address will be reported as * not containing a contract. * * IMPORTANT: It is unsafe to assume that an address for which this * function returns false is an externally-owned account (EOA) and not a * contract. */ function isContract(address account) internal view returns (bool) { // This method relies in extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. // According to EIP-1052, 0x0 is the value returned for not-yet created accounts // and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned // for accounts without code, i.e. `keccak256('')` bytes32 codehash; bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; // solhint-disable-next-line no-inline-assembly assembly { codehash := extcodehash(account) } return (codehash != 0x0 && codehash != accountHash); } /** * @dev Converts an `address` into `address payable`. Note that this is * simply a type cast: the actual underlying value is not changed. * * _Available since v2.4.0._ */ function toPayable(address account) internal pure returns (address payable) { return address(uint160(account)); } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. * * _Available since v2.4.0._ */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-call-value (bool success, ) = recipient.call.value(amount)(""); require(success, "Address: unable to send value, recipient may have reverted"); } } /** * @dev Implementation of the {IERC777} interface. * * Largely taken from the OpenZeppelin ERC777 contract. * * Support for ERC20 is included in this contract, as specified by the EIP: both * the ERC777 and ERC20 interfaces can be safely used when interacting with it. * Both {IERC777-Sent} and {IERC20-Transfer} events are emitted on token * movements. * * Additionally, the {IERC777-granularity} value is hard-coded to `1`, meaning that there * are no special restrictions in the amount of tokens that created, moved, or * destroyed. This makes integration with ERC20 applications seamless. * * It is important to note that no Mint events are emitted. Tokens are minted in batches * by a state change in a tree data structure, so emitting a Mint event for each user * is not possible. * */ contract PoolToken is Initializable, IERC20, IERC777 { using SafeMath for uint256; using Address for address; /** * Event emitted when a user or operator redeems tokens */ event Redeemed(address indexed operator, address indexed from, uint256 amount, bytes data, bytes operatorData); IERC1820Registry constant internal ERC1820_REGISTRY = IERC1820Registry(0x1820a4B7618BdE71Dce8cdc73aAB6C95905faD24); // We inline the result of the following hashes because Solidity doesn't resolve them at compile time. // See https://github.com/ethereum/solidity/issues/4024. // keccak256("ERC777TokensSender") bytes32 constant internal TOKENS_SENDER_INTERFACE_HASH = 0x29ddb589b1fb5fc7cf394961c1adf5f8c6454761adf795e67fe149f658abe895; // keccak256("ERC777TokensRecipient") bytes32 constant internal TOKENS_RECIPIENT_INTERFACE_HASH = 0xb281fc8c12954d22544db45de3159a39272895b169a852b314f9cc762e44c53b; // keccak256("ERC777Token") bytes32 constant internal TOKENS_INTERFACE_HASH = 0xac7fbab5f54a3ca8194167523c6753bfeb96a445279294b6125b68cce2177054; // keccak256("ERC20Token") bytes32 constant internal ERC20_TOKENS_INTERFACE_HASH = 0xaea199e31a596269b42cdafd93407f14436db6e4cad65417994c2eb37381e05a; string internal _name; string internal _symbol; // This isn't ever read from - it's only used to respond to the defaultOperators query. address[] internal _defaultOperatorsArray; // Immutable, but accounts may revoke them (tracked in __revokedDefaultOperators). mapping(address => bool) internal _defaultOperators; // For each account, a mapping of its operators and revoked default operators. mapping(address => mapping(address => bool)) internal _operators; mapping(address => mapping(address => bool)) internal _revokedDefaultOperators; // ERC20-allowances mapping (address => mapping (address => uint256)) internal _allowances; // The Pool that is bound to this token BasePool internal _pool; /** * @notice Initializes the PoolToken. * @param name The name of the token * @param symbol The token symbol * @param defaultOperators The default operators who are allowed to move tokens */ function init ( string memory name, string memory symbol, address[] memory defaultOperators, BasePool pool ) public initializer { require(bytes(name).length != 0, "PoolToken/name"); require(bytes(symbol).length != 0, "PoolToken/symbol"); require(address(pool) != address(0), "PoolToken/pool-zero"); _name = name; _symbol = symbol; _pool = pool; _defaultOperatorsArray = defaultOperators; for (uint256 i = 0; i < _defaultOperatorsArray.length; i++) { _defaultOperators[_defaultOperatorsArray[i]] = true; } // register interfaces ERC1820_REGISTRY.setInterfaceImplementer(address(this), TOKENS_INTERFACE_HASH, address(this)); ERC1820_REGISTRY.setInterfaceImplementer(address(this), ERC20_TOKENS_INTERFACE_HASH, address(this)); } /** * @notice Returns the address of the Pool contract * @return The address of the pool contract */ function pool() public view returns (BasePool) { return _pool; } /** * @notice Calls the ERC777 transfer hook, and emits Redeemed and Transfer. Can only be called by the Pool contract. * @param from The address from which to redeem tokens * @param amount The amount of tokens to redeem */ function poolRedeem(address from, uint256 amount) external onlyPool { _callTokensToSend(from, from, address(0), amount, '', ''); emit Redeemed(from, from, amount, '', ''); emit Transfer(from, address(0), amount); } /** * @dev See {IERC777-name}. */ function name() public view returns (string memory) { return _name; } /** * @dev See {IERC777-symbol}. */ function symbol() public view returns (string memory) { return _symbol; } /** * @dev See {ERC20Detailed-decimals}. * * Always returns 18, as per the * [ERC777 EIP](https://eips.ethereum.org/EIPS/eip-777#backward-compatibility). */ function decimals() public view returns (uint8) { return 18; } /** * @dev See {IERC777-granularity}. * * This implementation always returns `1`. */ function granularity() public view returns (uint256) { return 1; } /** * @dev See {IERC777-totalSupply}. */ function totalSupply() public view returns (uint256) { return _pool.committedSupply(); } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address _addr) external view returns (uint256) { return _pool.committedBalanceOf(_addr); } /** * @dev See {IERC777-send}. * * Also emits a {Transfer} event for ERC20 compatibility. */ function send(address recipient, uint256 amount, bytes calldata data) external { _send(msg.sender, msg.sender, recipient, amount, data, ""); } /** * @dev See {IERC20-transfer}. * * Unlike `send`, `recipient` is _not_ required to implement the {IERC777Recipient} * interface if it is a contract. * * Also emits a {Sent} event. */ function transfer(address recipient, uint256 amount) external returns (bool) { require(recipient != address(0), "PoolToken/transfer-zero"); address from = msg.sender; _callTokensToSend(from, from, recipient, amount, "", ""); _move(from, from, recipient, amount, "", ""); _callTokensReceived(from, from, recipient, amount, "", "", false); return true; } /** * @dev Allows a user to withdraw their tokens as the underlying asset. * * Also emits a {Transfer} event for ERC20 compatibility. */ function redeem(uint256 amount, bytes calldata data) external { _redeem(msg.sender, msg.sender, amount, data, ""); } /** * @dev See {IERC777-burn}. Not currently implemented. * * Also emits a {Transfer} event for ERC20 compatibility. */ function burn(uint256, bytes calldata) external { revert("PoolToken/no-support"); } /** * @dev See {IERC777-isOperatorFor}. */ function isOperatorFor( address operator, address tokenHolder ) public view returns (bool) { return operator == tokenHolder || (_defaultOperators[operator] && !_revokedDefaultOperators[tokenHolder][operator]) || _operators[tokenHolder][operator]; } /** * @dev See {IERC777-authorizeOperator}. */ function authorizeOperator(address operator) external { require(msg.sender != operator, "PoolToken/auth-self"); if (_defaultOperators[operator]) { delete _revokedDefaultOperators[msg.sender][operator]; } else { _operators[msg.sender][operator] = true; } emit AuthorizedOperator(operator, msg.sender); } /** * @dev See {IERC777-revokeOperator}. */ function revokeOperator(address operator) external { require(operator != msg.sender, "PoolToken/revoke-self"); if (_defaultOperators[operator]) { _revokedDefaultOperators[msg.sender][operator] = true; } else { delete _operators[msg.sender][operator]; } emit RevokedOperator(operator, msg.sender); } /** * @dev See {IERC777-defaultOperators}. */ function defaultOperators() public view returns (address[] memory) { return _defaultOperatorsArray; } /** * @dev See {IERC777-operatorSend}. * * Emits {Sent} and {Transfer} events. */ function operatorSend( address sender, address recipient, uint256 amount, bytes calldata data, bytes calldata operatorData ) external { require(isOperatorFor(msg.sender, sender), "PoolToken/not-operator"); _send(msg.sender, sender, recipient, amount, data, operatorData); } /** * @dev See {IERC777-operatorBurn}. * * Currently not supported */ function operatorBurn(address, uint256, bytes calldata, bytes calldata) external { revert("PoolToken/no-support"); } /** * @dev Allows an operator to redeem tokens for the underlying asset on behalf of a user. * * Emits {Redeemed} and {Transfer} events. */ function operatorRedeem(address account, uint256 amount, bytes calldata data, bytes calldata operatorData) external { require(isOperatorFor(msg.sender, account), "PoolToken/not-operator"); _redeem(msg.sender, account, amount, data, operatorData); } /** * @dev See {IERC20-allowance}. * * Note that operator and allowance concepts are orthogonal: operators may * not have allowance, and accounts with allowance may not be operators * themselves. */ function allowance(address holder, address spender) public view returns (uint256) { return _allowances[holder][spender]; } /** * @dev See {IERC20-approve}. * * Note that accounts cannot have allowance issued by their operators. */ function approve(address spender, uint256 value) external returns (bool) { address holder = msg.sender; _approve(holder, spender, value); 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(msg.sender, spender, _allowances[msg.sender][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(msg.sender, spender, _allowances[msg.sender][spender].sub(subtractedValue, "PoolToken/negative")); return true; } /** * @dev See {IERC20-transferFrom}. * * Note that operator and allowance concepts are orthogonal: operators cannot * call `transferFrom` (unless they have allowance), and accounts with * allowance cannot call `operatorSend` (unless they are operators). * * Emits {Sent}, {Transfer} and {Approval} events. */ function transferFrom(address holder, address recipient, uint256 amount) external returns (bool) { require(recipient != address(0), "PoolToken/to-zero"); require(holder != address(0), "PoolToken/from-zero"); address spender = msg.sender; _callTokensToSend(spender, holder, recipient, amount, "", ""); _move(spender, holder, recipient, amount, "", ""); _approve(holder, spender, _allowances[holder][spender].sub(amount, "PoolToken/exceed-allow")); _callTokensReceived(spender, holder, recipient, amount, "", "", false); return true; } /** * Called by the associated Pool to emit `Mint` events. * @param amount The amount that was minted */ function poolMint(uint256 amount) external onlyPool { _mintEvents(address(_pool), address(_pool), amount, '', ''); } /** * Emits {Minted} and {IERC20-Transfer} events. */ function _mintEvents( address operator, address account, uint256 amount, bytes memory userData, bytes memory operatorData ) internal { emit Minted(operator, account, amount, userData, operatorData); emit Transfer(address(0), account, amount); } /** * @dev Send tokens * @param operator address operator requesting the transfer * @param from address token holder address * @param to address recipient address * @param amount uint256 amount of tokens to transfer * @param userData bytes extra information provided by the token holder (if any) * @param operatorData bytes extra information provided by the operator (if any) */ function _send( address operator, address from, address to, uint256 amount, bytes memory userData, bytes memory operatorData ) private { require(from != address(0), "PoolToken/from-zero"); require(to != address(0), "PoolToken/to-zero"); _callTokensToSend(operator, from, to, amount, userData, operatorData); _move(operator, from, to, amount, userData, operatorData); _callTokensReceived(operator, from, to, amount, userData, operatorData, false); } /** * @dev Redeems tokens for the underlying asset. * @param operator address operator requesting the operation * @param from address token holder address * @param amount uint256 amount of tokens to redeem * @param data bytes extra information provided by the token holder * @param operatorData bytes extra information provided by the operator (if any) */ function _redeem( address operator, address from, uint256 amount, bytes memory data, bytes memory operatorData ) private { require(from != address(0), "PoolToken/from-zero"); _callTokensToSend(operator, from, address(0), amount, data, operatorData); _pool.withdrawCommittedDepositFrom(from, amount); emit Redeemed(operator, from, amount, data, operatorData); emit Transfer(from, address(0), amount); } /** * @notice Moves tokens from one user to another. Emits Sent and Transfer events. */ function _move( address operator, address from, address to, uint256 amount, bytes memory userData, bytes memory operatorData ) private { _pool.moveCommitted(from, to, amount); emit Sent(operator, from, to, amount, userData, operatorData); emit Transfer(from, to, amount); } /** * Approves of a token spend by a spender for a holder. * @param holder The address from which the tokens are spent * @param spender The address that is spending the tokens * @param value The amount of tokens to spend */ function _approve(address holder, address spender, uint256 value) private { require(spender != address(0), "PoolToken/from-zero"); _allowances[holder][spender] = value; emit Approval(holder, spender, value); } /** * @dev Call from.tokensToSend() if the interface is registered * @param operator address operator requesting the transfer * @param from address token holder address * @param to address recipient address * @param amount uint256 amount of tokens to transfer * @param userData bytes extra information provided by the token holder (if any) * @param operatorData bytes extra information provided by the operator (if any) */ function _callTokensToSend( address operator, address from, address to, uint256 amount, bytes memory userData, bytes memory operatorData ) internal notLocked { address implementer = ERC1820_REGISTRY.getInterfaceImplementer(from, TOKENS_SENDER_INTERFACE_HASH); if (implementer != address(0)) { IERC777Sender(implementer).tokensToSend(operator, from, to, amount, userData, operatorData); } } /** * @dev Call to.tokensReceived() if the interface is registered. Reverts if the recipient is a contract but * tokensReceived() was not registered for the recipient * @param operator address operator requesting the transfer * @param from address token holder address * @param to address recipient address * @param amount uint256 amount of tokens to transfer * @param userData bytes extra information provided by the token holder (if any) * @param operatorData bytes extra information provided by the operator (if any) * @param requireReceptionAck whether to require that, if the recipient is a contract, it has registered a IERC777Recipient */ function _callTokensReceived( address operator, address from, address to, uint256 amount, bytes memory userData, bytes memory operatorData, bool requireReceptionAck ) private { address implementer = ERC1820_REGISTRY.getInterfaceImplementer(to, TOKENS_RECIPIENT_INTERFACE_HASH); if (implementer != address(0)) { IERC777Recipient(implementer).tokensReceived(operator, from, to, amount, userData, operatorData); } else if (requireReceptionAck) { require(!to.isContract(), "PoolToken/no-recip-inter"); } } /** * @notice Requires the sender to be the pool contract */ modifier onlyPool() { require(msg.sender == address(_pool), "PoolToken/only-pool"); _; } /** * @notice Requires the contract to be unlocked */ modifier notLocked() { require(!_pool.isLocked(), "PoolToken/is-locked"); _; } } /** * @title The Pool contract * @author Brendan Asselstine * @notice This contract allows users to pool deposits into Compound and win the accrued interest in periodic draws. * Funds are immediately deposited and withdrawn from the Compound cToken contract. * Draws go through three stages: open, committed and rewarded in that order. * Only one draw is ever in the open stage. Users deposits are always added to the open draw. Funds in the open Draw are that user's open balance. * When a Draw is committed, the funds in it are moved to a user's committed total and the total committed balance of all users is updated. * When a Draw is rewarded, the gross winnings are the accrued interest since the last reward (if any). A winner is selected with their chances being * proportional to their committed balance vs the total committed balance of all users. * * * With the above in mind, there is always an open draw and possibly a committed draw. The progression is: * * Step 1: Draw 1 Open * Step 2: Draw 2 Open | Draw 1 Committed * Step 3: Draw 3 Open | Draw 2 Committed | Draw 1 Rewarded * Step 4: Draw 4 Open | Draw 3 Committed | Draw 2 Rewarded * Step 5: Draw 5 Open | Draw 4 Committed | Draw 3 Rewarded * Step X: ... */ contract BasePool is Initializable, ReentrancyGuard { using DrawManager for DrawManager.State; using SafeMath for uint256; using Roles for Roles.Role; using Blocklock for Blocklock.State; bytes32 internal constant ROLLED_OVER_ENTROPY_MAGIC_NUMBER = bytes32(uint256(1)); IERC1820Registry constant internal ERC1820_REGISTRY = IERC1820Registry(0x1820a4B7618BdE71Dce8cdc73aAB6C95905faD24); // We inline the result of the following hashes because Solidity doesn't resolve them at compile time. // See https://github.com/ethereum/solidity/issues/4024. // keccak256("PoolTogetherRewardListener") bytes32 constant internal REWARD_LISTENER_INTERFACE_HASH = 0x68f03b0b1a978ee238a70b362091d993343460bc1a2830ab3f708936d9f564a4; /** * Emitted when a user deposits into the Pool. * @param sender The purchaser of the tickets * @param amount The size of the deposit */ event Deposited(address indexed sender, uint256 amount); /** * Emitted when a user deposits into the Pool and the deposit is immediately committed * @param sender The purchaser of the tickets * @param amount The size of the deposit */ event DepositedAndCommitted(address indexed sender, uint256 amount); /** * Emitted when Sponsors have deposited into the Pool * @param sender The purchaser of the tickets * @param amount The size of the deposit */ event SponsorshipDeposited(address indexed sender, uint256 amount); /** * Emitted when an admin has been added to the Pool. * @param admin The admin that was added */ event AdminAdded(address indexed admin); /** * Emitted when an admin has been removed from the Pool. * @param admin The admin that was removed */ event AdminRemoved(address indexed admin); /** * Emitted when a user withdraws from the pool. * @param sender The user that is withdrawing from the pool * @param amount The amount that the user withdrew */ event Withdrawn(address indexed sender, uint256 amount); /** * Emitted when a user withdraws their sponsorship and fees from the pool. * @param sender The user that is withdrawing * @param amount The amount they are withdrawing */ event SponsorshipAndFeesWithdrawn(address indexed sender, uint256 amount); /** * Emitted when a user withdraws from their open deposit. * @param sender The user that is withdrawing * @param amount The amount they are withdrawing */ event OpenDepositWithdrawn(address indexed sender, uint256 amount); /** * Emitted when a user withdraws from their committed deposit. * @param sender The user that is withdrawing * @param amount The amount they are withdrawing */ event CommittedDepositWithdrawn(address indexed sender, uint256 amount); /** * Emitted when an address collects a fee * @param sender The address collecting the fee * @param amount The fee amount * @param drawId The draw from which the fee was awarded */ event FeeCollected(address indexed sender, uint256 amount, uint256 drawId); /** * Emitted when a new draw is opened for deposit. * @param drawId The draw id * @param feeBeneficiary The fee beneficiary for this draw * @param secretHash The committed secret hash * @param feeFraction The fee fraction of the winnings to be given to the beneficiary */ event Opened( uint256 indexed drawId, address indexed feeBeneficiary, bytes32 secretHash, uint256 feeFraction ); /** * Emitted when a draw is committed. * @param drawId The draw id */ event Committed( uint256 indexed drawId ); /** * Emitted when a draw is rewarded. * @param drawId The draw id * @param winner The address of the winner * @param entropy The entropy used to select the winner * @param winnings The net winnings given to the winner * @param fee The fee being given to the draw beneficiary */ event Rewarded( uint256 indexed drawId, address indexed winner, bytes32 entropy, uint256 winnings, uint256 fee ); /** * Emitted when a RewardListener call fails * @param drawId The draw id * @param winner The address that one the draw * @param impl The implementation address of the RewardListener */ event RewardListenerFailed( uint256 indexed drawId, address indexed winner, address indexed impl ); /** * Emitted when the fee fraction is changed. Takes effect on the next draw. * @param feeFraction The next fee fraction encoded as a fixed point 18 decimal */ event NextFeeFractionChanged(uint256 feeFraction); /** * Emitted when the next fee beneficiary changes. Takes effect on the next draw. * @param feeBeneficiary The next fee beneficiary */ event NextFeeBeneficiaryChanged(address indexed feeBeneficiary); /** * Emitted when an admin pauses the contract */ event DepositsPaused(address indexed sender); /** * Emitted when an admin unpauses the contract */ event DepositsUnpaused(address indexed sender); /** * Emitted when the draw is rolled over in the event that the secret is forgotten. */ event RolledOver(uint256 indexed drawId); struct Draw { uint256 feeFraction; //fixed point 18 address feeBeneficiary; uint256 openedBlock; bytes32 secretHash; bytes32 entropy; address winner; uint256 netWinnings; uint256 fee; } /** * The Compound cToken that this Pool is bound to. */ ICErc20 public cToken; /** * The fee beneficiary to use for subsequent Draws. */ address public nextFeeBeneficiary; /** * The fee fraction to use for subsequent Draws. */ uint256 public nextFeeFraction; /** * The total of all balances */ uint256 public accountedBalance; /** * The total deposits and winnings for each user. */ mapping (address => uint256) internal balances; /** * A mapping of draw ids to Draw structures */ mapping(uint256 => Draw) internal draws; /** * A structure that is used to manage the user's odds of winning. */ DrawManager.State internal drawState; /** * A structure containing the administrators */ Roles.Role internal admins; /** * Whether the contract is paused */ bool public paused; Blocklock.State internal blocklock; PoolToken public poolToken; /** * @notice Initializes a new Pool contract. * @param _owner The owner of the Pool. They are able to change settings and are set as the owner of new lotteries. * @param _cToken The Compound Finance MoneyMarket contract to supply and withdraw tokens. * @param _feeFraction The fraction of the gross winnings that should be transferred to the owner as the fee. Is a fixed point 18 number. * @param _feeBeneficiary The address that will receive the fee fraction */ function init ( address _owner, address _cToken, uint256 _feeFraction, address _feeBeneficiary, uint256 _lockDuration, uint256 _cooldownDuration ) public initializer { require(_owner != address(0), "Pool/owner-zero"); require(_cToken != address(0), "Pool/ctoken-zero"); cToken = ICErc20(_cToken); _addAdmin(_owner); _setNextFeeFraction(_feeFraction); _setNextFeeBeneficiary(_feeBeneficiary); initBlocklock(_lockDuration, _cooldownDuration); } function setPoolToken(PoolToken _poolToken) external onlyAdmin { require(address(poolToken) == address(0), "Pool/token-was-set"); require(address(_poolToken.pool()) == address(this), "Pool/token-mismatch"); poolToken = _poolToken; } function initBlocklock(uint256 _lockDuration, uint256 _cooldownDuration) internal { blocklock.setLockDuration(_lockDuration); blocklock.setCooldownDuration(_cooldownDuration); } /** * @notice Opens a new Draw. * @param _secretHash The secret hash to commit to the Draw. */ function open(bytes32 _secretHash) internal { drawState.openNextDraw(); draws[drawState.openDrawIndex] = Draw( nextFeeFraction, nextFeeBeneficiary, block.number, _secretHash, bytes32(0), address(0), uint256(0), uint256(0) ); emit Opened( drawState.openDrawIndex, nextFeeBeneficiary, _secretHash, nextFeeFraction ); } /** * @notice Emits the Committed event for the current open draw. */ function emitCommitted() internal { uint256 drawId = currentOpenDrawId(); emit Committed(drawId); if (address(poolToken) != address(0)) { poolToken.poolMint(openSupply()); } } /** * @notice Commits the current open draw, if any, and opens the next draw using the passed hash. Really this function is only called twice: * the first after Pool contract creation and the second immediately after. * Can only be called by an admin. * May fire the Committed event, and always fires the Open event. * @param nextSecretHash The secret hash to use to open a new Draw */ function openNextDraw(bytes32 nextSecretHash) public onlyAdmin { if (currentCommittedDrawId() > 0) { require(currentCommittedDrawHasBeenRewarded(), "Pool/not-reward"); } if (currentOpenDrawId() != 0) { emitCommitted(); } open(nextSecretHash); } /** * @notice Ignores the current draw, and opens the next draw. * @dev This function will be removed once the winner selection has been decentralized. * @param nextSecretHash The hash to commit for the next draw */ function rolloverAndOpenNextDraw(bytes32 nextSecretHash) public onlyAdmin { rollover(); openNextDraw(nextSecretHash); } /** * @notice Rewards the current committed draw using the passed secret, commits the current open draw, and opens the next draw using the passed secret hash. * Can only be called by an admin. * Fires the Rewarded event, the Committed event, and the Open event. * @param nextSecretHash The secret hash to use to open a new Draw * @param lastSecret The secret to reveal to reward the current committed Draw. * @param _salt The salt that was used to conceal the secret */ function rewardAndOpenNextDraw(bytes32 nextSecretHash, bytes32 lastSecret, bytes32 _salt) public onlyAdmin { reward(lastSecret, _salt); openNextDraw(nextSecretHash); } /** * @notice Rewards the winner for the current committed Draw using the passed secret. * The gross winnings are calculated by subtracting the accounted balance from the current underlying cToken balance. * A winner is calculated using the revealed secret. * If there is a winner (i.e. any eligible users) then winner's balance is updated with their net winnings. * The draw beneficiary's balance is updated with the fee. * The accounted balance is updated to include the fee and, if there was a winner, the net winnings. * Fires the Rewarded event. * @param _secret The secret to reveal for the current committed Draw * @param _salt The salt that was used to conceal the secret */ function reward(bytes32 _secret, bytes32 _salt) public onlyAdmin onlyLocked requireCommittedNoReward nonReentrant { // require that there is a committed draw // require that the committed draw has not been rewarded uint256 drawId = currentCommittedDrawId(); Draw storage draw = draws[drawId]; require(draw.secretHash == keccak256(abi.encodePacked(_secret, _salt)), "Pool/bad-secret"); // derive entropy from the revealed secret bytes32 entropy = keccak256(abi.encodePacked(_secret)); _reward(drawId, draw, entropy); } function _reward(uint256 drawId, Draw storage draw, bytes32 entropy) internal { blocklock.unlock(block.number); // Select the winner using the hash as entropy address winningAddress = calculateWinner(entropy); // Calculate the gross winnings uint256 underlyingBalance = balance(); uint256 grossWinnings; // It's possible when the APR is zero that the underlying balance will be slightly lower than the accountedBalance // due to rounding errors in the Compound contract. if (underlyingBalance > accountedBalance) { grossWinnings = capWinnings(underlyingBalance.sub(accountedBalance)); } // Calculate the beneficiary fee uint256 fee = calculateFee(draw.feeFraction, grossWinnings); // Update balance of the beneficiary balances[draw.feeBeneficiary] = balances[draw.feeBeneficiary].add(fee); // Calculate the net winnings uint256 netWinnings = grossWinnings.sub(fee); draw.winner = winningAddress; draw.netWinnings = netWinnings; draw.fee = fee; draw.entropy = entropy; // If there is a winner who is to receive non-zero winnings if (winningAddress != address(0) && netWinnings != 0) { // Updated the accounted total accountedBalance = underlyingBalance; // Update balance of the winner balances[winningAddress] = balances[winningAddress].add(netWinnings); // Enter their winnings into the open draw drawState.deposit(winningAddress, netWinnings); callRewarded(winningAddress, netWinnings, drawId); } else { // Only account for the fee accountedBalance = accountedBalance.add(fee); } emit Rewarded( drawId, winningAddress, entropy, netWinnings, fee ); emit FeeCollected(draw.feeBeneficiary, fee, drawId); } /** * @notice Calls the reward listener for the winner, if a listener exists. * @dev Checks for a listener using the ERC1820 registry. The listener is given a gas stipend of 200,000 to run the function. * The number 200,000 was selected because it's safely above the gas requirements for PoolTogether [Pod](https://github.com/pooltogether/pods) contract. * * @param winner The winner. If they have a listener registered in the ERC1820 registry it will be called. * @param netWinnings The amount that was won. * @param drawId The draw id that was won. */ function callRewarded(address winner, uint256 netWinnings, uint256 drawId) internal { address impl = ERC1820_REGISTRY.getInterfaceImplementer(winner, REWARD_LISTENER_INTERFACE_HASH); if (impl != address(0)) { (bool success,) = impl.call.gas(200000)(abi.encodeWithSignature("rewarded(address,uint256,uint256)", winner, netWinnings, drawId)); if (!success) { emit RewardListenerFailed(drawId, winner, impl); } } } /** * @notice A function that skips the reward for the committed draw id. * @dev This function will be removed once the entropy is decentralized. */ function rollover() public onlyAdmin requireCommittedNoReward { uint256 drawId = currentCommittedDrawId(); Draw storage draw = draws[drawId]; draw.entropy = ROLLED_OVER_ENTROPY_MAGIC_NUMBER; emit RolledOver( drawId ); emit Rewarded( drawId, address(0), ROLLED_OVER_ENTROPY_MAGIC_NUMBER, 0, 0 ); } /** * @notice Ensures that the winnings don't overflow. Note that we can make this integer max, because the fee * is always less than zero (meaning the FixidityLib.multiply will always make the number smaller) */ function capWinnings(uint256 _grossWinnings) internal pure returns (uint256) { uint256 max = uint256(FixidityLib.maxNewFixed()); if (_grossWinnings > max) { return max; } return _grossWinnings; } /** * @notice Calculate the beneficiary fee using the passed fee fraction and gross winnings. * @param _feeFraction The fee fraction, between 0 and 1, represented as a 18 point fixed number. * @param _grossWinnings The gross winnings to take a fraction of. */ function calculateFee(uint256 _feeFraction, uint256 _grossWinnings) internal pure returns (uint256) { int256 grossWinningsFixed = FixidityLib.newFixed(int256(_grossWinnings)); // _feeFraction *must* be less than 1 ether, so it will never overflow int256 feeFixed = FixidityLib.multiply(grossWinningsFixed, FixidityLib.newFixed(int256(_feeFraction), uint8(18))); return uint256(FixidityLib.fromFixed(feeFixed)); } /** * @notice Allows a user to deposit a sponsorship amount. The deposit is transferred into the cToken. * Sponsorships allow a user to contribute to the pool without becoming eligible to win. They can withdraw their sponsorship at any time. * The deposit will immediately be added to Compound and the interest will contribute to the next draw. * @param _amount The amount of the token underlying the cToken to deposit. */ function depositSponsorship(uint256 _amount) public unlessDepositsPaused nonReentrant { // Transfer the tokens into this contract require(token().transferFrom(msg.sender, address(this), _amount), "Pool/t-fail"); // Deposit the sponsorship amount _depositSponsorshipFrom(msg.sender, _amount); } /** * @notice Deposits the token balance for this contract as a sponsorship. * If people erroneously transfer tokens to this contract, this function will allow us to recoup those tokens as sponsorship. */ function transferBalanceToSponsorship() public unlessDepositsPaused { // Deposit the sponsorship amount _depositSponsorshipFrom(address(this), token().balanceOf(address(this))); } /** * @notice Deposits into the pool under the current open Draw. The deposit is transferred into the cToken. * Once the open draw is committed, the deposit will be added to the user's total committed balance and increase their chances of winning * proportional to the total committed balance of all users. * @param _amount The amount of the token underlying the cToken to deposit. */ function depositPool(uint256 _amount) public requireOpenDraw unlessDepositsPaused nonReentrant notLocked { // Transfer the tokens into this contract require(token().transferFrom(msg.sender, address(this), _amount), "Pool/t-fail"); // Deposit the funds _depositPoolFrom(msg.sender, _amount); } /** * @notice Deposits sponsorship for a user * @param _spender The user who is sponsoring * @param _amount The amount they are sponsoring */ function _depositSponsorshipFrom(address _spender, uint256 _amount) internal { // Deposit the funds _depositFrom(_spender, _amount); emit SponsorshipDeposited(_spender, _amount); } /** * @notice Deposits into the pool for a user. The deposit will be open until the next draw is committed. * @param _spender The user who is depositing * @param _amount The amount the user is depositing */ function _depositPoolFrom(address _spender, uint256 _amount) internal { // Update the user's eligibility drawState.deposit(_spender, _amount); _depositFrom(_spender, _amount); emit Deposited(_spender, _amount); } /** * @notice Deposits into the pool for a user. The deposit is made part of the currently committed draw * @param _spender The user who is depositing * @param _amount The amount to deposit */ function _depositPoolFromCommitted(address _spender, uint256 _amount) internal notLocked { // Update the user's eligibility drawState.depositCommitted(_spender, _amount); _depositFrom(_spender, _amount); emit DepositedAndCommitted(_spender, _amount); } /** * @notice Deposits into the pool for a user. Updates their balance and transfers their tokens into this contract. * @param _spender The user who is depositing * @param _amount The amount they are depositing */ function _depositFrom(address _spender, uint256 _amount) internal { // Update the user's balance balances[_spender] = balances[_spender].add(_amount); // Update the total of this contract accountedBalance = accountedBalance.add(_amount); // Deposit into Compound require(token().approve(address(cToken), _amount), "Pool/approve"); require(cToken.mint(_amount) == 0, "Pool/supply"); } /** * Withdraws the given amount from the user's deposits. It first withdraws from their sponsorship, * then their open deposits, then their committed deposits. * * @param amount The amount to withdraw. */ function withdraw(uint256 amount) public nonReentrant notLocked { uint256 remainingAmount = amount; // first sponsorship uint256 sponsorshipAndFeesBalance = sponsorshipAndFeeBalanceOf(msg.sender); if (sponsorshipAndFeesBalance < remainingAmount) { withdrawSponsorshipAndFee(sponsorshipAndFeesBalance); remainingAmount = remainingAmount.sub(sponsorshipAndFeesBalance); } else { withdrawSponsorshipAndFee(remainingAmount); return; } // now pending uint256 pendingBalance = drawState.openBalanceOf(msg.sender); if (pendingBalance < remainingAmount) { _withdrawOpenDeposit(msg.sender, pendingBalance); remainingAmount = remainingAmount.sub(pendingBalance); } else { _withdrawOpenDeposit(msg.sender, remainingAmount); return; } // now committed. remainingAmount should not be greater than committed balance. _withdrawCommittedDeposit(msg.sender, remainingAmount); } /** * @notice Withdraw the sender's entire balance back to them. */ function withdraw() public nonReentrant notLocked { uint256 committedBalance = drawState.committedBalanceOf(msg.sender); uint256 balance = balances[msg.sender]; // Update their chances of winning drawState.withdraw(msg.sender); _withdraw(msg.sender, balance); if (address(poolToken) != address(0)) { poolToken.poolRedeem(msg.sender, committedBalance); } emit Withdrawn(msg.sender, balance); } /** * Withdraws only from the sender's sponsorship and fee balances * @param _amount The amount to withdraw */ function withdrawSponsorshipAndFee(uint256 _amount) public { uint256 sponsorshipAndFees = sponsorshipAndFeeBalanceOf(msg.sender); require(_amount <= sponsorshipAndFees, "Pool/exceeds-sfee"); _withdraw(msg.sender, _amount); emit SponsorshipAndFeesWithdrawn(msg.sender, _amount); } /** * Returns the total balance of the user's sponsorship and fees * @param _sender The user whose balance should be returned */ function sponsorshipAndFeeBalanceOf(address _sender) public view returns (uint256) { return balances[_sender].sub(drawState.balanceOf(_sender)); } /** * Withdraws from the user's open deposits * @param _amount The amount to withdraw */ function withdrawOpenDeposit(uint256 _amount) public nonReentrant notLocked { _withdrawOpenDeposit(msg.sender, _amount); } function _withdrawOpenDeposit(address sender, uint256 _amount) internal { drawState.withdrawOpen(sender, _amount); _withdraw(sender, _amount); emit OpenDepositWithdrawn(sender, _amount); } /** * Withdraws from the user's committed deposits * @param _amount The amount to withdraw */ function withdrawCommittedDeposit(uint256 _amount) public nonReentrant notLocked returns (bool) { _withdrawCommittedDeposit(msg.sender, _amount); return true; } function _withdrawCommittedDeposit(address sender, uint256 _amount) internal { _withdrawCommittedDepositAndEmit(sender, _amount); if (address(poolToken) != address(0)) { poolToken.poolRedeem(sender, _amount); } } /** * Allows the associated PoolToken to withdraw for a user; useful when redeeming through the token. * @param _from The user to withdraw from * @param _amount The amount to withdraw */ function withdrawCommittedDepositFrom( address _from, uint256 _amount ) external onlyToken notLocked returns (bool) { return _withdrawCommittedDepositAndEmit(_from, _amount); } /** * A function that withdraws committed deposits for a user and emits the corresponding events. * @param _from User to withdraw for * @param _amount The amount to withdraw */ function _withdrawCommittedDepositAndEmit(address _from, uint256 _amount) internal returns (bool) { drawState.withdrawCommitted(_from, _amount); _withdraw(_from, _amount); emit CommittedDepositWithdrawn(_from, _amount); return true; } /** * @notice Allows the associated PoolToken to move committed tokens from one user to another. * @param _from The account to move tokens from * @param _to The account that is receiving the tokens * @param _amount The amount of tokens to transfer */ function moveCommitted( address _from, address _to, uint256 _amount ) external onlyToken onlyCommittedBalanceGteq(_from, _amount) notLocked returns (bool) { balances[_from] = balances[_from].sub(_amount, "move could not sub amount"); balances[_to] = balances[_to].add(_amount); drawState.withdrawCommitted(_from, _amount); drawState.depositCommitted(_to, _amount); return true; } /** * @notice Transfers tokens from the cToken contract to the sender. Updates the accounted balance. */ function _withdraw(address _sender, uint256 _amount) internal { uint256 balance = balances[_sender]; require(_amount <= balance, "Pool/no-funds"); // Update the user's balance balances[_sender] = balance.sub(_amount); // Update the total of this contract accountedBalance = accountedBalance.sub(_amount); // Withdraw from Compound and transfer require(cToken.redeemUnderlying(_amount) == 0, "Pool/redeem"); require(token().transfer(_sender, _amount), "Pool/transfer"); } /** * @notice Returns the id of the current open Draw. * @return The current open Draw id */ function currentOpenDrawId() public view returns (uint256) { return drawState.openDrawIndex; } /** * @notice Returns the id of the current committed Draw. * @return The current committed Draw id */ function currentCommittedDrawId() public view returns (uint256) { if (drawState.openDrawIndex > 1) { return drawState.openDrawIndex - 1; } else { return 0; } } /** * @notice Returns whether the current committed draw has been rewarded * @return True if the current committed draw has been rewarded, false otherwise */ function currentCommittedDrawHasBeenRewarded() internal view returns (bool) { Draw storage draw = draws[currentCommittedDrawId()]; return draw.entropy != bytes32(0); } /** * @notice Gets information for a given draw. * @param _drawId The id of the Draw to retrieve info for. * @return Fields including: * feeFraction: the fee fraction * feeBeneficiary: the beneficiary of the fee * openedBlock: The block at which the draw was opened * secretHash: The hash of the secret committed to this draw. * entropy: the entropy used to select the winner * winner: the address of the winner * netWinnings: the total winnings less the fee * fee: the fee taken by the beneficiary */ function getDraw(uint256 _drawId) public view returns ( uint256 feeFraction, address feeBeneficiary, uint256 openedBlock, bytes32 secretHash, bytes32 entropy, address winner, uint256 netWinnings, uint256 fee ) { Draw storage draw = draws[_drawId]; feeFraction = draw.feeFraction; feeBeneficiary = draw.feeBeneficiary; openedBlock = draw.openedBlock; secretHash = draw.secretHash; entropy = draw.entropy; winner = draw.winner; netWinnings = draw.netWinnings; fee = draw.fee; } /** * @notice Returns the total of the address's balance in committed Draws. That is, the total that contributes to their chances of winning. * @param _addr The address of the user * @return The total committed balance for the user */ function committedBalanceOf(address _addr) external view returns (uint256) { return drawState.committedBalanceOf(_addr); } /** * @notice Returns the total of the address's balance in the open Draw. That is, the total that will *eventually* contribute to their chances of winning. * @param _addr The address of the user * @return The total open balance for the user */ function openBalanceOf(address _addr) external view returns (uint256) { return drawState.openBalanceOf(_addr); } /** * @notice Returns a user's total balance. This includes their sponsorships, fees, open deposits, and committed deposits. * @param _addr The address of the user to check. * @return The user's current balance. */ function totalBalanceOf(address _addr) external view returns (uint256) { return balances[_addr]; } /** * @notice Returns a user's committed balance. This is the balance of their Pool tokens. * @param _addr The address of the user to check. * @return The user's current balance. */ function balanceOf(address _addr) external view returns (uint256) { return drawState.committedBalanceOf(_addr); } /** * @notice Calculates a winner using the passed entropy for the current committed balances. * @param _entropy The entropy to use to select the winner * @return The winning address */ function calculateWinner(bytes32 _entropy) public view returns (address) { return drawState.drawWithEntropy(_entropy); } /** * @notice Returns the total committed balance. Used to compute an address's chances of winning. * @return The total committed balance. */ function committedSupply() public view returns (uint256) { return drawState.committedSupply(); } /** * @notice Returns the total open balance. This balance is the number of tickets purchased for the open draw. * @return The total open balance */ function openSupply() public view returns (uint256) { return drawState.openSupply(); } /** * @notice Calculates the total estimated interest earned for the given number of blocks * @param _blocks The number of block that interest accrued for * @return The total estimated interest as a 18 point fixed decimal. */ function estimatedInterestRate(uint256 _blocks) public view returns (uint256) { return supplyRatePerBlock().mul(_blocks); } /** * @notice Convenience function to return the supplyRatePerBlock value from the money market contract. * @return The cToken supply rate per block */ function supplyRatePerBlock() public view returns (uint256) { return cToken.supplyRatePerBlock(); } /** * @notice Sets the beneficiary fee fraction for subsequent Draws. * Fires the NextFeeFractionChanged event. * Can only be called by an admin. * @param _feeFraction The fee fraction to use. * Must be between 0 and 1 and formatted as a fixed point number with 18 decimals (as in Ether). */ function setNextFeeFraction(uint256 _feeFraction) public onlyAdmin { _setNextFeeFraction(_feeFraction); } function _setNextFeeFraction(uint256 _feeFraction) internal { require(_feeFraction <= 1 ether, "Pool/less-1"); nextFeeFraction = _feeFraction; emit NextFeeFractionChanged(_feeFraction); } /** * @notice Sets the fee beneficiary for subsequent Draws. * Can only be called by admins. * @param _feeBeneficiary The beneficiary for the fee fraction. Cannot be the 0 address. */ function setNextFeeBeneficiary(address _feeBeneficiary) public onlyAdmin { _setNextFeeBeneficiary(_feeBeneficiary); } /** * @notice Sets the fee beneficiary for subsequent Draws. * @param _feeBeneficiary The beneficiary for the fee fraction. Cannot be the 0 address. */ function _setNextFeeBeneficiary(address _feeBeneficiary) internal { require(_feeBeneficiary != address(0), "Pool/not-zero"); nextFeeBeneficiary = _feeBeneficiary; emit NextFeeBeneficiaryChanged(_feeBeneficiary); } /** * @notice Adds an administrator. * Can only be called by administrators. * Fires the AdminAdded event. * @param _admin The address of the admin to add */ function addAdmin(address _admin) public onlyAdmin { _addAdmin(_admin); } /** * @notice Checks whether a given address is an administrator. * @param _admin The address to check * @return True if the address is an admin, false otherwise. */ function isAdmin(address _admin) public view returns (bool) { return admins.has(_admin); } /** * @notice Checks whether a given address is an administrator. * @param _admin The address to check * @return True if the address is an admin, false otherwise. */ function _addAdmin(address _admin) internal { admins.add(_admin); emit AdminAdded(_admin); } /** * @notice Removes an administrator * Can only be called by an admin. * Admins cannot remove themselves. This ensures there is always one admin. * @param _admin The address of the admin to remove */ function removeAdmin(address _admin) public onlyAdmin { require(admins.has(_admin), "Pool/no-admin"); require(_admin != msg.sender, "Pool/remove-self"); admins.remove(_admin); emit AdminRemoved(_admin); } /** * Requires that there is a committed draw that has not been rewarded. */ modifier requireCommittedNoReward() { require(currentCommittedDrawId() > 0, "Pool/committed"); require(!currentCommittedDrawHasBeenRewarded(), "Pool/already"); _; } /** * @notice Returns the token underlying the cToken. * @return An ERC20 token address */ function token() public view returns (IERC20) { return IERC20(cToken.underlying()); } /** * @notice Returns the underlying balance of this contract in the cToken. * @return The cToken underlying balance for this contract. */ function balance() public returns (uint256) { return cToken.balanceOfUnderlying(address(this)); } /** * @notice Locks the movement of tokens (essentially the committed deposits and winnings) * @dev The lock only lasts for a duration of blocks. The lock cannot be relocked until the cooldown duration completes. */ function lockTokens() public onlyAdmin { blocklock.lock(block.number); } /** * @notice Unlocks the movement of tokens (essentially the committed deposits) */ function unlockTokens() public onlyAdmin { blocklock.unlock(block.number); } /** * Pauses all deposits into the contract. This was added so that we can slowly deprecate Pools. Users can continue * to collect rewards and withdraw, but eventually the Pool will grow smaller. * * emits DepositsPaused */ function pauseDeposits() public unlessDepositsPaused onlyAdmin { paused = true; emit DepositsPaused(msg.sender); } /** * @notice Unpauses all deposits into the contract * * emits DepositsUnpaused */ function unpauseDeposits() public whenDepositsPaused onlyAdmin { paused = false; emit DepositsUnpaused(msg.sender); } /** * @notice Check if the contract is locked. * @return True if the contract is locked, false otherwise */ function isLocked() public view returns (bool) { return blocklock.isLocked(block.number); } /** * @notice Returns the block number at which the lock expires * @return The block number at which the lock expires */ function lockEndAt() public view returns (uint256) { return blocklock.lockEndAt(); } /** * @notice Check cooldown end block * @return The block number at which the cooldown ends and the contract can be re-locked */ function cooldownEndAt() public view returns (uint256) { return blocklock.cooldownEndAt(); } /** * @notice Returns whether the contract can be locked * @return True if the contract can be locked, false otherwise */ function canLock() public view returns (bool) { return blocklock.canLock(block.number); } /** * @notice Duration of the lock * @return Returns the duration of the lock in blocks. */ function lockDuration() public view returns (uint256) { return blocklock.lockDuration; } /** * @notice Returns the cooldown duration. The cooldown period starts after the Pool has been unlocked. * The Pool cannot be locked during the cooldown period. * @return The cooldown duration in blocks */ function cooldownDuration() public view returns (uint256) { return blocklock.cooldownDuration; } /** * @notice requires the pool not to be locked */ modifier notLocked() { require(!blocklock.isLocked(block.number), "Pool/locked"); _; } /** * @notice requires the pool to be locked */ modifier onlyLocked() { require(blocklock.isLocked(block.number), "Pool/unlocked"); _; } /** * @notice requires the caller to be an admin */ modifier onlyAdmin() { require(admins.has(msg.sender), "Pool/admin"); _; } /** * @notice Requires an open draw to exist */ modifier requireOpenDraw() { require(currentOpenDrawId() != 0, "Pool/no-open"); _; } /** * @notice Requires deposits to be paused */ modifier whenDepositsPaused() { require(paused, "Pool/d-not-paused"); _; } /** * @notice Requires deposits not to be paused */ modifier unlessDepositsPaused() { require(!paused, "Pool/d-paused"); _; } /** * @notice Requires the caller to be the pool token */ modifier onlyToken() { require(msg.sender == address(poolToken), "Pool/only-token"); _; } /** * @notice requires the passed user's committed balance to be greater than or equal to the passed amount * @param _from The user whose committed balance should be checked * @param _amount The minimum amount they must have */ modifier onlyCommittedBalanceGteq(address _from, uint256 _amount) { uint256 committedBalance = drawState.committedBalanceOf(_from); require(_amount <= committedBalance, "not enough funds"); _; } } contract ScdMcdMigration { SaiTubLike public tub; VatLike public vat; ManagerLike public cdpManager; JoinLike public saiJoin; JoinLike public wethJoin; JoinLike public daiJoin; constructor( address tub_, // SCD tub contract address address cdpManager_, // MCD manager contract address address saiJoin_, // MCD SAI collateral adapter contract address address wethJoin_, // MCD ETH collateral adapter contract address address daiJoin_ // MCD DAI adapter contract address ) public { tub = SaiTubLike(tub_); cdpManager = ManagerLike(cdpManager_); vat = VatLike(cdpManager.vat()); saiJoin = JoinLike(saiJoin_); wethJoin = JoinLike(wethJoin_); daiJoin = JoinLike(daiJoin_); require(wethJoin.gem() == tub.gem(), "non-matching-weth"); require(saiJoin.gem() == tub.sai(), "non-matching-sai"); tub.gov().approve(address(tub), uint(-1)); tub.skr().approve(address(tub), uint(-1)); tub.sai().approve(address(tub), uint(-1)); tub.sai().approve(address(saiJoin), uint(-1)); wethJoin.gem().approve(address(wethJoin), uint(-1)); daiJoin.dai().approve(address(daiJoin), uint(-1)); vat.hope(address(daiJoin)); } function add(uint x, uint y) internal pure returns (uint z) { require((z = x + y) >= x, "add-overflow"); } function sub(uint x, uint y) internal pure returns (uint z) { require((z = x - y) <= x, "sub-underflow"); } function mul(uint x, uint y) internal pure returns (uint z) { require(y == 0 || (z = x * y) / y == x, "mul-overflow"); } function toInt(uint x) internal pure returns (int y) { y = int(x); require(y >= 0, "int-overflow"); } // Function to swap SAI to DAI // This function is to be used by users that want to get new DAI in exchange of old one (aka SAI) // wad amount has to be <= the value pending to reach the debt ceiling (the minimum between general and ilk one) function swapSaiToDai( uint wad ) external { // Get wad amount of SAI from user's wallet: saiJoin.gem().transferFrom(msg.sender, address(this), wad); // Join the SAI wad amount to the `vat`: saiJoin.join(address(this), wad); // Lock the SAI wad amount to the CDP and generate the same wad amount of DAI vat.frob(saiJoin.ilk(), address(this), address(this), address(this), toInt(wad), toInt(wad)); // Send DAI wad amount as a ERC20 token to the user's wallet daiJoin.exit(msg.sender, wad); } // Function to swap DAI to SAI // This function is to be used by users that want to get SAI in exchange of DAI // wad amount has to be <= the amount of SAI locked (and DAI generated) in the migration contract SAI CDP function swapDaiToSai( uint wad ) external { // Get wad amount of DAI from user's wallet: daiJoin.dai().transferFrom(msg.sender, address(this), wad); // Join the DAI wad amount to the vat: daiJoin.join(address(this), wad); // Payback the DAI wad amount and unlocks the same value of SAI collateral vat.frob(saiJoin.ilk(), address(this), address(this), address(this), -toInt(wad), -toInt(wad)); // Send SAI wad amount as a ERC20 token to the user's wallet saiJoin.exit(msg.sender, wad); } // Function to migrate a SCD CDP to MCD one (needs to be used via a proxy so the code can be kept simpler). Check MigrationProxyActions.sol code for usage. // In order to use migrate function, SCD CDP debtAmt needs to be <= SAI previously deposited in the SAI CDP * (100% - Collateralization Ratio) function migrate( bytes32 cup ) external returns (uint cdp) { // Get values uint debtAmt = tub.tab(cup); // CDP SAI debt uint pethAmt = tub.ink(cup); // CDP locked collateral uint ethAmt = tub.bid(pethAmt); // CDP locked collateral equiv in ETH // Take SAI out from MCD SAI CDP. For this operation is necessary to have a very low collateralization ratio // This is not actually a problem as this ilk will only be accessed by this migration contract, // which will make sure to have the amounts balanced out at the end of the execution. vat.frob( bytes32(saiJoin.ilk()), address(this), address(this), address(this), -toInt(debtAmt), 0 ); saiJoin.exit(address(this), debtAmt); // SAI is exited as a token // Shut SAI CDP and gets WETH back tub.shut(cup); // CDP is closed using the SAI just exited and the MKR previously sent by the user (via the proxy call) tub.exit(pethAmt); // Converts PETH to WETH // Open future user's CDP in MCD cdp = cdpManager.open(wethJoin.ilk(), address(this)); // Join WETH to Adapter wethJoin.join(cdpManager.urns(cdp), ethAmt); // Lock WETH in future user's CDP and generate debt to compensate the SAI used to paid the SCD CDP (, uint rate,,,) = vat.ilks(wethJoin.ilk()); cdpManager.frob( cdp, toInt(ethAmt), toInt(mul(debtAmt, 10 ** 27) / rate + 1) // To avoid rounding issues we add an extra wei of debt ); // Move DAI generated to migration contract (to recover the used funds) cdpManager.move(cdp, address(this), mul(debtAmt, 10 ** 27)); // Re-balance MCD SAI migration contract's CDP vat.frob( bytes32(saiJoin.ilk()), address(this), address(this), address(this), 0, -toInt(debtAmt) ); // Set ownership of CDP to the user cdpManager.give(cdp, msg.sender); } } /** * @dev Interface of the ERC777TokensRecipient standard as defined in the EIP. * * Accounts can be notified of {IERC777} tokens being sent to them by having a * contract implement this interface (contract holders can be their own * implementer) and registering it on the * https://eips.ethereum.org/EIPS/eip-1820[ERC1820 global registry]. * * See {IERC1820Registry} and {ERC1820Implementer}. */ interface IERC777Recipient { /** * @dev Called by an {IERC777} token contract whenever tokens are being * moved or created into a registered account (`to`). The type of operation * is conveyed by `from` being the zero address or not. * * This call occurs _after_ the token contract's state is updated, so * {IERC777-balanceOf}, etc., can be used to query the post-operation state. * * This function may revert to prevent the operation from being executed. */ function tokensReceived( address operator, address from, address to, uint256 amount, bytes calldata userData, bytes calldata operatorData ) external; } /** * @title MCDAwarePool * @author Brendan Asselstine [email protected] * @notice This contract is a Pool that is aware of the new Multi-Collateral Dai. It uses the ERC777Recipient interface to * detect if it's being transferred tickets from the old single collateral Dai (Sai) Pool. If it is, it migrates the Sai to Dai * and immediately deposits the new Dai as committed tickets for that user. We are knowingly bypassing the committed period for * users to encourage them to migrate to the MCD Pool. */ contract MCDAwarePool is BasePool, IERC777Recipient { IERC1820Registry constant internal ERC1820_REGISTRY = IERC1820Registry(0x1820a4B7618BdE71Dce8cdc73aAB6C95905faD24); // keccak256("ERC777TokensRecipient") bytes32 constant internal TOKENS_RECIPIENT_INTERFACE_HASH = 0xb281fc8c12954d22544db45de3159a39272895b169a852b314f9cc762e44c53b; uint256 internal constant DEFAULT_LOCK_DURATION = 40; uint256 internal constant DEFAULT_COOLDOWN_DURATION = 80; /** * @notice The address of the ScdMcdMigration contract (see https://github.com/makerdao/developerguides/blob/master/mcd/upgrading-to-multi-collateral-dai/upgrading-to-multi-collateral-dai.md#direct-integration-with-smart-contracts) */ ScdMcdMigration public scdMcdMigration; /** * @notice The address of the Sai Pool contract */ MCDAwarePool public saiPool; /** * @notice Initializes the contract. * @param _owner The initial administrator of the contract * @param _cToken The Compound cToken to bind this Pool to * @param _feeFraction The fraction of the winnings to give to the beneficiary * @param _feeBeneficiary The beneficiary who receives the fee */ function init ( address _owner, address _cToken, uint256 _feeFraction, address _feeBeneficiary, uint256 lockDuration, uint256 cooldownDuration ) public initializer { super.init( _owner, _cToken, _feeFraction, _feeBeneficiary, lockDuration, cooldownDuration ); initRegistry(); initBlocklock(lockDuration, cooldownDuration); } /** * @notice Used to initialize the BasePool contract after an upgrade. Registers the MCDAwarePool with the ERC1820 registry so that it can receive tokens, and inits the block lock. */ function initMCDAwarePool(uint256 lockDuration, uint256 cooldownDuration) public { initRegistry(); if (blocklock.lockDuration == 0) { initBlocklock(lockDuration, cooldownDuration); } } function initRegistry() internal { ERC1820_REGISTRY.setInterfaceImplementer(address(this), TOKENS_RECIPIENT_INTERFACE_HASH, address(this)); } function initMigration(ScdMcdMigration _scdMcdMigration, MCDAwarePool _saiPool) public onlyAdmin { _initMigration(_scdMcdMigration, _saiPool); } function _initMigration(ScdMcdMigration _scdMcdMigration, MCDAwarePool _saiPool) internal { require(address(scdMcdMigration) == address(0), "Pool/init"); require(address(_scdMcdMigration) != address(0), "Pool/mig-def"); scdMcdMigration = _scdMcdMigration; saiPool = _saiPool; // may be null } /** * @notice Called by an ERC777 token when tokens are sent, transferred, or minted. If the sender is the original Sai Pool * and this pool is bound to the Dai token then it will accept the transfer, migrate the tokens, and deposit on behalf of * the sender. It will reject all other tokens. * * If there is a committed draw this function will mint the user tickets immediately, otherwise it will place them in the * open prize. This is to encourage migration. * * @param from The sender * @param amount The amount they are transferring */ function tokensReceived( address, // operator address from, address, // to address can't be anything but us because we don't implement ERC1820ImplementerInterface uint256 amount, bytes calldata, bytes calldata ) external unlessDepositsPaused { require(msg.sender == address(saiPoolToken()), "Pool/sai-only"); require(address(token()) == address(daiToken()), "Pool/not-dai"); // cash out of the Pool. This call transfers sai to this contract saiPoolToken().redeem(amount, ''); // approve of the transfer to the migration contract saiToken().approve(address(scdMcdMigration), amount); // migrate the sai to dai. The contract now has dai scdMcdMigration.swapSaiToDai(amount); if (currentCommittedDrawId() > 0) { // now deposit the dai as tickets _depositPoolFromCommitted(from, amount); } else { _depositPoolFrom(from, amount); } } /** * @notice Returns the address of the PoolSai pool token contract * @return The address of the Sai PoolToken contract */ function saiPoolToken() internal view returns (PoolToken) { if (address(saiPool) != address(0)) { return saiPool.poolToken(); } else { return PoolToken(0); } } /** * @notice Returns the address of the Sai token * @return The address of the sai token */ function saiToken() public returns (GemLike) { return scdMcdMigration.saiJoin().gem(); } /** * @notice Returns the address of the Dai token * @return The address of the Dai token. */ function daiToken() public returns (GemLike) { return scdMcdMigration.daiJoin().dai(); } }
See {IERC777-burn}. Not currently implemented. Also emits a {Transfer} event for ERC20 compatibility./
function burn(uint256, bytes calldata) external { revert("PoolToken/no-support"); }
8,015,339
pragma solidity 0.5.17; import "openzeppelin-solidity/contracts/math/SafeMath.sol"; import "openzeppelin-solidity/contracts/utils/ReentrancyGuard.sol"; import "./TokenStaking.sol"; import "./cryptography/BLS.sol"; import "./utils/AddressArrayUtils.sol"; import "./utils/PercentUtils.sol"; import "./libraries/operator/GroupSelection.sol"; import "./libraries/operator/Groups.sol"; import "./libraries/operator/DKGResultVerification.sol"; import "./libraries/operator/Reimbursements.sol"; interface ServiceContract { function entryCreated(uint256 requestId, bytes calldata entry, address payable submitter) external; function fundRequestSubsidyFeePool() external payable; function fundDkgFeePool() external payable; } /** * @title KeepRandomBeaconOperator * @dev Keep client facing contract for random beacon security-critical operations. * Handles group creation and expiration, BLS signature verification and incentives. * The contract is not upgradeable. New functionality can be implemented by deploying * new versions following Keep client update and re-authorization by the stakers. */ contract KeepRandomBeaconOperator is ReentrancyGuard { using SafeMath for uint256; using PercentUtils for uint256; using AddressArrayUtils for address[]; using GroupSelection for GroupSelection.Storage; using Groups for Groups.Storage; using DKGResultVerification for DKGResultVerification.Storage; event OnGroupRegistered(bytes groupPubKey); event DkgResultSubmittedEvent( uint256 memberIndex, bytes groupPubKey, bytes misbehaved ); event RelayEntryRequested(bytes previousEntry, bytes groupPublicKey); event RelayEntrySubmitted(); event GroupSelectionStarted(uint256 newEntry); event GroupMemberRewardsWithdrawn(address indexed beneficiary, address operator, uint256 amount, uint256 groupIndex); event RelayEntryTimeoutReported(uint256 indexed groupIndex); event UnauthorizedSigningReported(uint256 indexed groupIndex); GroupSelection.Storage groupSelection; Groups.Storage groups; DKGResultVerification.Storage dkgResultVerification; // Contract owner. address internal owner; address[] internal serviceContracts; // TODO: replace with a secure authorization protocol (addressed in RFC 11). TokenStaking internal stakingContract; // Each signing group member reward expressed in wei. uint256 public groupMemberBaseReward = 145*1e11; // 14500 Gwei, 10% of operational cost // Gas price ceiling value used to calculate the gas price for reimbursement // next to the actual gas price from the transaction. We use gas price // ceiling to defend against malicious miner-submitters who can manipulate // transaction gas price. uint256 public gasPriceCeiling = 30*1e9; // (30 Gwei = 30 * 10^9 wei) // Size of a group in the threshold relay. uint256 public groupSize = 64; // Minimum number of group members needed to interact according to the // protocol to produce a relay entry. uint256 public groupThreshold = 33; // Time in blocks after which the next group member is eligible // to submit the result. uint256 public resultPublicationBlockStep = 3; // Timeout in blocks for a relay entry to appear on the chain. Blocks are // counted from the moment relay request occur. // // Timeout is never shorter than the time needed by clients to generate // relay entry and the time it takes for the last group member to become // eligible to submit the result plus at least one block to submit it. uint256 public relayEntryTimeout = groupSize.mul(resultPublicationBlockStep); // Gas required to verify BLS signature and produce successful relay // entry. Excludes callback and DKG gas. The worst case (most expensive) // scenario. uint256 public entryVerificationGasEstimate = 280000; // Gas required to submit DKG result. Excludes initiation of group selection. uint256 public dkgGasEstimate = 1740000; // Gas required to trigger DKG (starting group selection). uint256 public groupSelectionGasEstimate = 200000; // Reimbursement for the submitter of the DKG result. This value is set when // a new DKG request comes to the operator contract. // // When submitting DKG result, the submitter is reimbursed with the actual cost // and some part of the fee stored in this field may be returned to the service // contract. uint256 public dkgSubmitterReimbursementFee; uint256 internal currentEntryStartBlock; // Seed value used for the genesis group selection. // https://www.wolframalpha.com/input/?i=pi+to+78+digits uint256 internal constant _genesisGroupSeed = 31415926535897932384626433832795028841971693993751058209749445923078164062862; // Service contract that triggered current group selection. ServiceContract internal groupSelectionStarterContract; struct SigningRequest { uint256 relayRequestId; uint256 entryVerificationAndProfitFee; uint256 callbackFee; uint256 groupIndex; bytes previousEntry; address serviceContract; } SigningRequest internal signingRequest; /** * @dev Triggers the first group selection. Genesis can be called only when * there are no groups on the operator contract. */ function genesis() public payable { require(numberOfGroups() == 0, "Groups exist"); // Set latest added service contract as a group selection starter to receive any DKG fee surplus. groupSelectionStarterContract = ServiceContract(serviceContracts[serviceContracts.length.sub(1)]); startGroupSelection(_genesisGroupSeed, msg.value); } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner == msg.sender, "Caller is not the owner"); _; } /** * @dev Checks if sender is authorized. */ modifier onlyServiceContract() { require( serviceContracts.contains(msg.sender), "Caller is not an authorized contract" ); _; } constructor(address _serviceContract, address _stakingContract) public { owner = msg.sender; serviceContracts.push(_serviceContract); stakingContract = TokenStaking(_stakingContract); groups.stakingContract = TokenStaking(_stakingContract); groups.groupActiveTime = TokenStaking(_stakingContract).undelegationPeriod(); // There are 39 blocks to submit group selection tickets. To minimize // the submitter's cost by minimizing the number of redundant tickets // that are not selected into the group, the following approach is // recommended: // // Tickets are submitted in 11 rounds, each round taking 3 blocks. // As the basic principle, the number of leading zeros in the ticket // value is subtracted from the number of rounds to determine the round // the ticket should be submitted in: // - in round 0, tickets with 11 or more leading zeros are submitted // - in round 1, tickets with 10 or more leading zeros are submitted // (...) // - in round 11, tickets with no leading zeros are submitted. // // In each round, group member candidate needs to monitor tickets // submitted by other candidates and compare them against tickets of // the candidate not yet submitted to determine if continuing with // ticket submission still makes sense. // // After 33 blocks, there is a 6 blocks mining lag allowing all // outstanding ticket submissions to have a higher chance of being // mined before the deadline. groupSelection.ticketSubmissionTimeout = 3 * 11 + 6; groupSelection.groupSize = groupSize; dkgResultVerification.timeDKG = 5*(1+5) + 2*(1+10) + 20; dkgResultVerification.resultPublicationBlockStep = resultPublicationBlockStep; dkgResultVerification.groupSize = groupSize; // TODO: For now, the required number of signatures is equal to group // threshold. This should be updated to keep a safety margin for // participants misbehaving during signing. dkgResultVerification.signatureThreshold = groupThreshold; } /** * @dev Adds service contract * @param serviceContract Address of the service contract. */ function addServiceContract(address serviceContract) public onlyOwner { serviceContracts.push(serviceContract); } /** * @dev Removes service contract * @param serviceContract Address of the service contract. */ function removeServiceContract(address serviceContract) public onlyOwner { serviceContracts.removeAddress(serviceContract); } /** * @dev Triggers the selection process of a new candidate group. * @param _newEntry New random beacon value that stakers will use to * generate their tickets. * @param submitter Operator of this contract. */ function createGroup(uint256 _newEntry, address payable submitter) public payable onlyServiceContract { uint256 groupSelectionStartFee = groupSelectionGasEstimate.mul(gasPriceCeiling); groupSelectionStarterContract = ServiceContract(msg.sender); startGroupSelection(_newEntry, msg.value.sub(groupSelectionStartFee)); // reimbursing a submitter that triggered group selection (bool success, ) = stakingContract.magpieOf(submitter).call.value(groupSelectionStartFee)(""); require(success, "Failed reimbursing submitter for starting a group selection"); } function startGroupSelection(uint256 _newEntry, uint256 _payment) internal { require( _payment >= gasPriceCeiling.mul(dkgGasEstimate), "Insufficient DKG fee" ); require(isGroupSelectionPossible(), "Group selection in progress"); // If previous group selection failed and there is reimbursement left // return it to the DKG fee pool. if (dkgSubmitterReimbursementFee > 0) { uint256 surplus = dkgSubmitterReimbursementFee; dkgSubmitterReimbursementFee = 0; ServiceContract(msg.sender).fundDkgFeePool.value(surplus)(); } groupSelection.minimumStake = stakingContract.minimumStake(); groupSelection.start(_newEntry); emit GroupSelectionStarted(_newEntry); dkgSubmitterReimbursementFee = _payment; } function isGroupSelectionPossible() public view returns (bool) { if (!groupSelection.inProgress) { return true; } // dkgTimeout is the time after key generation protocol is expected to // be complete plus the expected time to submit the result. uint256 dkgTimeout = groupSelection.ticketSubmissionStartBlock + groupSelection.ticketSubmissionTimeout + dkgResultVerification.timeDKG + groupSize * resultPublicationBlockStep; return block.number > dkgTimeout; } /** * @dev Submits ticket to request to participate in a new candidate group. * @param ticket Bytes representation of a ticket that holds the following: * - ticketValue: first 8 bytes of a result of keccak256 cryptography hash * function on the combination of the group selection seed (previous * beacon output), staker-specific value (address) and virtual staker index. * - stakerValue: a staker-specific value which is the address of the staker. * - virtualStakerIndex: 4-bytes number within a range of 1 to staker's weight; * has to be unique for all tickets submitted by the given staker for the * current candidate group selection. */ function submitTicket(bytes32 ticket) public { uint256 stakingWeight = stakingContract.eligibleStake(msg.sender, address(this)).div(groupSelection.minimumStake); groupSelection.submitTicket(ticket, stakingWeight); } /** * @dev Gets the timeout in blocks after which group candidate ticket * submission is finished. */ function ticketSubmissionTimeout() public view returns (uint256) { return groupSelection.ticketSubmissionTimeout; } /** * @dev Gets the submitted group candidate tickets so far. */ function submittedTickets() public view returns (uint64[] memory) { return groupSelection.tickets; } /** * @dev Gets selected participants in ascending order of their tickets. */ function selectedParticipants() public view returns (address[] memory) { return groupSelection.selectedParticipants(); } /** * @dev Submits result of DKG protocol. It is on-chain part of phase 14 of * the protocol. * * @param submitterMemberIndex Claimed submitter candidate group member index * @param groupPubKey Generated candidate group public key * @param misbehaved Bytes array of misbehaved (disqualified or inactive) * group members indexes in ascending order; Indexes reflect positions of * members in the group as outputted by the group selection protocol. * @param signatures Concatenation of signatures from members supporting the * result. * @param signingMembersIndexes Indices of members corresponding to each * signature. */ function submitDkgResult( uint256 submitterMemberIndex, bytes memory groupPubKey, bytes memory misbehaved, bytes memory signatures, uint[] memory signingMembersIndexes ) public { address[] memory members = selectedParticipants(); dkgResultVerification.verify( submitterMemberIndex, groupPubKey, misbehaved, signatures, signingMembersIndexes, members, groupSelection.ticketSubmissionStartBlock + groupSelection.ticketSubmissionTimeout ); groups.setGroupMembers(groupPubKey, members, misbehaved); groups.addGroup(groupPubKey); reimburseDkgSubmitter(); emit DkgResultSubmittedEvent(submitterMemberIndex, groupPubKey, misbehaved); groupSelection.stop(); } /** * @dev Compare the reimbursement fee calculated based on the current transaction gas * price and the current price feed estimate with the DKG reimbursement fee calculated * and paid at the moment when the DKG was requested. If there is any surplus, it will * be returned to the DKG fee pool of the service contract which triggered the DKG. */ function reimburseDkgSubmitter() internal { uint256 gasPrice = gasPriceCeiling; // We need to check if tx.gasprice is non-zero as a workaround to a bug // in go-ethereum: // https://github.com/ethereum/go-ethereum/pull/20189 if (tx.gasprice > 0 && tx.gasprice < gasPriceCeiling) { gasPrice = tx.gasprice; } uint256 reimbursementFee = dkgGasEstimate.mul(gasPrice); address payable magpie = stakingContract.magpieOf(msg.sender); if (reimbursementFee < dkgSubmitterReimbursementFee) { uint256 surplus = dkgSubmitterReimbursementFee.sub(reimbursementFee); dkgSubmitterReimbursementFee = 0; // Reimburse submitter with actual DKG cost. magpie.call.value(reimbursementFee)(""); // Return surplus to the contract that started DKG. groupSelectionStarterContract.fundDkgFeePool.value(surplus)(); } else { // If submitter used higher gas price reimburse only dkgSubmitterReimbursementFee max. reimbursementFee = dkgSubmitterReimbursementFee; dkgSubmitterReimbursementFee = 0; magpie.call.value(reimbursementFee)(""); } } /** * @dev Creates a request to generate a new relay entry, which will include a * random number (by signing the previous entry's random number). * @param requestId Request Id trackable by service contract * @param previousEntry Previous relay entry */ function sign( uint256 requestId, bytes memory previousEntry ) public payable onlyServiceContract { uint256 entryVerificationAndProfitFee = groupProfitFee().add( entryVerificationFee() ); require( msg.value >= entryVerificationAndProfitFee, "Insufficient new entry fee" ); uint256 callbackFee = msg.value.sub(entryVerificationAndProfitFee); signRelayEntry( requestId, previousEntry, msg.sender, entryVerificationAndProfitFee, callbackFee ); } function signRelayEntry( uint256 requestId, bytes memory previousEntry, address serviceContract, uint256 entryVerificationAndProfitFee, uint256 callbackFee ) internal { require(!isEntryInProgress() || hasEntryTimedOut(), "Beacon is busy"); currentEntryStartBlock = block.number; uint256 groupIndex = groups.selectGroup(uint256(keccak256(previousEntry))); signingRequest = SigningRequest( requestId, entryVerificationAndProfitFee, callbackFee, groupIndex, previousEntry, serviceContract ); bytes memory groupPubKey = groups.getGroupPublicKey(groupIndex); emit RelayEntryRequested(previousEntry, groupPubKey); } /** * @dev Creates a new relay entry and stores the associated data on the chain. * @param _groupSignature Group BLS signature over the concatenation of the * previous entry and seed. */ function relayEntry(bytes memory _groupSignature) public nonReentrant { require(isEntryInProgress(), "Entry was submitted"); require(!hasEntryTimedOut(), "Entry timed out"); bytes memory groupPubKey = groups.getGroupPublicKey(signingRequest.groupIndex); require( BLS.verify( groupPubKey, signingRequest.previousEntry, _groupSignature ), "Invalid signature" ); emit RelayEntrySubmitted(); // Spend no more than groupSelectionGasEstimate + 40000 gas max // This will prevent relayEntry failure in case the service contract is compromised signingRequest.serviceContract.call.gas(groupSelectionGasEstimate.add(40000))( abi.encodeWithSignature( "entryCreated(uint256,bytes,address)", signingRequest.relayRequestId, _groupSignature, msg.sender ) ); if (signingRequest.callbackFee > 0) { executeCallback(signingRequest, uint256(keccak256(_groupSignature))); } (uint256 groupMemberReward, uint256 submitterReward, uint256 subsidy) = newEntryRewardsBreakdown(); groups.addGroupMemberReward(groupPubKey, groupMemberReward); stakingContract.magpieOf(msg.sender).call.value(submitterReward)(""); if (subsidy > 0) { signingRequest.serviceContract.call.gas(35000).value(subsidy)(abi.encodeWithSignature("fundRequestSubsidyFeePool()")); } currentEntryStartBlock = 0; } /** * @dev Executes customer specified callback for the relay entry request. * @param signingRequest Request data tracked internally by this contract. * @param entry The generated random number. */ function executeCallback(SigningRequest memory signingRequest, uint256 entry) internal { uint256 callbackFee = signingRequest.callbackFee; // Make sure not to spend more than what was received from the service // contract for the callback uint256 gasLimit = callbackFee.div(gasPriceCeiling); bytes memory callbackReturnData; uint256 gasBeforeCallback = gasleft(); (, callbackReturnData) = signingRequest.serviceContract.call.gas( gasLimit )(abi.encodeWithSignature( "executeCallback(uint256,uint256)", signingRequest.relayRequestId, entry )); uint256 gasAfterCallback = gasleft(); uint256 gasSpent = gasBeforeCallback.sub(gasAfterCallback); Reimbursements.reimburseCallback( stakingContract, gasPriceCeiling, gasLimit, gasSpent, callbackFee, callbackReturnData ); } /** * @dev Get rewards breakdown in wei for successful entry for the current signing request. */ function newEntryRewardsBreakdown() internal view returns(uint256 groupMemberReward, uint256 submitterReward, uint256 subsidy) { uint256 decimals = 1e16; // Adding 16 decimals to perform float division. uint256 delayFactor = getDelayFactor(); groupMemberReward = groupMemberBaseReward.mul(delayFactor).div(decimals); // delay penalty = base reward * (1 - delay factor) uint256 groupMemberDelayPenalty = groupMemberBaseReward.mul(decimals.sub(delayFactor)); // The submitter reward consists of: // The callback gas expenditure (reimbursed by the service contract) // The entry verification fee to cover the cost of verifying the submission, // paid regardless of their gas expenditure // Submitter extra reward - 5% of the delay penalties of the entire group uint256 submitterExtraReward = groupMemberDelayPenalty.mul(groupSize).percent(5).div(decimals); uint256 entryVerificationFee = signingRequest.entryVerificationAndProfitFee.sub(groupProfitFee()); submitterReward = entryVerificationFee.add(submitterExtraReward); // Rewards not paid out to the operators are paid out to requesters to subsidize new requests. subsidy = groupProfitFee().sub(groupMemberReward.mul(groupSize)).sub(submitterExtraReward); } /** * @dev Gets delay factor for rewards calculation. * @return Integer representing floating-point number with 16 decimals places. */ function getDelayFactor() internal view returns(uint256 delayFactor) { uint256 decimals = 1e16; // Adding 16 decimals to perform float division. // T_deadline is the earliest block when no submissions are accepted // and an entry timed out. The last block the entry can be published in is // currentEntryStartBlock + relayEntryTimeout // and submission are no longer accepted from block // currentEntryStartBlock + relayEntryTimeout + 1. uint256 deadlineBlock = currentEntryStartBlock.add(relayEntryTimeout).add(1); // T_begin is the earliest block the result can be published in. // Relay entry can be generated instantly after relay request is // registered on-chain so a new entry can be published at the next // block the earliest. uint256 submissionStartBlock = currentEntryStartBlock.add(1); // Use submissionStartBlock block as entryReceivedBlock if entry submitted earlier than expected. uint256 entryReceivedBlock = block.number <= submissionStartBlock ? submissionStartBlock:block.number; // T_remaining = T_deadline - T_received uint256 remainingBlocks = deadlineBlock.sub(entryReceivedBlock); // T_deadline - T_begin uint256 submissionWindow = deadlineBlock.sub(submissionStartBlock); // delay factor = [ T_remaining / (T_deadline - T_begin)]^2 // // Since we add 16 decimal places to perform float division, we do: // delay factor = [ T_temaining * decimals / (T_deadline - T_begin)]^2 / decimals = // = [T_remaining / (T_deadline - T_begin) ]^2 * decimals delayFactor = ((remainingBlocks.mul(decimals).div(submissionWindow))**2).div(decimals); } /** * @dev Returns true if generation of a new relay entry is currently in * progress. */ function isEntryInProgress() internal view returns (bool) { return currentEntryStartBlock != 0; } /** * @dev Returns true if the currently ongoing new relay entry generation * operation timed out. There is a certain timeout for a new relay entry * to be produced, see `relayEntryTimeout` value. */ function hasEntryTimedOut() internal view returns (bool) { return currentEntryStartBlock != 0 && block.number > currentEntryStartBlock + relayEntryTimeout; } /** * @dev Function used to inform about the fact the currently ongoing * new relay entry generation operation timed out. As a result, the group * which was supposed to produce a new relay entry is immediately * terminated and a new group is selected to produce a new relay entry. * All members of the group are punished by seizing minimum stake of * their tokens. The submitter of the transaction is rewarded with a * tattletale reward which is limited to min(1, 20 / group_size) of the * maximum tattletale reward. */ function reportRelayEntryTimeout() public { require(hasEntryTimedOut(), "Entry did not time out"); uint256 minimumStake = stakingContract.minimumStake(); groups.reportRelayEntryTimeout(signingRequest.groupIndex, groupSize, minimumStake); // We could terminate the last active group. If that's the case, // do not try to execute signing again because there is no group // which can handle it. if (numberOfGroups() > 0) { signRelayEntry( signingRequest.relayRequestId, signingRequest.previousEntry, signingRequest.serviceContract, signingRequest.entryVerificationAndProfitFee, signingRequest.callbackFee ); } emit RelayEntryTimeoutReported(signingRequest.groupIndex); } /** * @dev Gets group profit fee expressed in wei. */ function groupProfitFee() public view returns(uint256) { return groupMemberBaseReward.mul(groupSize); } /** * @dev Checks if the specified account has enough active stake to become * network operator and that this contract has been authorized for potential * slashing. * * Having the required minimum of active stake makes the operator eligible * to join the network. If the active stake is not currently undelegating, * operator is also eligible for work selection. * * @param staker Staker's address * @return True if has enough active stake to participate in the network, * false otherwise. */ function hasMinimumStake(address staker) public view returns(bool) { return stakingContract.hasMinimumStake(staker, address(this)); } /** * @dev Checks if group with the given public key is registered. */ function isGroupRegistered(bytes memory groupPubKey) public view returns(bool) { return groups.isGroupRegistered(groupPubKey); } /** * @dev Checks if a group with the given public key is a stale group. * Stale group is an expired group which is no longer performing any * operations. It is important to understand that an expired group may * still perform some operations for which it was selected when it was still * active. We consider a group to be stale when it's expired and when its * expiration time and potentially executed operation timeout are both in * the past. */ function isStaleGroup(bytes memory groupPubKey) public view returns(bool) { return groups.isStaleGroup(groupPubKey); } /** * @dev Gets the number of active groups. Expired and terminated groups are * not counted as active. */ function numberOfGroups() public view returns(uint256) { return groups.numberOfGroups(); } /** * @dev Returns accumulated group member rewards for provided group. */ function getGroupMemberRewards(bytes memory groupPubKey) public view returns (uint256) { return groups.groupMemberRewards[groupPubKey]; } /** * @dev Gets all indices in the provided group for a member. */ function getGroupMemberIndices(bytes memory groupPubKey, address member) public view returns (uint256[] memory indices) { return groups.getGroupMemberIndices(groupPubKey, member); } /** * @dev Withdraws accumulated group member rewards for operator * using the provided group index and member indices. Once the * accumulated reward is withdrawn from the selected group, member is * removed from it. Rewards can be withdrawn only from stale group. * @param operator Operator address. * @param groupIndex Group index. * @param groupMemberIndices Array of member indices for the group member. */ function withdrawGroupMemberRewards(address operator, uint256 groupIndex, uint256[] memory groupMemberIndices) public nonReentrant { uint256 accumulatedRewards = groups.withdrawFromGroup(operator, groupIndex, groupMemberIndices); (bool success, ) = stakingContract.magpieOf(operator).call.value(accumulatedRewards)(""); if (success) { emit GroupMemberRewardsWithdrawn(stakingContract.magpieOf(operator), operator, accumulatedRewards, groupIndex); } } /** * @dev Gets the index of the first active group. */ function getFirstActiveGroupIndex() public view returns (uint256) { return groups.expiredGroupOffset; } /** * @dev Gets group public key. */ function getGroupPublicKey(uint256 groupIndex) public view returns (bytes memory) { return groups.getGroupPublicKey(groupIndex); } /** * @dev Returns fee for entry verification in wei. Does not include group * profit fee, DKG contribution or callback fee. */ function entryVerificationFee() public view returns (uint256) { return entryVerificationGasEstimate.mul(gasPriceCeiling); } /** * @dev Returns fee for group creation in wei. Includes the cost of DKG * and the cost of triggering group selection. */ function groupCreationFee() public view returns (uint256) { return dkgGasEstimate.add(groupSelectionGasEstimate).mul(gasPriceCeiling); } /** * @dev Returns members of the given group by group public key. */ function getGroupMembers(bytes memory groupPubKey) public view returns (address[] memory members) { return groups.getGroupMembers(groupPubKey); } /** * @dev Reports unauthorized signing for the provided group. Must provide * a valid signature of the tattletale address as a message. Successful signature * verification means the private key has been leaked and all group members * should be punished by seizing their tokens. The submitter of this proof is * rewarded with 5% of the total seized amount scaled by the reward adjustment * parameter and the rest 95% is burned. */ function reportUnauthorizedSigning( uint256 groupIndex, bytes memory signedMsgSender ) public { uint256 minimumStake = stakingContract.minimumStake(); groups.reportUnauthorizedSigning(groupIndex, signedMsgSender, minimumStake); emit UnauthorizedSigningReported(groupIndex); } }
Removes service contract serviceContract Address of the service contract./
function removeServiceContract(address serviceContract) public onlyOwner { serviceContracts.removeAddress(serviceContract); }
1,840,269
/** *Submitted for verification at Etherscan.io on 2022-02-04 */ /** *Submitted for verification at Etherscan.io on 2022-01-27 */ /** *Submitted for verification at BscScan.com on 2021-10-07 */ // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with 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. */ 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"); } /** * @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; } } 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 Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721 is IERC165 { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes calldata data ) external; } /** * @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); } /** * @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); } /** * @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); } } } } /** * @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); } } /** * @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 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; struct NFT{ uint256 price; address payable ownerAddress; address payable creatorAddress; bool sell; } mapping(uint256=>NFT) public NFTINFO; /** * @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"); NFTINFO[tokenId].sell=false; NFTINFO[tokenId].ownerAddress=payable(to); _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"); NFTINFO[tokenId].sell=false; NFTINFO[tokenId].ownerAddress=payable(to); _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 {} } /** * @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); } /** * @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(); } } contract BlackLkisted is Ownable { mapping(address=>bool) isBlacklisted; function blackList(address _user) public onlyOwner { require(!isBlacklisted[_user], "user already blacklisted"); isBlacklisted[_user] = true; // emit events as well } function removeFromBlacklist(address _user) public onlyOwner { require(isBlacklisted[_user], "user already whitelisted"); isBlacklisted[_user] = false; // emit events as well } } contract Whitelist is BlackLkisted { mapping(address => bool) whitelist; event AddedToWhitelist(address indexed account); event RemovedFromWhitelist(address indexed account); modifier onlyWhitelisted() { require(isWhitelisted(msg.sender)); _; } function addToWhiteList(address _address) public onlyOwner { whitelist[_address] = true; emit AddedToWhitelist(_address); } function removeToWhiteList(address _address) public onlyOwner { whitelist[_address] = false; emit RemovedFromWhitelist(_address); } function isWhitelisted(address _address) public view returns(bool) { return whitelist[_address]; } } pragma solidity >=0.6.2 <0.8.0; contract Bookiez is ERC721Enumerable, Whitelist { using SafeMath for uint256; uint256 public constant MAX_SUPPLY = 3999; string private _baseTokenURI = "ipfs://QmYrJ79U4WGH8Fb2X61KWQVBfBiYVtzvw6MKzpxH4ypeuB/"; string public notRevealedUri="ipfs://QmPFhG2A2h8uMj1xuSC334DHpqbGR2amLFG6FwmSG5MUWM/"; address payable public adminAddress; address payable public developmentAddress; bool public hasSaleStarted = true; uint256 public developmentFees; uint256 public adminFees; uint256 public artistFees; uint256 public floorPrice; uint256 public floorPriceWhiteListed; uint256 public maxMint=20; bool public revealed = false; constructor() ERC721("Bookiez", "Bookiez") { developmentAddress = payable(0x6466D51E667dB0748f16009D4d56ABBE34f90Ec9); developmentFees=3; adminFees=4; artistFees=3; floorPrice=0.08 ether; floorPriceWhiteListed=0.05 ether; } function setBaseURI(string memory baseURI) public onlyOwner { _baseTokenURI = baseURI; } // Start Sale, we can start minting! function startSale() public onlyOwner { hasSaleStarted = true; } // Pause Sale function pauseSale() public onlyOwner { hasSaleStarted = false; } // Function for set the Development Fees function setContractFees(uint256 _developmentFees,uint256 _sellingFees,uint256 _artistFees) public onlyOwner { developmentFees=_developmentFees; adminFees=_sellingFees; artistFees=_artistFees; } // Function for set the Development Address function setDevelopmentAddress(address payable _developmentAddress) public onlyOwner { developmentAddress=_developmentAddress; } function _baseURI() internal view virtual override returns (string memory) { return _baseTokenURI; } function setFloorPrice(uint256 FloorPrice,uint256 _floorPriceWhiteListed) public onlyOwner{ floorPrice=FloorPrice; floorPriceWhiteListed=_floorPriceWhiteListed; } function getBaseURI() public view returns (string memory) { return _baseTokenURI; } function setNotRevealedURI(string memory _notRevealedURI) public onlyOwner { notRevealedUri = _notRevealedURI; } function reveal() public onlyOwner { revealed = true; } function tokenURI(uint256 _tokenId) public view override returns (string memory) { uint256 totalSupply = totalSupply(); string memory json =".json"; require(_tokenId <= totalSupply, "That token hasn't been minted yet"); if(revealed == false) { return string(abi.encodePacked(notRevealedUri, Strings.toString(_tokenId),json)); } return string(abi.encodePacked(_baseTokenURI, Strings.toString(_tokenId),json)); } function setMaxMint(uint256 _maximum) public onlyOwner returns(bool){ maxMint = _maximum; return true; } function setTokenPrice(uint256 price,uint256 tokenId,bool sell) public { require(msg.sender==NFTINFO[tokenId].ownerAddress,"Only NFT Owner Can Set The Price"); NFTINFO[tokenId].price=price; NFTINFO[tokenId].sell=sell; } function walletOfOwner(address _owner) public view returns (uint256[] memory) { uint256 ownerTokenCount = balanceOf(_owner); uint256[] memory tokenIds = new uint256[](ownerTokenCount); for (uint256 i; i < ownerTokenCount; i++) { tokenIds[i] = tokenOfOwnerByIndex(_owner, i); } return tokenIds; } /* *@dev mint Fucntion is to mint the NFTS @dev _count is the number of NFTS you want to Mint */ function mint(uint256 _count) public payable { uint256 totalSupply = totalSupply(); require(!isBlacklisted[msg.sender], "caller is backlisted"); require(hasSaleStarted == true, "Sale hasn't started"); require(totalSupply <= MAX_SUPPLY, "Sold out"); require(totalSupply + _count <= MAX_SUPPLY, "Not enough tokens left"); require(_count <= maxMint, "Mint 20 or fewer, please."); if(isWhitelisted(msg.sender)){ require(msg.value >= _count.mul(floorPriceWhiteListed), "The value submitted with this transaction is too low FOr whitelisted user."); }else{ require(msg.value >= _count.mul(floorPrice), "The value submitted with this transaction is too low."); } payable(owner()).transfer(msg.value); for (uint256 i=1; i <=_count; i++) { _safeMint(msg.sender, totalSupply + i); NFTINFO[totalSupply + i].price=floorPrice; NFTINFO[totalSupply + i].ownerAddress=msg.sender; NFTINFO[totalSupply + i].creatorAddress=msg.sender; NFTINFO[totalSupply + i].sell=false; } } /* *@dev buy Fucntion is for buy Fixed Price NFT @dev tokenId is the token id of the NFT for buy */ function buy(uint256 tokenId) public payable{ require(!isBlacklisted[msg.sender], "caller is backlisted"); require(msg.value>=NFTINFO[tokenId].price," Low BNB Amount :("); uint256 owneFees=((uint256(100).sub(artistFees)).sub(adminFees)).sub(developmentFees); address payable ownerAddress= payable(address(uint160(ownerOf(tokenId)))); NFTINFO[tokenId].creatorAddress.transfer((msg.value.mul(artistFees)).div(100)); adminAddress.transfer((msg.value.mul(adminFees)).div(100)); developmentAddress.transfer((msg.value.mul(developmentFees)).div(100)); ownerAddress.transfer((msg.value.mul(owneFees)).div(100)); _transfer(ownerAddress,msg.sender,tokenId); NFTINFO[tokenId].price=floorPrice; NFTINFO[tokenId].ownerAddress=msg.sender; NFTINFO[tokenId].sell=false; } function reserveGiveaway(uint256 _count) public onlyOwner { uint currentSupply = totalSupply(); require(_count > 0 && _count <= 100, "Max 100 to reserve at once"); require(totalSupply().add(_count) <= MAX_SUPPLY, "Exceeds MAX_Bookiez"); require(hasSaleStarted == false, "Sale has already started"); uint256 index; // Reserved for people who helped this project and giveaways for (index = 0; index < _count; index++) { _safeMint(owner(), currentSupply + index); } } }
Function for set the Development Address
function setDevelopmentAddress(address payable _developmentAddress) public onlyOwner { developmentAddress=_developmentAddress; }
6,303,562
pragma solidity ^0.5.16; import "./ComptrollerInterface.sol"; import "./CTokenInterfaces.sol"; import "./ErrorReporter.sol"; import "./Exponential.sol"; import "./EIP20Interface.sol"; import "./EIP20NonStandardInterface.sol"; import "./InterestRateModel.sol"; /** * @title Compound's CToken Contract * @notice Abstract base for CTokens * @author Compound */ contract CToken is CTokenInterface, Exponential, TokenErrorReporter { /** * @notice Initialize the money market * @param comptroller_ The address of the Comptroller * @param interestRateModel_ The address of the interest rate model * @param initialExchangeRateMantissa_ The initial exchange rate, scaled by 1e18 * @param name_ EIP-20 name of this token * @param symbol_ EIP-20 symbol of this token * @param decimals_ EIP-20 decimal precision of this token */ function initialize( ComptrollerInterface comptroller_, InterestRateModel interestRateModel_, uint256 initialExchangeRateMantissa_, string memory name_, string memory symbol_, uint8 decimals_ ) public { require(msg.sender == admin, "admin only"); require(accrualBlockNumber == 0 && borrowIndex == 0, "initialized"); // Set initial exchange rate initialExchangeRateMantissa = initialExchangeRateMantissa_; require(initialExchangeRateMantissa > 0, "invalid exchange rate"); // Set the comptroller uint256 err = _setComptroller(comptroller_); require(err == uint256(Error.NO_ERROR), "failed to set comptroller"); // Initialize block number and borrow index (block number mocks depend on comptroller being set) accrualBlockNumber = getBlockNumber(); borrowIndex = mantissaOne; // Set the interest rate model (depends on block number / borrow index) err = _setInterestRateModelFresh(interestRateModel_); require(err == uint256(Error.NO_ERROR), "failed to set IRM"); name = name_; symbol = symbol_; decimals = decimals_; // The counter starts true to prevent changing it from zero to non-zero (i.e. smaller cost/refund) _notEntered = true; } /** * @notice Transfer `amount` tokens from `msg.sender` to `dst` * @param dst The address of the destination account * @param amount The number of tokens to transfer * @return Whether or not the transfer succeeded */ function transfer(address dst, uint256 amount) external nonReentrant returns (bool) { return transferTokens(msg.sender, msg.sender, dst, amount) == uint256(Error.NO_ERROR); } /** * @notice Transfer `amount` tokens from `src` to `dst` * @param src The address of the source account * @param dst The address of the destination account * @param amount The number of tokens to transfer * @return Whether or not the transfer succeeded */ function transferFrom( address src, address dst, uint256 amount ) external nonReentrant returns (bool) { return transferTokens(msg.sender, src, dst, amount) == uint256(Error.NO_ERROR); } /** * @notice Approve `spender` to transfer up to `amount` from `src` * @dev This will overwrite the approval amount for `spender` * and is subject to issues noted [here](https://eips.ethereum.org/EIPS/eip-20#approve) * @param spender The address of the account which may transfer tokens * @param amount The number of tokens that are approved (-1 means infinite) * @return Whether or not the approval succeeded */ function approve(address spender, uint256 amount) external returns (bool) { address src = msg.sender; transferAllowances[src][spender] = amount; emit Approval(src, spender, amount); return true; } /** * @notice Get the current allowance from `owner` for `spender` * @param owner The address of the account which owns the tokens to be spent * @param spender The address of the account which may transfer tokens * @return The number of tokens allowed to be spent (-1 means infinite) */ function allowance(address owner, address spender) external view returns (uint256) { return transferAllowances[owner][spender]; } /** * @notice Get the token balance of the `owner` * @param owner The address of the account to query * @return The number of tokens owned by `owner` */ function balanceOf(address owner) external view returns (uint256) { return accountTokens[owner]; } /** * @notice Get the underlying balance of the `owner` * @dev This also accrues interest in a transaction * @param owner The address of the account to query * @return The amount of underlying owned by `owner` */ function balanceOfUnderlying(address owner) external returns (uint256) { Exp memory exchangeRate = Exp({mantissa: exchangeRateCurrent()}); return mul_ScalarTruncate(exchangeRate, accountTokens[owner]); } /** * @notice Get a snapshot of the account's balances, and the cached exchange rate * @dev This is used by comptroller to more efficiently perform liquidity checks. * @param account Address of the account to snapshot * @return (possible error, token balance, borrow balance, exchange rate mantissa) */ function getAccountSnapshot(address account) external view returns ( uint256, uint256, uint256, uint256 ) { uint256 cTokenBalance = getCTokenBalanceInternal(account); uint256 borrowBalance = borrowBalanceStoredInternal(account); uint256 exchangeRateMantissa = exchangeRateStoredInternal(); return (uint256(Error.NO_ERROR), cTokenBalance, borrowBalance, exchangeRateMantissa); } /** * @dev Function to simply retrieve block number * This exists mainly for inheriting test contracts to stub this result. */ function getBlockNumber() internal view returns (uint256) { return block.number; } /** * @notice Returns the current per-block borrow interest rate for this cToken * @return The borrow interest rate per block, scaled by 1e18 */ function borrowRatePerBlock() external view returns (uint256) { return interestRateModel.getBorrowRate(getCashPrior(), totalBorrows, totalReserves); } /** * @notice Returns the current per-block supply interest rate for this cToken * @return The supply interest rate per block, scaled by 1e18 */ function supplyRatePerBlock() external view returns (uint256) { return interestRateModel.getSupplyRate(getCashPrior(), totalBorrows, totalReserves, reserveFactorMantissa); } /** * @notice Returns the estimated per-block borrow interest rate for this cToken after some change * @return The borrow interest rate per block, scaled by 1e18 */ function estimateBorrowRatePerBlockAfterChange(uint256 change, bool repay) external view returns (uint256) { uint256 cashPriorNew; uint256 totalBorrowsNew; if (repay) { cashPriorNew = add_(getCashPrior(), change); totalBorrowsNew = sub_(totalBorrows, change); } else { cashPriorNew = sub_(getCashPrior(), change); totalBorrowsNew = add_(totalBorrows, change); } return interestRateModel.getBorrowRate(cashPriorNew, totalBorrowsNew, totalReserves); } /** * @notice Returns the estimated per-block supply interest rate for this cToken after some change * @return The supply interest rate per block, scaled by 1e18 */ function estimateSupplyRatePerBlockAfterChange(uint256 change, bool repay) external view returns (uint256) { uint256 cashPriorNew; uint256 totalBorrowsNew; if (repay) { cashPriorNew = add_(getCashPrior(), change); totalBorrowsNew = sub_(totalBorrows, change); } else { cashPriorNew = sub_(getCashPrior(), change); totalBorrowsNew = add_(totalBorrows, change); } return interestRateModel.getSupplyRate(cashPriorNew, totalBorrowsNew, totalReserves, reserveFactorMantissa); } /** * @notice Returns the current total borrows plus accrued interest * @return The total borrows with interest */ function totalBorrowsCurrent() external nonReentrant returns (uint256) { accrueInterest(); return totalBorrows; } /** * @notice Accrue interest to updated borrowIndex and then calculate account's borrow balance using the updated borrowIndex * @param account The address whose balance should be calculated after updating borrowIndex * @return The calculated balance */ function borrowBalanceCurrent(address account) external nonReentrant returns (uint256) { accrueInterest(); return borrowBalanceStored(account); } /** * @notice Return the borrow balance of account based on stored data * @param account The address whose balance should be calculated * @return The calculated balance */ function borrowBalanceStored(address account) public view returns (uint256) { return borrowBalanceStoredInternal(account); } /** * @notice Return the borrow balance of account based on stored data * @param account The address whose balance should be calculated * @return the calculated balance or 0 if error code is non-zero */ function borrowBalanceStoredInternal(address account) internal view returns (uint256) { /* Get borrowBalance and borrowIndex */ BorrowSnapshot storage borrowSnapshot = accountBorrows[account]; /* If borrowBalance = 0 then borrowIndex is likely also 0. * Rather than failing the calculation with a division by 0, we immediately return 0 in this case. */ if (borrowSnapshot.principal == 0) { return 0; } /* Calculate new borrow balance using the interest index: * recentBorrowBalance = borrower.borrowBalance * market.borrowIndex / borrower.borrowIndex */ uint256 principalTimesIndex = mul_(borrowSnapshot.principal, borrowIndex); uint256 result = div_(principalTimesIndex, borrowSnapshot.interestIndex); return result; } /** * @notice Accrue interest then return the up-to-date exchange rate * @return Calculated exchange rate scaled by 1e18 */ function exchangeRateCurrent() public nonReentrant returns (uint256) { accrueInterest(); return exchangeRateStored(); } /** * @notice Calculates the exchange rate from the underlying to the CToken * @dev This function does not accrue interest before calculating the exchange rate * @return Calculated exchange rate scaled by 1e18 */ function exchangeRateStored() public view returns (uint256) { return exchangeRateStoredInternal(); } /** * @notice Calculates the exchange rate from the underlying to the CToken * @dev This function does not accrue interest before calculating the exchange rate * @return calculated exchange rate scaled by 1e18 */ function exchangeRateStoredInternal() internal view returns (uint256) { uint256 _totalSupply = totalSupply; if (_totalSupply == 0) { /* * If there are no tokens minted: * exchangeRate = initialExchangeRate */ return initialExchangeRateMantissa; } else { /* * Otherwise: * exchangeRate = (totalCash + totalBorrows - totalReserves) / totalSupply */ uint256 totalCash = getCashPrior(); uint256 cashPlusBorrowsMinusReserves = sub_(add_(totalCash, totalBorrows), totalReserves); uint256 exchangeRate = div_(cashPlusBorrowsMinusReserves, Exp({mantissa: _totalSupply})); return exchangeRate; } } /** * @notice Get cash balance of this cToken in the underlying asset * @return The quantity of underlying asset owned by this contract */ function getCash() external view returns (uint256) { return getCashPrior(); } /** * @notice Applies accrued interest to total borrows and reserves * @dev This calculates interest accrued from the last checkpointed block * up to the current block and writes new checkpoint to storage. */ function accrueInterest() public returns (uint256) { /* Remember the initial block number */ uint256 currentBlockNumber = getBlockNumber(); uint256 accrualBlockNumberPrior = accrualBlockNumber; /* Short-circuit accumulating 0 interest */ if (accrualBlockNumberPrior == currentBlockNumber) { return uint256(Error.NO_ERROR); } /* Read the previous values out of storage */ uint256 cashPrior = getCashPrior(); uint256 borrowsPrior = totalBorrows; uint256 reservesPrior = totalReserves; uint256 borrowIndexPrior = borrowIndex; /* Calculate the current borrow interest rate */ uint256 borrowRateMantissa = interestRateModel.getBorrowRate(cashPrior, borrowsPrior, reservesPrior); require(borrowRateMantissa <= borrowRateMaxMantissa, "borrow rate too high"); /* Calculate the number of blocks elapsed since the last accrual */ uint256 blockDelta = sub_(currentBlockNumber, accrualBlockNumberPrior); /* * Calculate the interest accumulated into borrows and reserves and the new index: * simpleInterestFactor = borrowRate * blockDelta * interestAccumulated = simpleInterestFactor * totalBorrows * totalBorrowsNew = interestAccumulated + totalBorrows * totalReservesNew = interestAccumulated * reserveFactor + totalReserves * borrowIndexNew = simpleInterestFactor * borrowIndex + borrowIndex */ Exp memory simpleInterestFactor = mul_(Exp({mantissa: borrowRateMantissa}), blockDelta); uint256 interestAccumulated = mul_ScalarTruncate(simpleInterestFactor, borrowsPrior); uint256 totalBorrowsNew = add_(interestAccumulated, borrowsPrior); uint256 totalReservesNew = mul_ScalarTruncateAddUInt( Exp({mantissa: reserveFactorMantissa}), interestAccumulated, reservesPrior ); uint256 borrowIndexNew = mul_ScalarTruncateAddUInt(simpleInterestFactor, borrowIndexPrior, borrowIndexPrior); ///////////////////////// // EFFECTS & INTERACTIONS // (No safe failures beyond this point) /* We write the previously calculated values into storage */ accrualBlockNumber = currentBlockNumber; borrowIndex = borrowIndexNew; totalBorrows = totalBorrowsNew; totalReserves = totalReservesNew; /* We emit an AccrueInterest event */ emit AccrueInterest(cashPrior, interestAccumulated, borrowIndexNew, totalBorrowsNew); return uint256(Error.NO_ERROR); } /** * @notice Sender supplies assets into the market and receives cTokens in exchange * @dev Accrues interest whether or not the operation succeeds, unless reverted * @param mintAmount The amount of the underlying asset to supply * @param isNative The amount is in native or not * @return (uint, uint) An error code (0=success, otherwise a failure, see ErrorReporter.sol), and the actual mint amount. */ function mintInternal(uint256 mintAmount, bool isNative) internal nonReentrant returns (uint256, uint256) { accrueInterest(); // mintFresh emits the actual Mint event if successful and logs on errors, so we don't need to return mintFresh(msg.sender, mintAmount, isNative); } /** * @notice Sender redeems cTokens in exchange for the underlying asset * @dev Accrues interest whether or not the operation succeeds, unless reverted * @param redeemTokens The number of cTokens to redeem into underlying * @param isNative The amount is in native or not * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function redeemInternal(uint256 redeemTokens, bool isNative) internal nonReentrant returns (uint256) { accrueInterest(); // redeemFresh emits redeem-specific logs on errors, so we don't need to return redeemFresh(msg.sender, redeemTokens, 0, isNative); } /** * @notice Sender redeems cTokens in exchange for a specified amount of underlying asset * @dev Accrues interest whether or not the operation succeeds, unless reverted * @param redeemAmount The amount of underlying to receive from redeeming cTokens * @param isNative The amount is in native or not * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function redeemUnderlyingInternal(uint256 redeemAmount, bool isNative) internal nonReentrant returns (uint256) { accrueInterest(); // redeemFresh emits redeem-specific logs on errors, so we don't need to return redeemFresh(msg.sender, 0, redeemAmount, isNative); } /** * @notice Sender borrows assets from the protocol to their own address * @param borrowAmount The amount of the underlying asset to borrow * @param isNative The amount is in native or not * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function borrowInternal(uint256 borrowAmount, bool isNative) internal nonReentrant returns (uint256) { accrueInterest(); // borrowFresh emits borrow-specific logs on errors, so we don't need to return borrowFresh(msg.sender, borrowAmount, isNative); } struct BorrowLocalVars { MathError mathErr; uint256 accountBorrows; uint256 accountBorrowsNew; uint256 totalBorrowsNew; } /** * @notice Users borrow assets from the protocol to their own address * @param borrowAmount The amount of the underlying asset to borrow * @param isNative The amount is in native or not * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function borrowFresh( address payable borrower, uint256 borrowAmount, bool isNative ) internal returns (uint256) { /* Fail if borrow not allowed */ require(comptroller.borrowAllowed(address(this), borrower, borrowAmount) == 0, "rejected"); /* Verify market's block number equals current block number */ require(accrualBlockNumber == getBlockNumber(), "market is stale"); /* Reverts if protocol has insufficient cash */ require(getCashPrior() >= borrowAmount, "insufficient cash"); BorrowLocalVars memory vars; /* * We calculate the new borrower and total borrow balances, failing on overflow: * accountBorrowsNew = accountBorrows + borrowAmount * totalBorrowsNew = totalBorrows + borrowAmount */ vars.accountBorrows = borrowBalanceStoredInternal(borrower); vars.accountBorrowsNew = add_(vars.accountBorrows, borrowAmount); vars.totalBorrowsNew = add_(totalBorrows, borrowAmount); ///////////////////////// // EFFECTS & INTERACTIONS // (No safe failures beyond this point) /* We write the previously calculated values into storage */ accountBorrows[borrower].principal = vars.accountBorrowsNew; accountBorrows[borrower].interestIndex = borrowIndex; totalBorrows = vars.totalBorrowsNew; /* * We invoke doTransferOut for the borrower and the borrowAmount. * Note: The cToken must handle variations between ERC-20 and ETH underlying. * On success, the cToken borrowAmount less of cash. * doTransferOut reverts if anything goes wrong, since we can't be sure if side effects occurred. */ doTransferOut(borrower, borrowAmount, isNative); /* We emit a Borrow event */ emit Borrow(borrower, borrowAmount, vars.accountBorrowsNew, vars.totalBorrowsNew); /* We call the defense hook */ comptroller.borrowVerify(address(this), borrower, borrowAmount); return uint256(Error.NO_ERROR); } /** * @notice Sender repays their own borrow * @param repayAmount The amount to repay * @param isNative The amount is in native or not * @return (uint, uint) An error code (0=success, otherwise a failure, see ErrorReporter.sol), and the actual repayment amount. */ function repayBorrowInternal(uint256 repayAmount, bool isNative) internal nonReentrant returns (uint256, uint256) { accrueInterest(); // repayBorrowFresh emits repay-borrow-specific logs on errors, so we don't need to return repayBorrowFresh(msg.sender, msg.sender, repayAmount, isNative); } /** * @notice Sender repays a borrow belonging to borrower * @param borrower the account with the debt being payed off * @param repayAmount The amount to repay * @param isNative The amount is in native or not * @return (uint, uint) An error code (0=success, otherwise a failure, see ErrorReporter.sol), and the actual repayment amount. */ function repayBorrowBehalfInternal( address borrower, uint256 repayAmount, bool isNative ) internal nonReentrant returns (uint256, uint256) { accrueInterest(); // repayBorrowFresh emits repay-borrow-specific logs on errors, so we don't need to return repayBorrowFresh(msg.sender, borrower, repayAmount, isNative); } struct RepayBorrowLocalVars { Error err; MathError mathErr; uint256 repayAmount; uint256 borrowerIndex; uint256 accountBorrows; uint256 accountBorrowsNew; uint256 totalBorrowsNew; uint256 actualRepayAmount; } /** * @notice Borrows are repaid by another user (possibly the borrower). * @param payer the account paying off the borrow * @param borrower the account with the debt being payed off * @param repayAmount the amount of undelrying tokens being returned * @param isNative The amount is in native or not * @return (uint, uint) An error code (0=success, otherwise a failure, see ErrorReporter.sol), and the actual repayment amount. */ function repayBorrowFresh( address payer, address borrower, uint256 repayAmount, bool isNative ) internal returns (uint256, uint256) { /* Fail if repayBorrow not allowed */ require(comptroller.repayBorrowAllowed(address(this), payer, borrower, repayAmount) == 0, "rejected"); /* Verify market's block number equals current block number */ require(accrualBlockNumber == getBlockNumber(), "market is stale"); RepayBorrowLocalVars memory vars; /* We remember the original borrowerIndex for verification purposes */ vars.borrowerIndex = accountBorrows[borrower].interestIndex; /* We fetch the amount the borrower owes, with accumulated interest */ vars.accountBorrows = borrowBalanceStoredInternal(borrower); /* If repayAmount == -1, repayAmount = accountBorrows */ if (repayAmount == uint256(-1)) { vars.repayAmount = vars.accountBorrows; } else { vars.repayAmount = repayAmount; } ///////////////////////// // EFFECTS & INTERACTIONS // (No safe failures beyond this point) /* * We call doTransferIn for the payer and the repayAmount * Note: The cToken must handle variations between ERC-20 and ETH underlying. * On success, the cToken holds an additional repayAmount of cash. * doTransferIn reverts if anything goes wrong, since we can't be sure if side effects occurred. * it returns the amount actually transferred, in case of a fee. */ vars.actualRepayAmount = doTransferIn(payer, vars.repayAmount, isNative); /* * We calculate the new borrower and total borrow balances, failing on underflow: * accountBorrowsNew = accountBorrows - actualRepayAmount * totalBorrowsNew = totalBorrows - actualRepayAmount */ vars.accountBorrowsNew = sub_(vars.accountBorrows, vars.actualRepayAmount); vars.totalBorrowsNew = sub_(totalBorrows, vars.actualRepayAmount); /* We write the previously calculated values into storage */ accountBorrows[borrower].principal = vars.accountBorrowsNew; accountBorrows[borrower].interestIndex = borrowIndex; totalBorrows = vars.totalBorrowsNew; /* We emit a RepayBorrow event */ emit RepayBorrow(payer, borrower, vars.actualRepayAmount, vars.accountBorrowsNew, vars.totalBorrowsNew); /* We call the defense hook */ comptroller.repayBorrowVerify(address(this), payer, borrower, vars.actualRepayAmount, vars.borrowerIndex); return (uint256(Error.NO_ERROR), vars.actualRepayAmount); } /** * @notice The sender liquidates the borrowers collateral. * The collateral seized is transferred to the liquidator. * @param borrower The borrower of this cToken to be liquidated * @param repayAmount The amount of the underlying borrowed asset to repay * @param cTokenCollateral The market in which to seize collateral from the borrower * @param isNative The amount is in native or not * @return (uint, uint) An error code (0=success, otherwise a failure, see ErrorReporter.sol), and the actual repayment amount. */ function liquidateBorrowInternal( address borrower, uint256 repayAmount, CTokenInterface cTokenCollateral, bool isNative ) internal nonReentrant returns (uint256, uint256) { accrueInterest(); require(cTokenCollateral.accrueInterest() == uint256(Error.NO_ERROR), "accrue interest failed"); // liquidateBorrowFresh emits borrow-specific logs on errors, so we don't need to return liquidateBorrowFresh(msg.sender, borrower, repayAmount, cTokenCollateral, isNative); } struct LiquidateBorrowLocalVars { uint256 repayBorrowError; uint256 actualRepayAmount; uint256 amountSeizeError; uint256 seizeTokens; } /** * @notice The liquidator liquidates the borrowers collateral. * The collateral seized is transferred to the liquidator. * @param borrower The borrower of this cToken to be liquidated * @param liquidator The address repaying the borrow and seizing collateral * @param cTokenCollateral The market in which to seize collateral from the borrower * @param repayAmount The amount of the underlying borrowed asset to repay * @param isNative The amount is in native or not * @return (uint, uint) An error code (0=success, otherwise a failure, see ErrorReporter.sol), and the actual repayment amount. */ function liquidateBorrowFresh( address liquidator, address borrower, uint256 repayAmount, CTokenInterface cTokenCollateral, bool isNative ) internal returns (uint256, uint256) { /* Fail if liquidate not allowed */ require( comptroller.liquidateBorrowAllowed( address(this), address(cTokenCollateral), liquidator, borrower, repayAmount ) == 0, "rejected" ); /* Verify market's block number equals current block number */ require(accrualBlockNumber == getBlockNumber(), "market is stale"); /* Verify cTokenCollateral market's block number equals current block number */ require(cTokenCollateral.accrualBlockNumber() == getBlockNumber(), "market is stale"); /* Fail if borrower = liquidator */ require(borrower != liquidator, "invalid account pair"); /* Fail if repayAmount = 0 or repayAmount = -1 */ require(repayAmount > 0 && repayAmount != uint256(-1), "invalid close amount requested"); LiquidateBorrowLocalVars memory vars; /* Fail if repayBorrow fails */ (vars.repayBorrowError, vars.actualRepayAmount) = repayBorrowFresh(liquidator, borrower, repayAmount, isNative); require(vars.repayBorrowError == uint256(Error.NO_ERROR), "repay borrow failed"); ///////////////////////// // EFFECTS & INTERACTIONS // (No safe failures beyond this point) /* We calculate the number of collateral tokens that will be seized */ (vars.amountSeizeError, vars.seizeTokens) = comptroller.liquidateCalculateSeizeTokens( address(this), address(cTokenCollateral), vars.actualRepayAmount ); require(vars.amountSeizeError == uint256(Error.NO_ERROR), "failed to calculate seize amount"); /* Revert if borrower collateral token balance < seizeTokens */ require(cTokenCollateral.balanceOf(borrower) >= vars.seizeTokens, "LIQUIDATE_SEIZE_TOO_MUCH"); // If this is also the collateral, run seizeInternal to avoid re-entrancy, otherwise make an external call uint256 seizeError; if (address(cTokenCollateral) == address(this)) { seizeError = seizeInternal(address(this), liquidator, borrower, vars.seizeTokens); } else { seizeError = cTokenCollateral.seize(liquidator, borrower, vars.seizeTokens); } /* Revert if seize tokens fails (since we cannot be sure of side effects) */ require(seizeError == uint256(Error.NO_ERROR), "token seizure failed"); /* We emit a LiquidateBorrow event */ emit LiquidateBorrow(liquidator, borrower, vars.actualRepayAmount, address(cTokenCollateral), vars.seizeTokens); /* We call the defense hook */ comptroller.liquidateBorrowVerify( address(this), address(cTokenCollateral), liquidator, borrower, vars.actualRepayAmount, vars.seizeTokens ); return (uint256(Error.NO_ERROR), vars.actualRepayAmount); } /** * @notice Transfers collateral tokens (this market) to the liquidator. * @dev Will fail unless called by another cToken during the process of liquidation. * Its absolutely critical to use msg.sender as the borrowed cToken and not a parameter. * @param liquidator The account receiving seized collateral * @param borrower The account having collateral seized * @param seizeTokens The number of cTokens to seize * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function seize( address liquidator, address borrower, uint256 seizeTokens ) external nonReentrant returns (uint256) { return seizeInternal(msg.sender, liquidator, borrower, seizeTokens); } /*** Admin Functions ***/ /** * @notice Begins transfer of admin rights. The newPendingAdmin must call `_acceptAdmin` to finalize the transfer. * @dev Admin function to begin change of admin. The newPendingAdmin must call `_acceptAdmin` to finalize the transfer. * @param newPendingAdmin New pending admin. * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _setPendingAdmin(address payable newPendingAdmin) external returns (uint256) { // Check caller = admin if (msg.sender != admin) { return fail(Error.UNAUTHORIZED, FailureInfo.SET_PENDING_ADMIN_OWNER_CHECK); } // Save current value, if any, for inclusion in log address oldPendingAdmin = pendingAdmin; // Store pendingAdmin with value newPendingAdmin pendingAdmin = newPendingAdmin; // Emit NewPendingAdmin(oldPendingAdmin, newPendingAdmin) emit NewPendingAdmin(oldPendingAdmin, newPendingAdmin); return uint256(Error.NO_ERROR); } /** * @notice Accepts transfer of admin rights. msg.sender must be pendingAdmin * @dev Admin function for pending admin to accept role and update admin * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _acceptAdmin() external returns (uint256) { // Check caller is pendingAdmin and pendingAdmin ≠ address(0) if (msg.sender != pendingAdmin || msg.sender == address(0)) { return fail(Error.UNAUTHORIZED, FailureInfo.ACCEPT_ADMIN_PENDING_ADMIN_CHECK); } // Save current values for inclusion in log address oldAdmin = admin; address oldPendingAdmin = pendingAdmin; // Store admin with value pendingAdmin admin = pendingAdmin; // Clear the pending value pendingAdmin = address(0); emit NewAdmin(oldAdmin, admin); emit NewPendingAdmin(oldPendingAdmin, pendingAdmin); return uint256(Error.NO_ERROR); } /** * @notice Sets a new comptroller for the market * @dev Admin function to set a new comptroller * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _setComptroller(ComptrollerInterface newComptroller) public returns (uint256) { // Check caller is admin if (msg.sender != admin) { return fail(Error.UNAUTHORIZED, FailureInfo.SET_COMPTROLLER_OWNER_CHECK); } ComptrollerInterface oldComptroller = comptroller; // Ensure invoke comptroller.isComptroller() returns true require(newComptroller.isComptroller(), "not comptroller"); // Set market's comptroller to newComptroller comptroller = newComptroller; // Emit NewComptroller(oldComptroller, newComptroller) emit NewComptroller(oldComptroller, newComptroller); return uint256(Error.NO_ERROR); } /** * @notice accrues interest and sets a new reserve factor for the protocol using _setReserveFactorFresh * @dev Admin function to accrue interest and set a new reserve factor * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _setReserveFactor(uint256 newReserveFactorMantissa) external nonReentrant returns (uint256) { uint256 error = accrueInterest(); if (error != uint256(Error.NO_ERROR)) { // accrueInterest emits logs on errors, but on top of that we want to log the fact that an attempted reserve factor change failed. return fail(Error(error), FailureInfo.SET_RESERVE_FACTOR_ACCRUE_INTEREST_FAILED); } // _setReserveFactorFresh emits reserve-factor-specific logs on errors, so we don't need to. return _setReserveFactorFresh(newReserveFactorMantissa); } /** * @notice Sets a new reserve factor for the protocol (*requires fresh interest accrual) * @dev Admin function to set a new reserve factor * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _setReserveFactorFresh(uint256 newReserveFactorMantissa) internal returns (uint256) { // Check caller is admin if (msg.sender != admin) { return fail(Error.UNAUTHORIZED, FailureInfo.SET_RESERVE_FACTOR_ADMIN_CHECK); } // Verify market's block number equals current block number if (accrualBlockNumber != getBlockNumber()) { return fail(Error.MARKET_NOT_FRESH, FailureInfo.SET_RESERVE_FACTOR_FRESH_CHECK); } // Check newReserveFactor ≤ maxReserveFactor if (newReserveFactorMantissa > reserveFactorMaxMantissa) { return fail(Error.BAD_INPUT, FailureInfo.SET_RESERVE_FACTOR_BOUNDS_CHECK); } uint256 oldReserveFactorMantissa = reserveFactorMantissa; reserveFactorMantissa = newReserveFactorMantissa; emit NewReserveFactor(oldReserveFactorMantissa, newReserveFactorMantissa); return uint256(Error.NO_ERROR); } /** * @notice Accrues interest and reduces reserves by transferring from msg.sender * @param addAmount Amount of addition to reserves * @param isNative The amount is in native or not * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _addReservesInternal(uint256 addAmount, bool isNative) internal nonReentrant returns (uint256) { uint256 error = accrueInterest(); if (error != uint256(Error.NO_ERROR)) { // accrueInterest emits logs on errors, but on top of that we want to log the fact that an attempted reduce reserves failed. return fail(Error(error), FailureInfo.ADD_RESERVES_ACCRUE_INTEREST_FAILED); } // _addReservesFresh emits reserve-addition-specific logs on errors, so we don't need to. (error, ) = _addReservesFresh(addAmount, isNative); return error; } /** * @notice Add reserves by transferring from caller * @dev Requires fresh interest accrual * @param addAmount Amount of addition to reserves * @param isNative The amount is in native or not * @return (uint, uint) An error code (0=success, otherwise a failure (see ErrorReporter.sol for details)) and the actual amount added, net token fees */ function _addReservesFresh(uint256 addAmount, bool isNative) internal returns (uint256, uint256) { // totalReserves + actualAddAmount uint256 totalReservesNew; uint256 actualAddAmount; // We fail gracefully unless market's block number equals current block number if (accrualBlockNumber != getBlockNumber()) { return (fail(Error.MARKET_NOT_FRESH, FailureInfo.ADD_RESERVES_FRESH_CHECK), actualAddAmount); } ///////////////////////// // EFFECTS & INTERACTIONS // (No safe failures beyond this point) /* * We call doTransferIn for the caller and the addAmount * Note: The cToken must handle variations between ERC-20 and ETH underlying. * On success, the cToken holds an additional addAmount of cash. * doTransferIn reverts if anything goes wrong, since we can't be sure if side effects occurred. * it returns the amount actually transferred, in case of a fee. */ actualAddAmount = doTransferIn(msg.sender, addAmount, isNative); totalReservesNew = add_(totalReserves, actualAddAmount); // Store reserves[n+1] = reserves[n] + actualAddAmount totalReserves = totalReservesNew; /* Emit NewReserves(admin, actualAddAmount, reserves[n+1]) */ emit ReservesAdded(msg.sender, actualAddAmount, totalReservesNew); /* Return (NO_ERROR, actualAddAmount) */ return (uint256(Error.NO_ERROR), actualAddAmount); } /** * @notice Accrues interest and reduces reserves by transferring to admin * @param reduceAmount Amount of reduction to reserves * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _reduceReserves(uint256 reduceAmount) external nonReentrant returns (uint256) { uint256 error = accrueInterest(); if (error != uint256(Error.NO_ERROR)) { // accrueInterest emits logs on errors, but on top of that we want to log the fact that an attempted reduce reserves failed. return fail(Error(error), FailureInfo.REDUCE_RESERVES_ACCRUE_INTEREST_FAILED); } // _reduceReservesFresh emits reserve-reduction-specific logs on errors, so we don't need to. return _reduceReservesFresh(reduceAmount); } /** * @notice Reduces reserves by transferring to admin * @dev Requires fresh interest accrual * @param reduceAmount Amount of reduction to reserves * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _reduceReservesFresh(uint256 reduceAmount) internal returns (uint256) { // totalReserves - reduceAmount uint256 totalReservesNew; // Check caller is admin if (msg.sender != admin) { return fail(Error.UNAUTHORIZED, FailureInfo.REDUCE_RESERVES_ADMIN_CHECK); } // We fail gracefully unless market's block number equals current block number if (accrualBlockNumber != getBlockNumber()) { return fail(Error.MARKET_NOT_FRESH, FailureInfo.REDUCE_RESERVES_FRESH_CHECK); } // Fail gracefully if protocol has insufficient underlying cash if (getCashPrior() < reduceAmount) { return fail(Error.TOKEN_INSUFFICIENT_CASH, FailureInfo.REDUCE_RESERVES_CASH_NOT_AVAILABLE); } // Check reduceAmount ≤ reserves[n] (totalReserves) if (reduceAmount > totalReserves) { return fail(Error.BAD_INPUT, FailureInfo.REDUCE_RESERVES_VALIDATION); } ///////////////////////// // EFFECTS & INTERACTIONS // (No safe failures beyond this point) totalReservesNew = sub_(totalReserves, reduceAmount); // Store reserves[n+1] = reserves[n] - reduceAmount totalReserves = totalReservesNew; // doTransferOut reverts if anything goes wrong, since we can't be sure if side effects occurred. // Restrict reducing reserves in wrapped token. Implementations except `CWrappedNative` won't use parameter `isNative`. doTransferOut(admin, reduceAmount, false); emit ReservesReduced(admin, reduceAmount, totalReservesNew); return uint256(Error.NO_ERROR); } /** * @notice accrues interest and updates the interest rate model using _setInterestRateModelFresh * @dev Admin function to accrue interest and update the interest rate model * @param newInterestRateModel the new interest rate model to use * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _setInterestRateModel(InterestRateModel newInterestRateModel) public returns (uint256) { uint256 error = accrueInterest(); if (error != uint256(Error.NO_ERROR)) { // accrueInterest emits logs on errors, but on top of that we want to log the fact that an attempted change of interest rate model failed return fail(Error(error), FailureInfo.SET_INTEREST_RATE_MODEL_ACCRUE_INTEREST_FAILED); } // _setInterestRateModelFresh emits interest-rate-model-update-specific logs on errors, so we don't need to. return _setInterestRateModelFresh(newInterestRateModel); } /** * @notice updates the interest rate model (*requires fresh interest accrual) * @dev Admin function to update the interest rate model * @param newInterestRateModel the new interest rate model to use * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _setInterestRateModelFresh(InterestRateModel newInterestRateModel) internal returns (uint256) { // Used to store old model for use in the event that is emitted on success InterestRateModel oldInterestRateModel; // Check caller is admin if (msg.sender != admin) { return fail(Error.UNAUTHORIZED, FailureInfo.SET_INTEREST_RATE_MODEL_OWNER_CHECK); } // We fail gracefully unless market's block number equals current block number if (accrualBlockNumber != getBlockNumber()) { return fail(Error.MARKET_NOT_FRESH, FailureInfo.SET_INTEREST_RATE_MODEL_FRESH_CHECK); } // Track the market's current interest rate model oldInterestRateModel = interestRateModel; // Ensure invoke newInterestRateModel.isInterestRateModel() returns true require(newInterestRateModel.isInterestRateModel(), "invalid IRM"); // Set the interest rate model to newInterestRateModel interestRateModel = newInterestRateModel; // Emit NewMarketInterestRateModel(oldInterestRateModel, newInterestRateModel) emit NewMarketInterestRateModel(oldInterestRateModel, newInterestRateModel); return uint256(Error.NO_ERROR); } /*** Safe Token ***/ /** * @notice Gets balance of this contract in terms of the underlying * @dev This excludes the value of the current message, if any * @return The quantity of underlying owned by this contract */ function getCashPrior() internal view returns (uint256); /** * @dev Performs a transfer in, reverting upon failure. Returns the amount actually transferred to the protocol, in case of a fee. * This may revert due to insufficient balance or insufficient allowance. */ function doTransferIn( address from, uint256 amount, bool isNative ) internal returns (uint256); /** * @dev Performs a transfer out, ideally returning an explanatory error code upon failure tather than reverting. * If caller has not called checked protocol's balance, may revert due to insufficient cash held in the contract. * If caller has checked protocol's balance, and verified it is >= amount, this should not revert in normal conditions. */ function doTransferOut( address payable to, uint256 amount, bool isNative ) internal; /** * @notice Transfer `tokens` tokens from `src` to `dst` by `spender` * @dev Called by both `transfer` and `transferFrom` internally */ function transferTokens( address spender, address src, address dst, uint256 tokens ) internal returns (uint256); /** * @notice Get the account's cToken balances */ function getCTokenBalanceInternal(address account) internal view returns (uint256); /** * @notice User supplies assets into the market and receives cTokens in exchange * @dev Assumes interest has already been accrued up to the current block */ function mintFresh( address minter, uint256 mintAmount, bool isNative ) internal returns (uint256, uint256); /** * @notice User redeems cTokens in exchange for the underlying asset * @dev Assumes interest has already been accrued up to the current block */ function redeemFresh( address payable redeemer, uint256 redeemTokensIn, uint256 redeemAmountIn, bool isNative ) internal returns (uint256); /** * @notice Transfers collateral tokens (this market) to the liquidator. * @dev Called only during an in-kind liquidation, or by liquidateBorrow during the liquidation of another CToken. * Its absolutely critical to use msg.sender as the seizer cToken and not a parameter. */ function seizeInternal( address seizerToken, address liquidator, address borrower, uint256 seizeTokens ) internal returns (uint256); /*** Reentrancy Guard ***/ /** * @dev Prevents a contract from calling itself, directly or indirectly. */ modifier nonReentrant() { require(_notEntered, "re-entered"); _notEntered = false; _; _notEntered = true; // get a gas-refund post-Istanbul } } pragma solidity ^0.5.16; import "./ComptrollerInterface.sol"; import "./InterestRateModel.sol"; import "./ERC3156FlashBorrowerInterface.sol"; contract CTokenStorage { /** * @dev Guard variable for re-entrancy checks */ bool internal _notEntered; /** * @notice EIP-20 token name for this token */ string public name; /** * @notice EIP-20 token symbol for this token */ string public symbol; /** * @notice EIP-20 token decimals for this token */ uint8 public decimals; /** * @notice Maximum borrow rate that can ever be applied (.0005% / block) */ uint256 internal constant borrowRateMaxMantissa = 0.0005e16; /** * @notice Maximum fraction of interest that can be set aside for reserves */ uint256 internal constant reserveFactorMaxMantissa = 1e18; /** * @notice Administrator for this contract */ address payable public admin; /** * @notice Pending administrator for this contract */ address payable public pendingAdmin; /** * @notice Contract which oversees inter-cToken operations */ ComptrollerInterface public comptroller; /** * @notice Model which tells what the current interest rate should be */ InterestRateModel public interestRateModel; /** * @notice Initial exchange rate used when minting the first CTokens (used when totalSupply = 0) */ uint256 internal initialExchangeRateMantissa; /** * @notice Fraction of interest currently set aside for reserves */ uint256 public reserveFactorMantissa; /** * @notice Block number that interest was last accrued at */ uint256 public accrualBlockNumber; /** * @notice Accumulator of the total earned interest rate since the opening of the market */ uint256 public borrowIndex; /** * @notice Total amount of outstanding borrows of the underlying in this market */ uint256 public totalBorrows; /** * @notice Total amount of reserves of the underlying held in this market */ uint256 public totalReserves; /** * @notice Total number of tokens in circulation */ uint256 public totalSupply; /** * @notice Official record of token balances for each account */ mapping(address => uint256) internal accountTokens; /** * @notice Approved token transfer amounts on behalf of others */ mapping(address => mapping(address => uint256)) internal transferAllowances; /** * @notice Container for borrow balance information * @member principal Total balance (with accrued interest), after applying the most recent balance-changing action * @member interestIndex Global borrowIndex as of the most recent balance-changing action */ struct BorrowSnapshot { uint256 principal; uint256 interestIndex; } /** * @notice Mapping of account addresses to outstanding borrow balances */ mapping(address => BorrowSnapshot) internal accountBorrows; } contract CErc20Storage { /** * @notice Underlying asset for this CToken */ address public underlying; /** * @notice Implementation address for this contract */ address public implementation; } contract CSupplyCapStorage { /** * @notice Internal cash counter for this CToken. Should equal underlying.balanceOf(address(this)) for CERC20. */ uint256 public internalCash; } contract CCollateralCapStorage { /** * @notice Total number of tokens used as collateral in circulation. */ uint256 public totalCollateralTokens; /** * @notice Record of token balances which could be treated as collateral for each account. * If collateral cap is not set, the value should be equal to accountTokens. */ mapping(address => uint256) public accountCollateralTokens; /** * @notice Check if accountCollateralTokens have been initialized. */ mapping(address => bool) public isCollateralTokenInit; /** * @notice Collateral cap for this CToken, zero for no cap. */ uint256 public collateralCap; } /*** Interface ***/ contract CTokenInterface is CTokenStorage { /** * @notice Indicator that this is a CToken contract (for inspection) */ bool public constant isCToken = true; /*** Market Events ***/ /** * @notice Event emitted when interest is accrued */ event AccrueInterest(uint256 cashPrior, uint256 interestAccumulated, uint256 borrowIndex, uint256 totalBorrows); /** * @notice Event emitted when tokens are minted */ event Mint(address minter, uint256 mintAmount, uint256 mintTokens); /** * @notice Event emitted when tokens are redeemed */ event Redeem(address redeemer, uint256 redeemAmount, uint256 redeemTokens); /** * @notice Event emitted when underlying is borrowed */ event Borrow(address borrower, uint256 borrowAmount, uint256 accountBorrows, uint256 totalBorrows); /** * @notice Event emitted when a borrow is repaid */ event RepayBorrow( address payer, address borrower, uint256 repayAmount, uint256 accountBorrows, uint256 totalBorrows ); /** * @notice Event emitted when a borrow is liquidated */ event LiquidateBorrow( address liquidator, address borrower, uint256 repayAmount, address cTokenCollateral, uint256 seizeTokens ); /*** Admin Events ***/ /** * @notice Event emitted when pendingAdmin is changed */ event NewPendingAdmin(address oldPendingAdmin, address newPendingAdmin); /** * @notice Event emitted when pendingAdmin is accepted, which means admin is updated */ event NewAdmin(address oldAdmin, address newAdmin); /** * @notice Event emitted when comptroller is changed */ event NewComptroller(ComptrollerInterface oldComptroller, ComptrollerInterface newComptroller); /** * @notice Event emitted when interestRateModel is changed */ event NewMarketInterestRateModel(InterestRateModel oldInterestRateModel, InterestRateModel newInterestRateModel); /** * @notice Event emitted when the reserve factor is changed */ event NewReserveFactor(uint256 oldReserveFactorMantissa, uint256 newReserveFactorMantissa); /** * @notice Event emitted when the reserves are added */ event ReservesAdded(address benefactor, uint256 addAmount, uint256 newTotalReserves); /** * @notice Event emitted when the reserves are reduced */ event ReservesReduced(address admin, uint256 reduceAmount, uint256 newTotalReserves); /** * @notice EIP20 Transfer event */ event Transfer(address indexed from, address indexed to, uint256 amount); /** * @notice EIP20 Approval event */ event Approval(address indexed owner, address indexed spender, uint256 amount); /** * @notice Failure event */ event Failure(uint256 error, uint256 info, uint256 detail); /*** User Interface ***/ function transfer(address dst, uint256 amount) external returns (bool); function transferFrom( address src, address dst, uint256 amount ) external returns (bool); function approve(address spender, uint256 amount) external returns (bool); function allowance(address owner, address spender) external view returns (uint256); function balanceOf(address owner) external view returns (uint256); function balanceOfUnderlying(address owner) external returns (uint256); function getAccountSnapshot(address account) external view returns ( uint256, uint256, uint256, uint256 ); function borrowRatePerBlock() external view returns (uint256); function supplyRatePerBlock() external view returns (uint256); function totalBorrowsCurrent() external returns (uint256); function borrowBalanceCurrent(address account) external returns (uint256); function borrowBalanceStored(address account) public view returns (uint256); function exchangeRateCurrent() public returns (uint256); function exchangeRateStored() public view returns (uint256); function getCash() external view returns (uint256); function accrueInterest() public returns (uint256); function seize( address liquidator, address borrower, uint256 seizeTokens ) external returns (uint256); /*** Admin Functions ***/ function _setPendingAdmin(address payable newPendingAdmin) external returns (uint256); function _acceptAdmin() external returns (uint256); function _setComptroller(ComptrollerInterface newComptroller) public returns (uint256); function _setReserveFactor(uint256 newReserveFactorMantissa) external returns (uint256); function _reduceReserves(uint256 reduceAmount) external returns (uint256); function _setInterestRateModel(InterestRateModel newInterestRateModel) public returns (uint256); } contract CErc20Interface is CErc20Storage { /*** User Interface ***/ function mint(uint256 mintAmount) external returns (uint256); function redeem(uint256 redeemTokens) external returns (uint256); function redeemUnderlying(uint256 redeemAmount) external returns (uint256); function borrow(uint256 borrowAmount) external returns (uint256); function repayBorrow(uint256 repayAmount) external returns (uint256); function repayBorrowBehalf(address borrower, uint256 repayAmount) external returns (uint256); function liquidateBorrow( address borrower, uint256 repayAmount, CTokenInterface cTokenCollateral ) external returns (uint256); function _addReserves(uint256 addAmount) external returns (uint256); } contract CWrappedNativeInterface is CErc20Interface { /** * @notice Flash loan fee ratio */ uint256 public constant flashFeeBips = 3; /*** Market Events ***/ /** * @notice Event emitted when a flashloan occured */ event Flashloan(address indexed receiver, uint256 amount, uint256 totalFee, uint256 reservesFee); /*** User Interface ***/ function mintNative() external payable returns (uint256); function redeemNative(uint256 redeemTokens) external returns (uint256); function redeemUnderlyingNative(uint256 redeemAmount) external returns (uint256); function borrowNative(uint256 borrowAmount) external returns (uint256); function repayBorrowNative() external payable returns (uint256); function repayBorrowBehalfNative(address borrower) external payable returns (uint256); function liquidateBorrowNative(address borrower, CTokenInterface cTokenCollateral) external payable returns (uint256); function flashLoan( ERC3156FlashBorrowerInterface receiver, address initiator, uint256 amount, bytes calldata data ) external returns (bool); function _addReservesNative() external payable returns (uint256); } contract CCapableErc20Interface is CErc20Interface, CSupplyCapStorage { /** * @notice Flash loan fee ratio */ uint256 public constant flashFeeBips = 3; /*** Market Events ***/ /** * @notice Event emitted when a flashloan occured */ event Flashloan(address indexed receiver, uint256 amount, uint256 totalFee, uint256 reservesFee); /*** User Interface ***/ function gulp() external; } contract CCollateralCapErc20Interface is CCapableErc20Interface, CCollateralCapStorage { /*** Admin Events ***/ /** * @notice Event emitted when collateral cap is set */ event NewCollateralCap(address token, uint256 newCap); /** * @notice Event emitted when user collateral is changed */ event UserCollateralChanged(address account, uint256 newCollateralTokens); /*** User Interface ***/ function registerCollateral(address account) external returns (uint256); function unregisterCollateral(address account) external; function flashLoan( ERC3156FlashBorrowerInterface receiver, address initiator, uint256 amount, bytes calldata data ) external returns (bool); /*** Admin Functions ***/ function _setCollateralCap(uint256 newCollateralCap) external; } contract CDelegatorInterface { /** * @notice Emitted when implementation is changed */ event NewImplementation(address oldImplementation, address newImplementation); /** * @notice Called by the admin to update the implementation of the delegator * @param implementation_ The address of the new implementation for delegation * @param allowResign Flag to indicate whether to call _resignImplementation on the old implementation * @param becomeImplementationData The encoded bytes data to be passed to _becomeImplementation */ function _setImplementation( address implementation_, bool allowResign, bytes memory becomeImplementationData ) public; } contract CDelegateInterface { /** * @notice Called by the delegator on a delegate to initialize it for duty * @dev Should revert if any issues arise which make it unfit for delegation * @param data The encoded bytes data for any initialization */ function _becomeImplementation(bytes memory data) public; /** * @notice Called by the delegator on a delegate to forfeit its responsibility */ function _resignImplementation() public; } /*** External interface ***/ /** * @title Flash loan receiver interface */ interface IFlashloanReceiver { function executeOperation( address sender, address underlying, uint256 amount, uint256 fee, bytes calldata params ) external; } pragma solidity ^0.5.16; /** * @title Careful Math * @author Compound * @notice Derived from OpenZeppelin's SafeMath library * https://github.com/OpenZeppelin/openzeppelin-solidity/blob/master/contracts/math/SafeMath.sol */ contract CarefulMath { /** * @dev Possible error codes that we can return */ enum MathError { NO_ERROR, DIVISION_BY_ZERO, INTEGER_OVERFLOW, INTEGER_UNDERFLOW } /** * @dev Multiplies two numbers, returns an error on overflow. */ function mulUInt(uint256 a, uint256 b) internal pure returns (MathError, uint256) { if (a == 0) { return (MathError.NO_ERROR, 0); } uint256 c = a * b; if (c / a != b) { return (MathError.INTEGER_OVERFLOW, 0); } else { return (MathError.NO_ERROR, c); } } /** * @dev Integer division of two numbers, truncating the quotient. */ function divUInt(uint256 a, uint256 b) internal pure returns (MathError, uint256) { if (b == 0) { return (MathError.DIVISION_BY_ZERO, 0); } return (MathError.NO_ERROR, a / b); } /** * @dev Subtracts two numbers, returns an error on overflow (i.e. if subtrahend is greater than minuend). */ function subUInt(uint256 a, uint256 b) internal pure returns (MathError, uint256) { if (b <= a) { return (MathError.NO_ERROR, a - b); } else { return (MathError.INTEGER_UNDERFLOW, 0); } } /** * @dev Adds two numbers, returns an error on overflow. */ function addUInt(uint256 a, uint256 b) internal pure returns (MathError, uint256) { uint256 c = a + b; if (c >= a) { return (MathError.NO_ERROR, c); } else { return (MathError.INTEGER_OVERFLOW, 0); } } /** * @dev add a and b and then subtract c */ function addThenSubUInt( uint256 a, uint256 b, uint256 c ) internal pure returns (MathError, uint256) { (MathError err0, uint256 sum) = addUInt(a, b); if (err0 != MathError.NO_ERROR) { return (err0, 0); } return subUInt(sum, c); } } pragma solidity ^0.5.16; import "./CToken.sol"; import "./ErrorReporter.sol"; import "./Exponential.sol"; import "./PriceOracle/PriceOracle.sol"; import "./ComptrollerInterface.sol"; import "./ComptrollerStorage.sol"; import "./LiquidityMiningInterface.sol"; import "./Unitroller.sol"; import "./Governance/Comp.sol"; /** * @title Compound's Comptroller Contract * @author Compound (modified by Cream) */ contract Comptroller is ComptrollerV1Storage, ComptrollerInterface, ComptrollerErrorReporter, Exponential { /// @notice Emitted when an admin supports a market event MarketListed(CToken cToken); /// @notice Emitted when an admin delists a market event MarketDelisted(CToken cToken); /// @notice Emitted when an account enters a market event MarketEntered(CToken cToken, address account); /// @notice Emitted when an account exits a market event MarketExited(CToken cToken, address account); /// @notice Emitted when close factor is changed by admin event NewCloseFactor(uint256 oldCloseFactorMantissa, uint256 newCloseFactorMantissa); /// @notice Emitted when a collateral factor is changed by admin event NewCollateralFactor(CToken cToken, uint256 oldCollateralFactorMantissa, uint256 newCollateralFactorMantissa); /// @notice Emitted when liquidation incentive is changed by admin event NewLiquidationIncentive(uint256 oldLiquidationIncentiveMantissa, uint256 newLiquidationIncentiveMantissa); /// @notice Emitted when price oracle is changed event NewPriceOracle(PriceOracle oldPriceOracle, PriceOracle newPriceOracle); /// @notice Emitted when pause guardian is changed event NewPauseGuardian(address oldPauseGuardian, address newPauseGuardian); /// @notice Emitted when liquidity mining module is changed event NewLiquidityMining(address oldLiquidityMining, address newLiquidityMining); /// @notice Emitted when an action is paused globally event ActionPaused(string action, bool pauseState); /// @notice Emitted when an action is paused on a market event ActionPaused(CToken cToken, string action, bool pauseState); /// @notice Emitted when borrow cap for a cToken is changed event NewBorrowCap(CToken indexed cToken, uint256 newBorrowCap); /// @notice Emitted when borrow cap guardian is changed event NewBorrowCapGuardian(address oldBorrowCapGuardian, address newBorrowCapGuardian); /// @notice Emitted when supply cap for a cToken is changed event NewSupplyCap(CToken indexed cToken, uint256 newSupplyCap); /// @notice Emitted when supply cap guardian is changed event NewSupplyCapGuardian(address oldSupplyCapGuardian, address newSupplyCapGuardian); /// @notice Emitted when protocol's credit limit has changed event CreditLimitChanged(address protocol, address market, uint256 creditLimit); /// @notice Emitted when cToken version is changed event NewCTokenVersion(CToken cToken, Version oldVersion, Version newVersion); // No collateralFactorMantissa may exceed this value uint256 internal constant collateralFactorMaxMantissa = 0.9e18; // 0.9 constructor() public { admin = msg.sender; } /*** Assets You Are In ***/ /** * @notice Returns the assets an account has entered * @param account The address of the account to pull assets for * @return A dynamic list with the assets the account has entered */ function getAssetsIn(address account) external view returns (CToken[] memory) { CToken[] memory assetsIn = accountAssets[account]; return assetsIn; } /** * @notice Returns whether the given account is entered in the given asset * @param account The address of the account to check * @param cToken The cToken to check * @return True if the account is in the asset, otherwise false. */ function checkMembership(address account, CToken cToken) external view returns (bool) { return markets[address(cToken)].accountMembership[account]; } /** * @notice Add assets to be included in account liquidity calculation * @param cTokens The list of addresses of the cToken markets to be enabled * @return Success indicator for whether each corresponding market was entered */ function enterMarkets(address[] memory cTokens) public returns (uint256[] memory) { uint256 len = cTokens.length; uint256[] memory results = new uint256[](len); for (uint256 i = 0; i < len; i++) { CToken cToken = CToken(cTokens[i]); results[i] = uint256(addToMarketInternal(cToken, msg.sender)); } return results; } /** * @notice Add the market to the borrower's "assets in" for liquidity calculations * @param cToken The market to enter * @param borrower The address of the account to modify * @return Success indicator for whether the market was entered */ function addToMarketInternal(CToken cToken, address borrower) internal returns (Error) { Market storage marketToJoin = markets[address(cToken)]; require(marketToJoin.isListed, "market not listed"); if (marketToJoin.version == Version.COLLATERALCAP) { // register collateral for the borrower if the token is CollateralCap version. CCollateralCapErc20Interface(address(cToken)).registerCollateral(borrower); } if (marketToJoin.accountMembership[borrower] == true) { // already joined return Error.NO_ERROR; } // survived the gauntlet, add to list // NOTE: we store these somewhat redundantly as a significant optimization // this avoids having to iterate through the list for the most common use cases // that is, only when we need to perform liquidity checks // and not whenever we want to check if an account is in a particular market marketToJoin.accountMembership[borrower] = true; accountAssets[borrower].push(cToken); emit MarketEntered(cToken, borrower); return Error.NO_ERROR; } /** * @notice Removes asset from sender's account liquidity calculation * @dev Sender must not have an outstanding borrow balance in the asset, * or be providing necessary collateral for an outstanding borrow. * @param cTokenAddress The address of the asset to be removed * @return Whether or not the account successfully exited the market */ function exitMarket(address cTokenAddress) external returns (uint256) { CToken cToken = CToken(cTokenAddress); /* Get sender tokensHeld and amountOwed underlying from the cToken */ (uint256 oErr, uint256 tokensHeld, uint256 amountOwed, ) = cToken.getAccountSnapshot(msg.sender); require(oErr == 0, "exitMarket: getAccountSnapshot failed"); // semi-opaque error code /* Fail if the sender has a borrow balance */ require(amountOwed == 0, "nonzero borrow balance"); /* Fail if the sender is not permitted to redeem all of their tokens */ require(redeemAllowedInternal(cTokenAddress, msg.sender, tokensHeld) == 0, "failed to exit market"); Market storage marketToExit = markets[cTokenAddress]; if (marketToExit.version == Version.COLLATERALCAP) { CCollateralCapErc20Interface(cTokenAddress).unregisterCollateral(msg.sender); } /* Return true if the sender is not already ‘in’ the market */ if (!marketToExit.accountMembership[msg.sender]) { return uint256(Error.NO_ERROR); } /* Set cToken account membership to false */ delete marketToExit.accountMembership[msg.sender]; /* Delete cToken from the account’s list of assets */ // load into memory for faster iteration CToken[] memory userAssetList = accountAssets[msg.sender]; uint256 len = userAssetList.length; uint256 assetIndex = len; for (uint256 i = 0; i < len; i++) { if (userAssetList[i] == cToken) { assetIndex = i; break; } } // We *must* have found the asset in the list or our redundant data structure is broken assert(assetIndex < len); // copy last item in list to location of item to be removed, reduce length by 1 CToken[] storage storedList = accountAssets[msg.sender]; if (assetIndex != storedList.length - 1) { storedList[assetIndex] = storedList[storedList.length - 1]; } storedList.length--; emit MarketExited(cToken, msg.sender); return uint256(Error.NO_ERROR); } /** * @notice Return a specific market is listed or not * @param cTokenAddress The address of the asset to be checked * @return Whether or not the market is listed */ function isMarketListed(address cTokenAddress) public view returns (bool) { return markets[cTokenAddress].isListed; } /** * @notice Return the credit limit of a specific protocol * @dev This function shouldn't be called. It exists only for backward compatibility. * @param protocol The address of the protocol * @return The credit */ function creditLimits(address protocol) public view returns (uint256) { protocol; // Shh return 0; } /** * @notice Return the credit limit of a specific protocol for a specific market * @param protocol The address of the protocol * @param market The market * @return The credit */ function creditLimits(address protocol, address market) public view returns (uint256) { return _creditLimits[protocol][market]; } /*** Policy Hooks ***/ /** * @notice Checks if the account should be allowed to mint tokens in the given market * @param cToken The market to verify the mint against * @param minter The account which would get the minted tokens * @param mintAmount The amount of underlying being supplied to the market in exchange for tokens * @return 0 if the mint is allowed, otherwise a semi-opaque error code (See ErrorReporter.sol) */ function mintAllowed( address cToken, address minter, uint256 mintAmount ) external returns (uint256) { // Pausing is a very serious situation - we revert to sound the alarms require(!mintGuardianPaused[cToken], "mint is paused"); require(!isCreditAccount(minter, cToken), "credit account cannot mint"); require(isMarketListed(cToken), "market not listed"); uint256 supplyCap = supplyCaps[cToken]; // Supply cap of 0 corresponds to unlimited supplying if (supplyCap != 0) { uint256 totalCash = CToken(cToken).getCash(); uint256 totalBorrows = CToken(cToken).totalBorrows(); uint256 totalReserves = CToken(cToken).totalReserves(); // totalSupplies = totalCash + totalBorrows - totalReserves (MathError mathErr, uint256 totalSupplies) = addThenSubUInt(totalCash, totalBorrows, totalReserves); require(mathErr == MathError.NO_ERROR, "totalSupplies failed"); uint256 nextTotalSupplies = add_(totalSupplies, mintAmount); require(nextTotalSupplies < supplyCap, "market supply cap reached"); } return uint256(Error.NO_ERROR); } /** * @notice Validates mint and reverts on rejection. May emit logs. * @param cToken Asset being minted * @param minter The address minting the tokens * @param actualMintAmount The amount of the underlying asset being minted * @param mintTokens The number of tokens being minted */ function mintVerify( address cToken, address minter, uint256 actualMintAmount, uint256 mintTokens ) external { // Shh - currently unused cToken; minter; actualMintAmount; mintTokens; // Shh - we don't ever want this hook to be marked pure if (false) { closeFactorMantissa = closeFactorMantissa; } } /** * @notice Checks if the account should be allowed to redeem tokens in the given market * @param cToken The market to verify the redeem against * @param redeemer The account which would redeem the tokens * @param redeemTokens The number of cTokens to exchange for the underlying asset in the market * @return 0 if the redeem is allowed, otherwise a semi-opaque error code (See ErrorReporter.sol) */ function redeemAllowed( address cToken, address redeemer, uint256 redeemTokens ) external returns (uint256) { return redeemAllowedInternal(cToken, redeemer, redeemTokens); } function redeemAllowedInternal( address cToken, address redeemer, uint256 redeemTokens ) internal view returns (uint256) { require(isMarketListed(cToken), "market not listed"); /* If the redeemer is not 'in' the market, then we can bypass the liquidity check */ if (!markets[cToken].accountMembership[redeemer]) { return uint256(Error.NO_ERROR); } /* Otherwise, perform a hypothetical liquidity check to guard against shortfall */ (Error err, , uint256 shortfall) = getHypotheticalAccountLiquidityInternal( redeemer, CToken(cToken), redeemTokens, 0 ); require(err == Error.NO_ERROR, "failed to get account liquidity"); require(shortfall == 0, "insufficient liquidity"); return uint256(Error.NO_ERROR); } /** * @notice Validates redeem and reverts on rejection. May emit logs. * @param cToken Asset being redeemed * @param redeemer The address redeeming the tokens * @param redeemAmount The amount of the underlying asset being redeemed * @param redeemTokens The number of tokens being redeemed */ function redeemVerify( address cToken, address redeemer, uint256 redeemAmount, uint256 redeemTokens ) external { // Shh - currently unused cToken; redeemer; // Require tokens is zero or amount is also zero if (redeemTokens == 0 && redeemAmount > 0) { revert("redeemTokens zero"); } } /** * @notice Checks if the account should be allowed to borrow the underlying asset of the given market * @param cToken The market to verify the borrow against * @param borrower The account which would borrow the asset * @param borrowAmount The amount of underlying the account would borrow * @return 0 if the borrow is allowed, otherwise a semi-opaque error code (See ErrorReporter.sol) */ function borrowAllowed( address cToken, address borrower, uint256 borrowAmount ) external returns (uint256) { // Pausing is a very serious situation - we revert to sound the alarms require(!borrowGuardianPaused[cToken], "borrow is paused"); require(isMarketListed(cToken), "market not listed"); if (!markets[cToken].accountMembership[borrower]) { // only cTokens may call borrowAllowed if borrower not in market require(msg.sender == cToken, "sender must be cToken"); // attempt to add borrower to the market require(addToMarketInternal(CToken(cToken), borrower) == Error.NO_ERROR, "failed to add market"); // it should be impossible to break the important invariant assert(markets[cToken].accountMembership[borrower]); } require(oracle.getUnderlyingPrice(CToken(cToken)) != 0, "price error"); uint256 borrowCap = borrowCaps[cToken]; // Borrow cap of 0 corresponds to unlimited borrowing if (borrowCap != 0) { uint256 totalBorrows = CToken(cToken).totalBorrows(); uint256 nextTotalBorrows = add_(totalBorrows, borrowAmount); require(nextTotalBorrows < borrowCap, "market borrow cap reached"); } (Error err, , uint256 shortfall) = getHypotheticalAccountLiquidityInternal( borrower, CToken(cToken), 0, borrowAmount ); require(err == Error.NO_ERROR, "failed to get account liquidity"); require(shortfall == 0, "insufficient liquidity"); return uint256(Error.NO_ERROR); } /** * @notice Validates borrow and reverts on rejection. May emit logs. * @param cToken Asset whose underlying is being borrowed * @param borrower The address borrowing the underlying * @param borrowAmount The amount of the underlying asset requested to borrow */ function borrowVerify( address cToken, address borrower, uint256 borrowAmount ) external { // Shh - currently unused cToken; borrower; borrowAmount; // Shh - we don't ever want this hook to be marked pure if (false) { closeFactorMantissa = closeFactorMantissa; } } /** * @notice Checks if the account should be allowed to repay a borrow in the given market * @param cToken The market to verify the repay against * @param payer The account which would repay the asset * @param borrower The account which would borrowed the asset * @param repayAmount The amount of the underlying asset the account would repay * @return 0 if the repay is allowed, otherwise a semi-opaque error code (See ErrorReporter.sol) */ function repayBorrowAllowed( address cToken, address payer, address borrower, uint256 repayAmount ) external returns (uint256) { // Shh - currently unused repayAmount; require(isMarketListed(cToken), "market not listed"); if (isCreditAccount(borrower, cToken)) { require(borrower == payer, "cannot repay on behalf of credit account"); } return uint256(Error.NO_ERROR); } /** * @notice Validates repayBorrow and reverts on rejection. May emit logs. * @param cToken Asset being repaid * @param payer The address repaying the borrow * @param borrower The address of the borrower * @param actualRepayAmount The amount of underlying being repaid */ function repayBorrowVerify( address cToken, address payer, address borrower, uint256 actualRepayAmount, uint256 borrowerIndex ) external { // Shh - currently unused cToken; payer; borrower; actualRepayAmount; borrowerIndex; // Shh - we don't ever want this hook to be marked pure if (false) { closeFactorMantissa = closeFactorMantissa; } } /** * @notice Checks if the liquidation should be allowed to occur * @param cTokenBorrowed Asset which was borrowed by the borrower * @param cTokenCollateral Asset which was used as collateral and will be seized * @param liquidator The address repaying the borrow and seizing the collateral * @param borrower The address of the borrower * @param repayAmount The amount of underlying being repaid */ function liquidateBorrowAllowed( address cTokenBorrowed, address cTokenCollateral, address liquidator, address borrower, uint256 repayAmount ) external returns (uint256) { require(!isCreditAccount(borrower, cTokenBorrowed), "cannot liquidate credit account"); // Shh - currently unused liquidator; require(isMarketListed(cTokenBorrowed) && isMarketListed(cTokenCollateral), "market not listed"); /* The borrower must have shortfall in order to be liquidatable */ (Error err, , uint256 shortfall) = getAccountLiquidityInternal(borrower); require(err == Error.NO_ERROR, "failed to get account liquidity"); require(shortfall > 0, "insufficient shortfall"); /* The liquidator may not repay more than what is allowed by the closeFactor */ uint256 borrowBalance = CToken(cTokenBorrowed).borrowBalanceStored(borrower); uint256 maxClose = mul_ScalarTruncate(Exp({mantissa: closeFactorMantissa}), borrowBalance); if (repayAmount > maxClose) { return uint256(Error.TOO_MUCH_REPAY); } return uint256(Error.NO_ERROR); } /** * @notice Validates liquidateBorrow and reverts on rejection. May emit logs. * @param cTokenBorrowed Asset which was borrowed by the borrower * @param cTokenCollateral Asset which was used as collateral and will be seized * @param liquidator The address repaying the borrow and seizing the collateral * @param borrower The address of the borrower * @param actualRepayAmount The amount of underlying being repaid */ function liquidateBorrowVerify( address cTokenBorrowed, address cTokenCollateral, address liquidator, address borrower, uint256 actualRepayAmount, uint256 seizeTokens ) external { // Shh - currently unused cTokenBorrowed; cTokenCollateral; liquidator; borrower; actualRepayAmount; seizeTokens; // Shh - we don't ever want this hook to be marked pure if (false) { closeFactorMantissa = closeFactorMantissa; } } /** * @notice Checks if the seizing of assets should be allowed to occur * @param cTokenCollateral Asset which was used as collateral and will be seized * @param cTokenBorrowed Asset which was borrowed by the borrower * @param liquidator The address repaying the borrow and seizing the collateral * @param borrower The address of the borrower * @param seizeTokens The number of collateral tokens to seize */ function seizeAllowed( address cTokenCollateral, address cTokenBorrowed, address liquidator, address borrower, uint256 seizeTokens ) external returns (uint256) { // Pausing is a very serious situation - we revert to sound the alarms require(!seizeGuardianPaused, "seize is paused"); require(!isCreditAccount(borrower, cTokenBorrowed), "cannot sieze from credit account"); // Shh - currently unused liquidator; seizeTokens; require(isMarketListed(cTokenBorrowed) && isMarketListed(cTokenCollateral), "market not listed"); require( CToken(cTokenCollateral).comptroller() == CToken(cTokenBorrowed).comptroller(), "comptroller mismatched" ); return uint256(Error.NO_ERROR); } /** * @notice Validates seize and reverts on rejection. May emit logs. * @param cTokenCollateral Asset which was used as collateral and will be seized * @param cTokenBorrowed Asset which was borrowed by the borrower * @param liquidator The address repaying the borrow and seizing the collateral * @param borrower The address of the borrower * @param seizeTokens The number of collateral tokens to seize */ function seizeVerify( address cTokenCollateral, address cTokenBorrowed, address liquidator, address borrower, uint256 seizeTokens ) external { // Shh - currently unused cTokenCollateral; cTokenBorrowed; liquidator; borrower; seizeTokens; // Shh - we don't ever want this hook to be marked pure if (false) { closeFactorMantissa = closeFactorMantissa; } } /** * @notice Checks if the account should be allowed to transfer tokens in the given market * @param cToken The market to verify the transfer against * @param src The account which sources the tokens * @param dst The account which receives the tokens * @param transferTokens The number of cTokens to transfer * @return 0 if the transfer is allowed, otherwise a semi-opaque error code (See ErrorReporter.sol) */ function transferAllowed( address cToken, address src, address dst, uint256 transferTokens ) external returns (uint256) { // Pausing is a very serious situation - we revert to sound the alarms require(!transferGuardianPaused, "transfer is paused"); require(!isCreditAccount(dst, cToken), "cannot transfer to a credit account"); // Shh - currently unused dst; // Currently the only consideration is whether or not // the src is allowed to redeem this many tokens return redeemAllowedInternal(cToken, src, transferTokens); } /** * @notice Validates transfer and reverts on rejection. May emit logs. * @param cToken Asset being transferred * @param src The account which sources the tokens * @param dst The account which receives the tokens * @param transferTokens The number of cTokens to transfer */ function transferVerify( address cToken, address src, address dst, uint256 transferTokens ) external { // Shh - currently unused cToken; src; dst; transferTokens; // Shh - we don't ever want this hook to be marked pure if (false) { closeFactorMantissa = closeFactorMantissa; } } /** * @notice Checks if the account should be allowed to transfer tokens in the given market * @param cToken The market to verify the transfer against * @param receiver The account which receives the tokens * @param amount The amount of the tokens * @param params The other parameters */ function flashloanAllowed( address cToken, address receiver, uint256 amount, bytes calldata params ) external view returns (bool) { return !flashloanGuardianPaused[cToken]; } /** * @notice Update CToken's version. * @param cToken Version of the asset being updated * @param newVersion The new version */ function updateCTokenVersion(address cToken, Version newVersion) external { require(msg.sender == cToken, "cToken only"); // This function will be called when a new CToken implementation becomes active. // If a new CToken is newly created, this market is not listed yet. The version of // this market will be taken care of when calling `_supportMarket`. if (isMarketListed(cToken)) { Version oldVersion = markets[cToken].version; markets[cToken].version = newVersion; emit NewCTokenVersion(CToken(cToken), oldVersion, newVersion); } } /** * @notice Check if the account is a credit account * @param account The account needs to be checked * @param cToken The market * @return The account is a credit account or not */ function isCreditAccount(address account, address cToken) public view returns (bool) { return _creditLimits[account][cToken] > 0; } /*** Liquidity/Liquidation Calculations ***/ /** * @dev Local vars for avoiding stack-depth limits in calculating account liquidity. * Note that `cTokenBalance` is the number of cTokens the account owns in the market, * whereas `borrowBalance` is the amount of underlying that the account has borrowed. */ struct AccountLiquidityLocalVars { uint256 sumCollateral; uint256 sumBorrowPlusEffects; uint256 cTokenBalance; uint256 borrowBalance; uint256 exchangeRateMantissa; uint256 oraclePriceMantissa; Exp collateralFactor; Exp exchangeRate; Exp oraclePrice; Exp tokensToDenom; } /** * @notice Determine the current account liquidity wrt collateral requirements * @return (possible error code (semi-opaque), account liquidity in excess of collateral requirements, * account shortfall below collateral requirements) */ function getAccountLiquidity(address account) public view returns ( uint256, uint256, uint256 ) { (Error err, uint256 liquidity, uint256 shortfall) = getHypotheticalAccountLiquidityInternal( account, CToken(0), 0, 0 ); return (uint256(err), liquidity, shortfall); } /** * @notice Determine the current account liquidity wrt collateral requirements * @return (possible error code, account liquidity in excess of collateral requirements, * account shortfall below collateral requirements) */ function getAccountLiquidityInternal(address account) internal view returns ( Error, uint256, uint256 ) { return getHypotheticalAccountLiquidityInternal(account, CToken(0), 0, 0); } /** * @notice Determine what the account liquidity would be if the given amounts were redeemed/borrowed * @param cTokenModify The market to hypothetically redeem/borrow in * @param account The account to determine liquidity for * @param redeemTokens The number of tokens to hypothetically redeem * @param borrowAmount The amount of underlying to hypothetically borrow * @return (possible error code (semi-opaque), hypothetical account liquidity in excess of collateral requirements, * hypothetical account shortfall below collateral requirements) */ function getHypotheticalAccountLiquidity( address account, address cTokenModify, uint256 redeemTokens, uint256 borrowAmount ) public view returns ( uint256, uint256, uint256 ) { (Error err, uint256 liquidity, uint256 shortfall) = getHypotheticalAccountLiquidityInternal( account, CToken(cTokenModify), redeemTokens, borrowAmount ); return (uint256(err), liquidity, shortfall); } /** * @notice Determine what the account liquidity would be if the given amounts were redeemed/borrowed * @param cTokenModify The market to hypothetically redeem/borrow in * @param account The account to determine liquidity for * @param redeemTokens The number of tokens to hypothetically redeem * @param borrowAmount The amount of underlying to hypothetically borrow * @dev Note that we calculate the exchangeRateStored for each collateral cToken using stored data, * without calculating accumulated interest. * @return (possible error code, hypothetical account liquidity in excess of collateral requirements, * hypothetical account shortfall below collateral requirements) */ function getHypotheticalAccountLiquidityInternal( address account, CToken cTokenModify, uint256 redeemTokens, uint256 borrowAmount ) internal view returns ( Error, uint256, uint256 ) { AccountLiquidityLocalVars memory vars; // Holds all our calculation results uint256 oErr; // For each asset the account is in CToken[] memory assets = accountAssets[account]; for (uint256 i = 0; i < assets.length; i++) { CToken asset = assets[i]; // Read the balances and exchange rate from the cToken (oErr, vars.cTokenBalance, vars.borrowBalance, vars.exchangeRateMantissa) = asset.getAccountSnapshot( account ); require(oErr == 0, "snapshot error"); // Once a market's credit limit is set, the account's collateral won't be considered anymore. uint256 creditLimit = _creditLimits[account][address(asset)]; if (creditLimit > 0) { // The market's credit limit should be always greater than its borrow balance and the borrow balance won't be added to sumBorrowPlusEffects. require(creditLimit >= vars.borrowBalance, "insufficient credit limit"); if (asset == cTokenModify) { // borrowAmount must not exceed the credit limit. require(creditLimit >= add_(vars.borrowBalance, borrowAmount), "insufficient credit limit"); } } else { // Unlike compound protocol, getUnderlyingPrice is relatively expensive because we use ChainLink as our primary price feed. // If user has no supply / borrow balance on this asset, and user is not redeeming / borrowing this asset, skip it. if (vars.cTokenBalance == 0 && vars.borrowBalance == 0 && asset != cTokenModify) { continue; } vars.collateralFactor = Exp({mantissa: markets[address(asset)].collateralFactorMantissa}); vars.exchangeRate = Exp({mantissa: vars.exchangeRateMantissa}); // Get the normalized price of the asset vars.oraclePriceMantissa = oracle.getUnderlyingPrice(asset); require(vars.oraclePriceMantissa > 0, "price error"); vars.oraclePrice = Exp({mantissa: vars.oraclePriceMantissa}); // Pre-compute a conversion factor from tokens -> ether (normalized price value) vars.tokensToDenom = mul_(mul_(vars.collateralFactor, vars.exchangeRate), vars.oraclePrice); // sumCollateral += tokensToDenom * cTokenBalance vars.sumCollateral = mul_ScalarTruncateAddUInt( vars.tokensToDenom, vars.cTokenBalance, vars.sumCollateral ); // sumBorrowPlusEffects += oraclePrice * borrowBalance vars.sumBorrowPlusEffects = mul_ScalarTruncateAddUInt( vars.oraclePrice, vars.borrowBalance, vars.sumBorrowPlusEffects ); // Calculate effects of interacting with cTokenModify if (asset == cTokenModify) { // redeem effect // sumBorrowPlusEffects += tokensToDenom * redeemTokens vars.sumBorrowPlusEffects = mul_ScalarTruncateAddUInt( vars.tokensToDenom, redeemTokens, vars.sumBorrowPlusEffects ); // borrow effect // sumBorrowPlusEffects += oraclePrice * borrowAmount vars.sumBorrowPlusEffects = mul_ScalarTruncateAddUInt( vars.oraclePrice, borrowAmount, vars.sumBorrowPlusEffects ); } } } // These are safe, as the underflow condition is checked first if (vars.sumCollateral > vars.sumBorrowPlusEffects) { return (Error.NO_ERROR, vars.sumCollateral - vars.sumBorrowPlusEffects, 0); } else { return (Error.NO_ERROR, 0, vars.sumBorrowPlusEffects - vars.sumCollateral); } } /** * @notice Calculate number of tokens of collateral asset to seize given an underlying amount * @dev Used in liquidation (called in cToken.liquidateBorrowFresh) * @param cTokenBorrowed The address of the borrowed cToken * @param cTokenCollateral The address of the collateral cToken * @param actualRepayAmount The amount of cTokenBorrowed underlying to convert into cTokenCollateral tokens * @return (errorCode, number of cTokenCollateral tokens to be seized in a liquidation) */ function liquidateCalculateSeizeTokens( address cTokenBorrowed, address cTokenCollateral, uint256 actualRepayAmount ) external view returns (uint256, uint256) { /* Read oracle prices for borrowed and collateral markets */ uint256 priceBorrowedMantissa = oracle.getUnderlyingPrice(CToken(cTokenBorrowed)); uint256 priceCollateralMantissa = oracle.getUnderlyingPrice(CToken(cTokenCollateral)); require(priceBorrowedMantissa > 0 && priceCollateralMantissa > 0, "price error"); /* * Get the exchange rate and calculate the number of collateral tokens to seize: * seizeAmount = actualRepayAmount * liquidationIncentive * priceBorrowed / priceCollateral * seizeTokens = seizeAmount / exchangeRate * = actualRepayAmount * (liquidationIncentive * priceBorrowed) / (priceCollateral * exchangeRate) */ uint256 exchangeRateMantissa = CToken(cTokenCollateral).exchangeRateStored(); // Note: reverts on error Exp memory numerator = mul_( Exp({mantissa: liquidationIncentiveMantissa}), Exp({mantissa: priceBorrowedMantissa}) ); Exp memory denominator = mul_(Exp({mantissa: priceCollateralMantissa}), Exp({mantissa: exchangeRateMantissa})); Exp memory ratio = div_(numerator, denominator); uint256 seizeTokens = mul_ScalarTruncate(ratio, actualRepayAmount); return (uint256(Error.NO_ERROR), seizeTokens); } /*** Admin Functions ***/ /** * @notice Sets a new price oracle for the comptroller * @dev Admin function to set a new price oracle * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _setPriceOracle(PriceOracle newOracle) public returns (uint256) { // Check caller is admin if (msg.sender != admin) { return fail(Error.UNAUTHORIZED, FailureInfo.SET_PRICE_ORACLE_OWNER_CHECK); } // Track the old oracle for the comptroller PriceOracle oldOracle = oracle; // Set comptroller's oracle to newOracle oracle = newOracle; // Emit NewPriceOracle(oldOracle, newOracle) emit NewPriceOracle(oldOracle, newOracle); return uint256(Error.NO_ERROR); } /** * @notice Sets the closeFactor used when liquidating borrows * @dev Admin function to set closeFactor * @param newCloseFactorMantissa New close factor, scaled by 1e18 * @return uint 0=success, otherwise a failure. (See ErrorReporter for details) */ function _setCloseFactor(uint256 newCloseFactorMantissa) external returns (uint256) { // Check caller is admin if (msg.sender != admin) { return fail(Error.UNAUTHORIZED, FailureInfo.SET_CLOSE_FACTOR_OWNER_CHECK); } uint256 oldCloseFactorMantissa = closeFactorMantissa; closeFactorMantissa = newCloseFactorMantissa; emit NewCloseFactor(oldCloseFactorMantissa, closeFactorMantissa); return uint256(Error.NO_ERROR); } /** * @notice Sets the collateralFactor for a market * @dev Admin function to set per-market collateralFactor * @param cToken The market to set the factor on * @param newCollateralFactorMantissa The new collateral factor, scaled by 1e18 * @return uint 0=success, otherwise a failure. (See ErrorReporter for details) */ function _setCollateralFactor(CToken cToken, uint256 newCollateralFactorMantissa) external returns (uint256) { // Check caller is admin if (msg.sender != admin) { return fail(Error.UNAUTHORIZED, FailureInfo.SET_COLLATERAL_FACTOR_OWNER_CHECK); } // Verify market is listed Market storage market = markets[address(cToken)]; if (!market.isListed) { return fail(Error.MARKET_NOT_LISTED, FailureInfo.SET_COLLATERAL_FACTOR_NO_EXISTS); } Exp memory newCollateralFactorExp = Exp({mantissa: newCollateralFactorMantissa}); // Check collateral factor <= 0.9 Exp memory highLimit = Exp({mantissa: collateralFactorMaxMantissa}); if (lessThanExp(highLimit, newCollateralFactorExp)) { return fail(Error.INVALID_COLLATERAL_FACTOR, FailureInfo.SET_COLLATERAL_FACTOR_VALIDATION); } // If collateral factor != 0, fail if price == 0 if (newCollateralFactorMantissa != 0 && oracle.getUnderlyingPrice(cToken) == 0) { return fail(Error.PRICE_ERROR, FailureInfo.SET_COLLATERAL_FACTOR_WITHOUT_PRICE); } // Set market's collateral factor to new collateral factor, remember old value uint256 oldCollateralFactorMantissa = market.collateralFactorMantissa; market.collateralFactorMantissa = newCollateralFactorMantissa; // Emit event with asset, old collateral factor, and new collateral factor emit NewCollateralFactor(cToken, oldCollateralFactorMantissa, newCollateralFactorMantissa); return uint256(Error.NO_ERROR); } /** * @notice Sets liquidationIncentive * @dev Admin function to set liquidationIncentive * @param newLiquidationIncentiveMantissa New liquidationIncentive scaled by 1e18 * @return uint 0=success, otherwise a failure. (See ErrorReporter for details) */ function _setLiquidationIncentive(uint256 newLiquidationIncentiveMantissa) external returns (uint256) { // Check caller is admin if (msg.sender != admin) { return fail(Error.UNAUTHORIZED, FailureInfo.SET_LIQUIDATION_INCENTIVE_OWNER_CHECK); } // Save current value for use in log uint256 oldLiquidationIncentiveMantissa = liquidationIncentiveMantissa; // Set liquidation incentive to new incentive liquidationIncentiveMantissa = newLiquidationIncentiveMantissa; // Emit event with old incentive, new incentive emit NewLiquidationIncentive(oldLiquidationIncentiveMantissa, newLiquidationIncentiveMantissa); return uint256(Error.NO_ERROR); } /** * @notice Add the market to the markets mapping and set it as listed * @dev Admin function to set isListed and add support for the market * @param cToken The address of the market (token) to list * @param version The version of the market (token) * @return uint 0=success, otherwise a failure. (See enum Error for details) */ function _supportMarket(CToken cToken, Version version) external returns (uint256) { require(msg.sender == admin, "admin only"); require(!isMarketListed(address(cToken)), "market already listed"); cToken.isCToken(); // Sanity check to make sure its really a CToken markets[address(cToken)] = Market({isListed: true, collateralFactorMantissa: 0, version: version}); _addMarketInternal(address(cToken)); emit MarketListed(cToken); return uint256(Error.NO_ERROR); } /** * @notice Remove the market from the markets mapping * @param cToken The address of the market (token) to delist */ function _delistMarket(CToken cToken) external { require(msg.sender == admin, "admin only"); require(isMarketListed(address(cToken)), "market not listed"); require(cToken.totalSupply() == 0, "market not empty"); cToken.isCToken(); // Sanity check to make sure its really a CToken delete markets[address(cToken)]; for (uint256 i = 0; i < allMarkets.length; i++) { if (allMarkets[i] == cToken) { allMarkets[i] = allMarkets[allMarkets.length - 1]; delete allMarkets[allMarkets.length - 1]; allMarkets.length--; break; } } emit MarketDelisted(cToken); } function _addMarketInternal(address cToken) internal { for (uint256 i = 0; i < allMarkets.length; i++) { require(allMarkets[i] != CToken(cToken), "market already added"); } allMarkets.push(CToken(cToken)); } /** * @notice Admin function to change the Supply Cap Guardian * @param newSupplyCapGuardian The address of the new Supply Cap Guardian */ function _setSupplyCapGuardian(address newSupplyCapGuardian) external { require(msg.sender == admin, "admin only"); // Save current value for inclusion in log address oldSupplyCapGuardian = supplyCapGuardian; // Store supplyCapGuardian with value newSupplyCapGuardian supplyCapGuardian = newSupplyCapGuardian; // Emit NewSupplyCapGuardian(OldSupplyCapGuardian, NewSupplyCapGuardian) emit NewSupplyCapGuardian(oldSupplyCapGuardian, newSupplyCapGuardian); } /** * @notice Set the given supply caps for the given cToken markets. Supplying that brings total supplys to or above supply cap will revert. * @dev Admin or supplyCapGuardian function to set the supply caps. A supply cap of 0 corresponds to unlimited supplying. If the total borrows * already exceeded the cap, it will prevent anyone to borrow. * @param cTokens The addresses of the markets (tokens) to change the supply caps for * @param newSupplyCaps The new supply cap values in underlying to be set. A value of 0 corresponds to unlimited supplying. */ function _setMarketSupplyCaps(CToken[] calldata cTokens, uint256[] calldata newSupplyCaps) external { require(msg.sender == admin || msg.sender == supplyCapGuardian, "admin or supply cap guardian only"); uint256 numMarkets = cTokens.length; uint256 numSupplyCaps = newSupplyCaps.length; require(numMarkets != 0 && numMarkets == numSupplyCaps, "invalid input"); for (uint256 i = 0; i < numMarkets; i++) { supplyCaps[address(cTokens[i])] = newSupplyCaps[i]; emit NewSupplyCap(cTokens[i], newSupplyCaps[i]); } } /** * @notice Set the given borrow caps for the given cToken markets. Borrowing that brings total borrows to or above borrow cap will revert. * @dev Admin or borrowCapGuardian function to set the borrow caps. A borrow cap of 0 corresponds to unlimited borrowing. If the total supplies * already exceeded the cap, it will prevent anyone to mint. * @param cTokens The addresses of the markets (tokens) to change the borrow caps for * @param newBorrowCaps The new borrow cap values in underlying to be set. A value of 0 corresponds to unlimited borrowing. */ function _setMarketBorrowCaps(CToken[] calldata cTokens, uint256[] calldata newBorrowCaps) external { require(msg.sender == admin || msg.sender == borrowCapGuardian, "admin or borrow cap guardian only"); uint256 numMarkets = cTokens.length; uint256 numBorrowCaps = newBorrowCaps.length; require(numMarkets != 0 && numMarkets == numBorrowCaps, "invalid input"); for (uint256 i = 0; i < numMarkets; i++) { borrowCaps[address(cTokens[i])] = newBorrowCaps[i]; emit NewBorrowCap(cTokens[i], newBorrowCaps[i]); } } /** * @notice Admin function to change the Borrow Cap Guardian * @param newBorrowCapGuardian The address of the new Borrow Cap Guardian */ function _setBorrowCapGuardian(address newBorrowCapGuardian) external { require(msg.sender == admin, "admin only"); // Save current value for inclusion in log address oldBorrowCapGuardian = borrowCapGuardian; // Store borrowCapGuardian with value newBorrowCapGuardian borrowCapGuardian = newBorrowCapGuardian; // Emit NewBorrowCapGuardian(OldBorrowCapGuardian, NewBorrowCapGuardian) emit NewBorrowCapGuardian(oldBorrowCapGuardian, newBorrowCapGuardian); } /** * @notice Admin function to change the Pause Guardian * @param newPauseGuardian The address of the new Pause Guardian * @return uint 0=success, otherwise a failure. (See enum Error for details) */ function _setPauseGuardian(address newPauseGuardian) public returns (uint256) { if (msg.sender != admin) { return fail(Error.UNAUTHORIZED, FailureInfo.SET_PAUSE_GUARDIAN_OWNER_CHECK); } // Save current value for inclusion in log address oldPauseGuardian = pauseGuardian; // Store pauseGuardian with value newPauseGuardian pauseGuardian = newPauseGuardian; // Emit NewPauseGuardian(OldPauseGuardian, NewPauseGuardian) emit NewPauseGuardian(oldPauseGuardian, pauseGuardian); return uint256(Error.NO_ERROR); } /** * @notice Admin function to set the liquidity mining module address * @dev Removing the liquidity mining module address could cause the inconsistency in the LM module. * @param newLiquidityMining The address of the new liquidity mining module */ function _setLiquidityMining(address newLiquidityMining) external { require(msg.sender == admin, "admin only"); require(LiquidityMiningInterface(newLiquidityMining).comptroller() == address(this), "mismatch comptroller"); // Save current value for inclusion in log address oldLiquidityMining = liquidityMining; // Store pauseGuardian with value newLiquidityMining liquidityMining = newLiquidityMining; // Emit NewLiquidityMining(OldLiquidityMining, NewLiquidityMining) emit NewLiquidityMining(oldLiquidityMining, liquidityMining); } function _setMintPaused(CToken cToken, bool state) public returns (bool) { require(isMarketListed(address(cToken)), "market not listed"); require(msg.sender == pauseGuardian || msg.sender == admin, "guardian or admin only"); require(msg.sender == admin || state == true, "admin only"); mintGuardianPaused[address(cToken)] = state; emit ActionPaused(cToken, "Mint", state); return state; } function _setBorrowPaused(CToken cToken, bool state) public returns (bool) { require(isMarketListed(address(cToken)), "market not listed"); require(msg.sender == pauseGuardian || msg.sender == admin, "guardian or admin only"); require(msg.sender == admin || state == true, "admin only"); borrowGuardianPaused[address(cToken)] = state; emit ActionPaused(cToken, "Borrow", state); return state; } function _setFlashloanPaused(CToken cToken, bool state) public returns (bool) { require(isMarketListed(address(cToken)), "market not listed"); require(msg.sender == pauseGuardian || msg.sender == admin, "guardian or admin only"); require(msg.sender == admin || state == true, "admin only"); flashloanGuardianPaused[address(cToken)] = state; emit ActionPaused(cToken, "Flashloan", state); return state; } function _setTransferPaused(bool state) public returns (bool) { require(msg.sender == pauseGuardian || msg.sender == admin, "guardian or admin only"); require(msg.sender == admin || state == true, "admin only"); transferGuardianPaused = state; emit ActionPaused("Transfer", state); return state; } function _setSeizePaused(bool state) public returns (bool) { require(msg.sender == pauseGuardian || msg.sender == admin, "guardian or admin only"); require(msg.sender == admin || state == true, "admin only"); seizeGuardianPaused = state; emit ActionPaused("Seize", state); return state; } function _become(Unitroller unitroller) public { require(msg.sender == unitroller.admin(), "unitroller admin only"); require(unitroller._acceptImplementation() == 0, "unauthorized"); } /** * @notice Sets protocol's credit limit by market * @param protocol The address of the protocol * @param market The market * @param creditLimit The credit limit */ function _setCreditLimit( address protocol, address market, uint256 creditLimit ) public { require(msg.sender == admin, "only admin can set protocol credit limit"); require(addToMarketInternal(CToken(market), protocol) == Error.NO_ERROR, "invalid market"); _creditLimits[protocol][market] = creditLimit; emit CreditLimitChanged(protocol, market, creditLimit); } /** * @notice Return all of the markets * @dev The automatic getter may be used to access an individual market. * @return The list of market addresses */ function getAllMarkets() public view returns (CToken[] memory) { return allMarkets; } function getBlockNumber() public view returns (uint256) { return block.number; } } pragma solidity ^0.5.16; import "./CToken.sol"; import "./ComptrollerStorage.sol"; contract ComptrollerInterface { /// @notice Indicator that this is a Comptroller contract (for inspection) bool public constant isComptroller = true; /*** Assets You Are In ***/ function enterMarkets(address[] calldata cTokens) external returns (uint256[] memory); function exitMarket(address cToken) external returns (uint256); /*** Policy Hooks ***/ function mintAllowed( address cToken, address minter, uint256 mintAmount ) external returns (uint256); function mintVerify( address cToken, address minter, uint256 mintAmount, uint256 mintTokens ) external; function redeemAllowed( address cToken, address redeemer, uint256 redeemTokens ) external returns (uint256); function redeemVerify( address cToken, address redeemer, uint256 redeemAmount, uint256 redeemTokens ) external; function borrowAllowed( address cToken, address borrower, uint256 borrowAmount ) external returns (uint256); function borrowVerify( address cToken, address borrower, uint256 borrowAmount ) external; function repayBorrowAllowed( address cToken, address payer, address borrower, uint256 repayAmount ) external returns (uint256); function repayBorrowVerify( address cToken, address payer, address borrower, uint256 repayAmount, uint256 borrowerIndex ) external; function liquidateBorrowAllowed( address cTokenBorrowed, address cTokenCollateral, address liquidator, address borrower, uint256 repayAmount ) external returns (uint256); function liquidateBorrowVerify( address cTokenBorrowed, address cTokenCollateral, address liquidator, address borrower, uint256 repayAmount, uint256 seizeTokens ) external; function seizeAllowed( address cTokenCollateral, address cTokenBorrowed, address liquidator, address borrower, uint256 seizeTokens ) external returns (uint256); function seizeVerify( address cTokenCollateral, address cTokenBorrowed, address liquidator, address borrower, uint256 seizeTokens ) external; function transferAllowed( address cToken, address src, address dst, uint256 transferTokens ) external returns (uint256); function transferVerify( address cToken, address src, address dst, uint256 transferTokens ) external; /*** Liquidity/Liquidation Calculations ***/ function liquidateCalculateSeizeTokens( address cTokenBorrowed, address cTokenCollateral, uint256 repayAmount ) external view returns (uint256, uint256); } interface ComptrollerInterfaceExtension { function checkMembership(address account, CToken cToken) external view returns (bool); function updateCTokenVersion(address cToken, ComptrollerV1Storage.Version version) external; function flashloanAllowed( address cToken, address receiver, uint256 amount, bytes calldata params ) external view returns (bool); function getAccountLiquidity(address account) external view returns ( uint256, uint256, uint256 ); } pragma solidity ^0.5.16; import "./CToken.sol"; import "./PriceOracle/PriceOracle.sol"; contract UnitrollerAdminStorage { /** * @notice Administrator for this contract */ address public admin; /** * @notice Pending administrator for this contract */ address public pendingAdmin; /** * @notice Active brains of Unitroller */ address public comptrollerImplementation; /** * @notice Pending brains of Unitroller */ address public pendingComptrollerImplementation; } contract ComptrollerV1Storage is UnitrollerAdminStorage { /** * @notice Oracle which gives the price of any given asset */ PriceOracle public oracle; /** * @notice Multiplier used to calculate the maximum repayAmount when liquidating a borrow */ uint256 public closeFactorMantissa; /** * @notice Multiplier representing the discount on collateral that a liquidator receives */ uint256 public liquidationIncentiveMantissa; /** * @notice Per-account mapping of "assets you are in" */ mapping(address => CToken[]) public accountAssets; enum Version { VANILLA, COLLATERALCAP, WRAPPEDNATIVE } struct Market { /// @notice Whether or not this market is listed bool isListed; /** * @notice Multiplier representing the most one can borrow against their collateral in this market. * For instance, 0.9 to allow borrowing 90% of collateral value. * Must be between 0 and 1, and stored as a mantissa. */ uint256 collateralFactorMantissa; /// @notice Per-market mapping of "accounts in this asset" mapping(address => bool) accountMembership; /// @notice CToken version Version version; } /** * @notice Official mapping of cTokens -> Market metadata * @dev Used e.g. to determine if a market is supported */ mapping(address => Market) public markets; /** * @notice The Pause Guardian can pause certain actions as a safety mechanism. * Actions which allow users to remove their own assets cannot be paused. * Liquidation / seizing / transfer can only be paused globally, not by market. */ address public pauseGuardian; bool public _mintGuardianPaused; bool public _borrowGuardianPaused; bool public transferGuardianPaused; bool public seizeGuardianPaused; mapping(address => bool) public mintGuardianPaused; mapping(address => bool) public borrowGuardianPaused; struct CompMarketState { /// @notice The market's last updated compBorrowIndex or compSupplyIndex uint224 index; /// @notice The block number the index was last updated at uint32 block; } /// @notice A list of all markets CToken[] public allMarkets; /// @notice The portion of compRate that each market currently receives /// @dev This storage is depreacted. mapping(address => uint256) public compSpeeds; /// @notice The COMP market supply state for each market /// @dev This storage is depreacted. mapping(address => CompMarketState) public compSupplyState; /// @notice The COMP market borrow state for each market /// @dev This storage is depreacted. mapping(address => CompMarketState) public compBorrowState; /// @notice The COMP borrow index for each market for each supplier as of the last time they accrued COMP /// @dev This storage is depreacted. mapping(address => mapping(address => uint256)) public compSupplierIndex; /// @notice The COMP borrow index for each market for each borrower as of the last time they accrued COMP /// @dev This storage is depreacted. mapping(address => mapping(address => uint256)) public compBorrowerIndex; /// @notice The COMP accrued but not yet transferred to each user /// @dev This storage is depreacted. mapping(address => uint256) public compAccrued; /// @notice The borrowCapGuardian can set borrowCaps to any number for any market. Lowering the borrow cap could disable borrowing on the given market. address public borrowCapGuardian; /// @notice Borrow caps enforced by borrowAllowed for each cToken address. Defaults to zero which corresponds to unlimited borrowing. mapping(address => uint256) public borrowCaps; /// @notice The supplyCapGuardian can set supplyCaps to any number for any market. Lowering the supply cap could disable supplying to the given market. address public supplyCapGuardian; /// @notice Supply caps enforced by mintAllowed for each cToken address. Defaults to zero which corresponds to unlimited supplying. mapping(address => uint256) public supplyCaps; /// @notice creditLimits allowed specific protocols to borrow and repay without collateral. /// @dev This storage is depreacted. mapping(address => uint256) internal _oldCreditLimits; /// @notice flashloanGuardianPaused can pause flash loan as a safety mechanism. mapping(address => bool) public flashloanGuardianPaused; /// @notice liquidityMining the liquidity mining module that handles the LM rewards distribution. address public liquidityMining; /// @notice creditLimits allowed specific protocols to borrow and repay specific markets without collateral. mapping(address => mapping(address => uint256)) internal _creditLimits; } pragma solidity ^0.5.16; /** * @title ERC 20 Token Standard Interface * https://eips.ethereum.org/EIPS/eip-20 */ interface EIP20Interface { function name() external view returns (string memory); function symbol() external view returns (string memory); function decimals() external view returns (uint8); /** * @notice Get the total number of tokens in circulation * @return The supply of tokens */ function totalSupply() external view returns (uint256); /** * @notice Gets the balance of the specified address * @param owner The address from which the balance will be retrieved * @return The balance */ function balanceOf(address owner) external view returns (uint256 balance); /** * @notice Transfer `amount` tokens from `msg.sender` to `dst` * @param dst The address of the destination account * @param amount The number of tokens to transfer * @return Whether or not the transfer succeeded */ function transfer(address dst, uint256 amount) external returns (bool success); /** * @notice Transfer `amount` tokens from `src` to `dst` * @param src The address of the source account * @param dst The address of the destination account * @param amount The number of tokens to transfer * @return Whether or not the transfer succeeded */ function transferFrom( address src, address dst, uint256 amount ) external returns (bool success); /** * @notice Approve `spender` to transfer up to `amount` from `src` * @dev This will overwrite the approval amount for `spender` * and is subject to issues noted [here](https://eips.ethereum.org/EIPS/eip-20#approve) * @param spender The address of the account which may transfer tokens * @param amount The number of tokens that are approved (-1 means infinite) * @return Whether or not the approval succeeded */ function approve(address spender, uint256 amount) external returns (bool success); /** * @notice Get the current allowance from `owner` for `spender` * @param owner The address of the account which owns the tokens to be spent * @param spender The address of the account which may transfer tokens * @return The number of tokens allowed to be spent (-1 means infinite) */ function allowance(address owner, address spender) external view returns (uint256 remaining); event Transfer(address indexed from, address indexed to, uint256 amount); event Approval(address indexed owner, address indexed spender, uint256 amount); } pragma solidity ^0.5.16; /** * @title EIP20NonStandardInterface * @dev Version of ERC20 with no return values for `transfer` and `transferFrom` * See https://medium.com/coinmonks/missing-return-value-bug-at-least-130-tokens-affected-d67bf08521ca */ interface EIP20NonStandardInterface { /** * @notice Get the total number of tokens in circulation * @return The supply of tokens */ function totalSupply() external view returns (uint256); /** * @notice Gets the balance of the specified address * @param owner The address from which the balance will be retrieved * @return The balance */ function balanceOf(address owner) external view returns (uint256 balance); /// /// !!!!!!!!!!!!!! /// !!! NOTICE !!! `transfer` does not return a value, in violation of the ERC-20 specification /// !!!!!!!!!!!!!! /// /** * @notice Transfer `amount` tokens from `msg.sender` to `dst` * @param dst The address of the destination account * @param amount The number of tokens to transfer */ function transfer(address dst, uint256 amount) external; /// /// !!!!!!!!!!!!!! /// !!! NOTICE !!! `transferFrom` does not return a value, in violation of the ERC-20 specification /// !!!!!!!!!!!!!! /// /** * @notice Transfer `amount` tokens from `src` to `dst` * @param src The address of the source account * @param dst The address of the destination account * @param amount The number of tokens to transfer */ function transferFrom( address src, address dst, uint256 amount ) external; /** * @notice Approve `spender` to transfer up to `amount` from `src` * @dev This will overwrite the approval amount for `spender` * and is subject to issues noted [here](https://eips.ethereum.org/EIPS/eip-20#approve) * @param spender The address of the account which may transfer tokens * @param amount The number of tokens that are approved * @return Whether or not the approval succeeded */ function approve(address spender, uint256 amount) external returns (bool success); /** * @notice Get the current allowance from `owner` for `spender` * @param owner The address of the account which owns the tokens to be spent * @param spender The address of the account which may transfer tokens * @return The number of tokens allowed to be spent */ function allowance(address owner, address spender) external view returns (uint256 remaining); event Transfer(address indexed from, address indexed to, uint256 amount); event Approval(address indexed owner, address indexed spender, uint256 amount); } pragma solidity ^0.5.16; interface ERC3156FlashBorrowerInterface { /** * @dev Receive a flash loan. * @param initiator The initiator of the loan. * @param token The loan currency. * @param amount The amount of tokens lent. * @param fee The additional amount of tokens to repay. * @param data Arbitrary data structure, intended to contain user-defined parameters. * @return The keccak256 hash of "ERC3156FlashBorrower.onFlashLoan" */ function onFlashLoan( address initiator, address token, uint256 amount, uint256 fee, bytes calldata data ) external returns (bytes32); } pragma solidity ^0.5.16; contract ComptrollerErrorReporter { enum Error { NO_ERROR, UNAUTHORIZED, COMPTROLLER_MISMATCH, INSUFFICIENT_SHORTFALL, INSUFFICIENT_LIQUIDITY, INVALID_CLOSE_FACTOR, INVALID_COLLATERAL_FACTOR, INVALID_LIQUIDATION_INCENTIVE, MARKET_NOT_ENTERED, // no longer possible MARKET_NOT_LISTED, MARKET_ALREADY_LISTED, MATH_ERROR, NONZERO_BORROW_BALANCE, PRICE_ERROR, REJECTION, SNAPSHOT_ERROR, TOO_MANY_ASSETS, TOO_MUCH_REPAY } enum FailureInfo { ACCEPT_ADMIN_PENDING_ADMIN_CHECK, ACCEPT_PENDING_IMPLEMENTATION_ADDRESS_CHECK, EXIT_MARKET_BALANCE_OWED, EXIT_MARKET_REJECTION, SET_CLOSE_FACTOR_OWNER_CHECK, SET_CLOSE_FACTOR_VALIDATION, SET_COLLATERAL_FACTOR_OWNER_CHECK, SET_COLLATERAL_FACTOR_NO_EXISTS, SET_COLLATERAL_FACTOR_VALIDATION, SET_COLLATERAL_FACTOR_WITHOUT_PRICE, SET_IMPLEMENTATION_OWNER_CHECK, SET_LIQUIDATION_INCENTIVE_OWNER_CHECK, SET_LIQUIDATION_INCENTIVE_VALIDATION, SET_MAX_ASSETS_OWNER_CHECK, SET_PENDING_ADMIN_OWNER_CHECK, SET_PENDING_IMPLEMENTATION_OWNER_CHECK, SET_PRICE_ORACLE_OWNER_CHECK, SUPPORT_MARKET_EXISTS, SUPPORT_MARKET_OWNER_CHECK, SET_PAUSE_GUARDIAN_OWNER_CHECK } /** * @dev `error` corresponds to enum Error; `info` corresponds to enum FailureInfo, and `detail` is an arbitrary * contract-specific code that enables us to report opaque error codes from upgradeable contracts. **/ event Failure(uint256 error, uint256 info, uint256 detail); /** * @dev use this when reporting a known error from the money market or a non-upgradeable collaborator */ function fail(Error err, FailureInfo info) internal returns (uint256) { emit Failure(uint256(err), uint256(info), 0); return uint256(err); } /** * @dev use this when reporting an opaque error from an upgradeable collaborator contract */ function failOpaque( Error err, FailureInfo info, uint256 opaqueError ) internal returns (uint256) { emit Failure(uint256(err), uint256(info), opaqueError); return uint256(err); } } contract TokenErrorReporter { enum Error { NO_ERROR, UNAUTHORIZED, BAD_INPUT, COMPTROLLER_REJECTION, COMPTROLLER_CALCULATION_ERROR, INTEREST_RATE_MODEL_ERROR, INVALID_ACCOUNT_PAIR, INVALID_CLOSE_AMOUNT_REQUESTED, INVALID_COLLATERAL_FACTOR, MATH_ERROR, MARKET_NOT_FRESH, MARKET_NOT_LISTED, TOKEN_INSUFFICIENT_ALLOWANCE, TOKEN_INSUFFICIENT_BALANCE, TOKEN_INSUFFICIENT_CASH, TOKEN_TRANSFER_IN_FAILED, TOKEN_TRANSFER_OUT_FAILED } /* * Note: FailureInfo (but not Error) is kept in alphabetical order * This is because FailureInfo grows significantly faster, and * the order of Error has some meaning, while the order of FailureInfo * is entirely arbitrary. */ enum FailureInfo { ACCEPT_ADMIN_PENDING_ADMIN_CHECK, ACCRUE_INTEREST_BORROW_RATE_CALCULATION_FAILED, BORROW_ACCRUE_INTEREST_FAILED, BORROW_CASH_NOT_AVAILABLE, BORROW_FRESHNESS_CHECK, BORROW_MARKET_NOT_LISTED, BORROW_COMPTROLLER_REJECTION, LIQUIDATE_ACCRUE_BORROW_INTEREST_FAILED, LIQUIDATE_ACCRUE_COLLATERAL_INTEREST_FAILED, LIQUIDATE_COLLATERAL_FRESHNESS_CHECK, LIQUIDATE_COMPTROLLER_REJECTION, LIQUIDATE_COMPTROLLER_CALCULATE_AMOUNT_SEIZE_FAILED, LIQUIDATE_CLOSE_AMOUNT_IS_UINT_MAX, LIQUIDATE_CLOSE_AMOUNT_IS_ZERO, LIQUIDATE_FRESHNESS_CHECK, LIQUIDATE_LIQUIDATOR_IS_BORROWER, LIQUIDATE_REPAY_BORROW_FRESH_FAILED, LIQUIDATE_SEIZE_COMPTROLLER_REJECTION, LIQUIDATE_SEIZE_LIQUIDATOR_IS_BORROWER, LIQUIDATE_SEIZE_TOO_MUCH, MINT_ACCRUE_INTEREST_FAILED, MINT_COMPTROLLER_REJECTION, MINT_FRESHNESS_CHECK, MINT_TRANSFER_IN_FAILED, MINT_TRANSFER_IN_NOT_POSSIBLE, REDEEM_ACCRUE_INTEREST_FAILED, REDEEM_COMPTROLLER_REJECTION, REDEEM_FRESHNESS_CHECK, REDEEM_TRANSFER_OUT_NOT_POSSIBLE, REDUCE_RESERVES_ACCRUE_INTEREST_FAILED, REDUCE_RESERVES_ADMIN_CHECK, REDUCE_RESERVES_CASH_NOT_AVAILABLE, REDUCE_RESERVES_FRESH_CHECK, REDUCE_RESERVES_VALIDATION, REPAY_BEHALF_ACCRUE_INTEREST_FAILED, REPAY_BORROW_ACCRUE_INTEREST_FAILED, REPAY_BORROW_COMPTROLLER_REJECTION, REPAY_BORROW_FRESHNESS_CHECK, REPAY_BORROW_TRANSFER_IN_NOT_POSSIBLE, SET_COLLATERAL_FACTOR_OWNER_CHECK, SET_COLLATERAL_FACTOR_VALIDATION, SET_COMPTROLLER_OWNER_CHECK, SET_INTEREST_RATE_MODEL_ACCRUE_INTEREST_FAILED, SET_INTEREST_RATE_MODEL_FRESH_CHECK, SET_INTEREST_RATE_MODEL_OWNER_CHECK, SET_MAX_ASSETS_OWNER_CHECK, SET_ORACLE_MARKET_NOT_LISTED, SET_PENDING_ADMIN_OWNER_CHECK, SET_RESERVE_FACTOR_ACCRUE_INTEREST_FAILED, SET_RESERVE_FACTOR_ADMIN_CHECK, SET_RESERVE_FACTOR_FRESH_CHECK, SET_RESERVE_FACTOR_BOUNDS_CHECK, TRANSFER_COMPTROLLER_REJECTION, TRANSFER_NOT_ALLOWED, ADD_RESERVES_ACCRUE_INTEREST_FAILED, ADD_RESERVES_FRESH_CHECK, ADD_RESERVES_TRANSFER_IN_NOT_POSSIBLE } /** * @dev `error` corresponds to enum Error; `info` corresponds to enum FailureInfo, and `detail` is an arbitrary * contract-specific code that enables us to report opaque error codes from upgradeable contracts. **/ event Failure(uint256 error, uint256 info, uint256 detail); /** * @dev use this when reporting a known error from the money market or a non-upgradeable collaborator */ function fail(Error err, FailureInfo info) internal returns (uint256) { emit Failure(uint256(err), uint256(info), 0); return uint256(err); } /** * @dev use this when reporting an opaque error from an upgradeable collaborator contract */ function failOpaque( Error err, FailureInfo info, uint256 opaqueError ) internal returns (uint256) { emit Failure(uint256(err), uint256(info), opaqueError); return uint256(err); } } pragma solidity ^0.5.16; import "./CarefulMath.sol"; /** * @title Exponential module for storing fixed-precision decimals * @author Compound * @notice Exp is a struct which stores decimals with a fixed precision of 18 decimal places. * Thus, if we wanted to store the 5.1, mantissa would store 5.1e18. That is: * `Exp({mantissa: 5100000000000000000})`. */ contract Exponential is CarefulMath { uint256 constant expScale = 1e18; uint256 constant doubleScale = 1e36; uint256 constant halfExpScale = expScale / 2; uint256 constant mantissaOne = expScale; struct Exp { uint256 mantissa; } struct Double { uint256 mantissa; } /** * @dev Creates an exponential from numerator and denominator values. * Note: Returns an error if (`num` * 10e18) > MAX_INT, * or if `denom` is zero. */ function getExp(uint256 num, uint256 denom) internal pure returns (MathError, Exp memory) { (MathError err0, uint256 scaledNumerator) = mulUInt(num, expScale); if (err0 != MathError.NO_ERROR) { return (err0, Exp({mantissa: 0})); } (MathError err1, uint256 rational) = divUInt(scaledNumerator, denom); if (err1 != MathError.NO_ERROR) { return (err1, Exp({mantissa: 0})); } return (MathError.NO_ERROR, Exp({mantissa: rational})); } /** * @dev Adds two exponentials, returning a new exponential. */ function addExp(Exp memory a, Exp memory b) internal pure returns (MathError, Exp memory) { (MathError error, uint256 result) = addUInt(a.mantissa, b.mantissa); return (error, Exp({mantissa: result})); } /** * @dev Subtracts two exponentials, returning a new exponential. */ function subExp(Exp memory a, Exp memory b) internal pure returns (MathError, Exp memory) { (MathError error, uint256 result) = subUInt(a.mantissa, b.mantissa); return (error, Exp({mantissa: result})); } /** * @dev Multiply an Exp by a scalar, returning a new Exp. */ function mulScalar(Exp memory a, uint256 scalar) internal pure returns (MathError, Exp memory) { (MathError err0, uint256 scaledMantissa) = mulUInt(a.mantissa, scalar); if (err0 != MathError.NO_ERROR) { return (err0, Exp({mantissa: 0})); } return (MathError.NO_ERROR, Exp({mantissa: scaledMantissa})); } /** * @dev Multiply an Exp by a scalar, then truncate to return an unsigned integer. */ function mulScalarTruncate(Exp memory a, uint256 scalar) internal pure returns (MathError, uint256) { (MathError err, Exp memory product) = mulScalar(a, scalar); if (err != MathError.NO_ERROR) { return (err, 0); } return (MathError.NO_ERROR, truncate(product)); } /** * @dev Multiply an Exp by a scalar, truncate, then add an to an unsigned integer, returning an unsigned integer. */ function mulScalarTruncateAddUInt( Exp memory a, uint256 scalar, uint256 addend ) internal pure returns (MathError, uint256) { (MathError err, Exp memory product) = mulScalar(a, scalar); if (err != MathError.NO_ERROR) { return (err, 0); } return addUInt(truncate(product), addend); } /** * @dev Multiply an Exp by a scalar, then truncate to return an unsigned integer. */ function mul_ScalarTruncate(Exp memory a, uint256 scalar) internal pure returns (uint256) { Exp memory product = mul_(a, scalar); return truncate(product); } /** * @dev Multiply an Exp by a scalar, truncate, then add an to an unsigned integer, returning an unsigned integer. */ function mul_ScalarTruncateAddUInt( Exp memory a, uint256 scalar, uint256 addend ) internal pure returns (uint256) { Exp memory product = mul_(a, scalar); return add_(truncate(product), addend); } /** * @dev Divide an Exp by a scalar, returning a new Exp. */ function divScalar(Exp memory a, uint256 scalar) internal pure returns (MathError, Exp memory) { (MathError err0, uint256 descaledMantissa) = divUInt(a.mantissa, scalar); if (err0 != MathError.NO_ERROR) { return (err0, Exp({mantissa: 0})); } return (MathError.NO_ERROR, Exp({mantissa: descaledMantissa})); } /** * @dev Divide a scalar by an Exp, returning a new Exp. */ function divScalarByExp(uint256 scalar, Exp memory divisor) internal pure returns (MathError, Exp memory) { /* We are doing this as: getExp(mulUInt(expScale, scalar), divisor.mantissa) How it works: Exp = a / b; Scalar = s; `s / (a / b)` = `b * s / a` and since for an Exp `a = mantissa, b = expScale` */ (MathError err0, uint256 numerator) = mulUInt(expScale, scalar); if (err0 != MathError.NO_ERROR) { return (err0, Exp({mantissa: 0})); } return getExp(numerator, divisor.mantissa); } /** * @dev Divide a scalar by an Exp, then truncate to return an unsigned integer. */ function divScalarByExpTruncate(uint256 scalar, Exp memory divisor) internal pure returns (MathError, uint256) { (MathError err, Exp memory fraction) = divScalarByExp(scalar, divisor); if (err != MathError.NO_ERROR) { return (err, 0); } return (MathError.NO_ERROR, truncate(fraction)); } /** * @dev Divide a scalar by an Exp, returning a new Exp. */ function div_ScalarByExp(uint256 scalar, Exp memory divisor) internal pure returns (Exp memory) { /* We are doing this as: getExp(mulUInt(expScale, scalar), divisor.mantissa) How it works: Exp = a / b; Scalar = s; `s / (a / b)` = `b * s / a` and since for an Exp `a = mantissa, b = expScale` */ uint256 numerator = mul_(expScale, scalar); return Exp({mantissa: div_(numerator, divisor)}); } /** * @dev Divide a scalar by an Exp, then truncate to return an unsigned integer. */ function div_ScalarByExpTruncate(uint256 scalar, Exp memory divisor) internal pure returns (uint256) { Exp memory fraction = div_ScalarByExp(scalar, divisor); return truncate(fraction); } /** * @dev Multiplies two exponentials, returning a new exponential. */ function mulExp(Exp memory a, Exp memory b) internal pure returns (MathError, Exp memory) { (MathError err0, uint256 doubleScaledProduct) = mulUInt(a.mantissa, b.mantissa); if (err0 != MathError.NO_ERROR) { return (err0, Exp({mantissa: 0})); } // We add half the scale before dividing so that we get rounding instead of truncation. // See "Listing 6" and text above it at https://accu.org/index.php/journals/1717 // Without this change, a result like 6.6...e-19 will be truncated to 0 instead of being rounded to 1e-18. (MathError err1, uint256 doubleScaledProductWithHalfScale) = addUInt(halfExpScale, doubleScaledProduct); if (err1 != MathError.NO_ERROR) { return (err1, Exp({mantissa: 0})); } (MathError err2, uint256 product) = divUInt(doubleScaledProductWithHalfScale, expScale); // The only error `div` can return is MathError.DIVISION_BY_ZERO but we control `expScale` and it is not zero. assert(err2 == MathError.NO_ERROR); return (MathError.NO_ERROR, Exp({mantissa: product})); } /** * @dev Multiplies two exponentials given their mantissas, returning a new exponential. */ function mulExp(uint256 a, uint256 b) internal pure returns (MathError, Exp memory) { return mulExp(Exp({mantissa: a}), Exp({mantissa: b})); } /** * @dev Multiplies three exponentials, returning a new exponential. */ function mulExp3( Exp memory a, Exp memory b, Exp memory c ) internal pure returns (MathError, Exp memory) { (MathError err, Exp memory ab) = mulExp(a, b); if (err != MathError.NO_ERROR) { return (err, ab); } return mulExp(ab, c); } /** * @dev Divides two exponentials, returning a new exponential. * (a/scale) / (b/scale) = (a/scale) * (scale/b) = a/b, * which we can scale as an Exp by calling getExp(a.mantissa, b.mantissa) */ function divExp(Exp memory a, Exp memory b) internal pure returns (MathError, Exp memory) { return getExp(a.mantissa, b.mantissa); } /** * @dev Truncates the given exp to a whole number value. * For example, truncate(Exp{mantissa: 15 * expScale}) = 15 */ function truncate(Exp memory exp) internal pure returns (uint256) { // Note: We are not using careful math here as we're performing a division that cannot fail return exp.mantissa / expScale; } /** * @dev Checks if first Exp is less than second Exp. */ function lessThanExp(Exp memory left, Exp memory right) internal pure returns (bool) { return left.mantissa < right.mantissa; } /** * @dev Checks if left Exp <= right Exp. */ function lessThanOrEqualExp(Exp memory left, Exp memory right) internal pure returns (bool) { return left.mantissa <= right.mantissa; } /** * @dev returns true if Exp is exactly zero */ function isZeroExp(Exp memory value) internal pure returns (bool) { return value.mantissa == 0; } function safe224(uint256 n, string memory errorMessage) internal pure returns (uint224) { require(n < 2**224, errorMessage); return uint224(n); } function safe32(uint256 n, string memory errorMessage) internal pure returns (uint32) { require(n < 2**32, errorMessage); return uint32(n); } function add_(Exp memory a, Exp memory b) internal pure returns (Exp memory) { return Exp({mantissa: add_(a.mantissa, b.mantissa)}); } function add_(Double memory a, Double memory b) internal pure returns (Double memory) { return Double({mantissa: add_(a.mantissa, b.mantissa)}); } function add_(uint256 a, uint256 b) internal pure returns (uint256) { return add_(a, b, "addition overflow"); } function add_( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, errorMessage); return c; } function sub_(Exp memory a, Exp memory b) internal pure returns (Exp memory) { return Exp({mantissa: sub_(a.mantissa, b.mantissa)}); } function sub_(Double memory a, Double memory b) internal pure returns (Double memory) { return Double({mantissa: sub_(a.mantissa, b.mantissa)}); } function sub_(uint256 a, uint256 b) internal pure returns (uint256) { return sub_(a, b, "subtraction underflow"); } function sub_( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { require(b <= a, errorMessage); return a - b; } function mul_(Exp memory a, Exp memory b) internal pure returns (Exp memory) { return Exp({mantissa: mul_(a.mantissa, b.mantissa) / expScale}); } function mul_(Exp memory a, uint256 b) internal pure returns (Exp memory) { return Exp({mantissa: mul_(a.mantissa, b)}); } function mul_(uint256 a, Exp memory b) internal pure returns (uint256) { return mul_(a, b.mantissa) / expScale; } function mul_(Double memory a, Double memory b) internal pure returns (Double memory) { return Double({mantissa: mul_(a.mantissa, b.mantissa) / doubleScale}); } function mul_(Double memory a, uint256 b) internal pure returns (Double memory) { return Double({mantissa: mul_(a.mantissa, b)}); } function mul_(uint256 a, Double memory b) internal pure returns (uint256) { return mul_(a, b.mantissa) / doubleScale; } function mul_(uint256 a, uint256 b) internal pure returns (uint256) { return mul_(a, b, "multiplication overflow"); } function mul_( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { if (a == 0 || b == 0) { return 0; } uint256 c = a * b; require(c / a == b, errorMessage); return c; } function div_(Exp memory a, Exp memory b) internal pure returns (Exp memory) { return Exp({mantissa: div_(mul_(a.mantissa, expScale), b.mantissa)}); } function div_(Exp memory a, uint256 b) internal pure returns (Exp memory) { return Exp({mantissa: div_(a.mantissa, b)}); } function div_(uint256 a, Exp memory b) internal pure returns (uint256) { return div_(mul_(a, expScale), b.mantissa); } function div_(Double memory a, Double memory b) internal pure returns (Double memory) { return Double({mantissa: div_(mul_(a.mantissa, doubleScale), b.mantissa)}); } function div_(Double memory a, uint256 b) internal pure returns (Double memory) { return Double({mantissa: div_(a.mantissa, b)}); } function div_(uint256 a, Double memory b) internal pure returns (uint256) { return div_(mul_(a, doubleScale), b.mantissa); } function div_(uint256 a, uint256 b) internal pure returns (uint256) { return div_(a, b, "divide by zero"); } function div_( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { require(b > 0, errorMessage); return a / b; } function fraction(uint256 a, uint256 b) internal pure returns (Double memory) { return Double({mantissa: div_(mul_(a, doubleScale), b)}); } // 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(uint256 x) internal pure returns (uint256) { if (x == 0) return 0; uint256 xx = x; uint256 r = 1; if (xx >= 0x100000000000000000000000000000000) { xx >>= 128; r <<= 64; } if (xx >= 0x10000000000000000) { xx >>= 64; r <<= 32; } if (xx >= 0x100000000) { xx >>= 32; r <<= 16; } if (xx >= 0x10000) { xx >>= 16; r <<= 8; } if (xx >= 0x100) { xx >>= 8; r <<= 4; } if (xx >= 0x10) { xx >>= 4; r <<= 2; } if (xx >= 0x8) { r <<= 1; } r = (r + x / r) >> 1; r = (r + x / r) >> 1; r = (r + x / r) >> 1; r = (r + x / r) >> 1; r = (r + x / r) >> 1; r = (r + x / r) >> 1; r = (r + x / r) >> 1; // Seven iterations should be enough uint256 r1 = x / r; return (r < r1 ? r : r1); } } pragma solidity ^0.5.16; contract Comp { /// @notice EIP-20 token name for this token string public constant name = "Cream"; /// @notice EIP-20 token symbol for this token string public constant symbol = "CREAM"; /// @notice EIP-20 token decimals for this token uint8 public constant decimals = 18; /// @notice Total number of tokens in circulation uint256 public constant totalSupply = 9000000e18; // 9 million Comp /// @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 => uint256) public nonces; /// @notice An event thats emitted when an account changes its delegate event DelegateChanged(address indexed delegator, address indexed fromDelegate, address indexed toDelegate); /// @notice An event thats emitted when a delegate account's vote balance changes event DelegateVotesChanged(address indexed delegate, uint256 previousBalance, uint256 newBalance); /// @notice The 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 Comp 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 (uint256) { 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, uint256 rawAmount) external returns (bool) { uint96 amount; if (rawAmount == uint256(-1)) { amount = uint96(-1); } else { amount = safe96(rawAmount, "Comp::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 (uint256) { 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, uint256 rawAmount) external returns (bool) { uint96 amount = safe96(rawAmount, "Comp::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, uint256 rawAmount ) external returns (bool) { address spender = msg.sender; uint96 spenderAllowance = allowances[src][spender]; uint96 amount = safe96(rawAmount, "Comp::approve: amount exceeds 96 bits"); if (spender != src && spenderAllowance != uint96(-1)) { uint96 newAllowance = sub96( spenderAllowance, amount, "Comp::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, uint256 nonce, uint256 expiry, uint8 v, bytes32 r, bytes32 s ) public { bytes32 domainSeparator = keccak256( abi.encode(DOMAIN_TYPEHASH, keccak256(bytes(name)), getChainId(), address(this)) ); bytes32 structHash = keccak256(abi.encode(DELEGATION_TYPEHASH, delegatee, nonce, expiry)); bytes32 digest = keccak256(abi.encodePacked("\x19\x01", domainSeparator, structHash)); address signatory = ecrecover(digest, v, r, s); require(signatory != address(0), "Comp::delegateBySig: invalid signature"); require(nonce == nonces[signatory]++, "Comp::delegateBySig: invalid nonce"); require(now <= expiry, "Comp::delegateBySig: signature expired"); return _delegate(signatory, delegatee); } /** * @notice Gets the current votes balance for `account` * @param account The address to get votes balance * @return The number of current votes for `account` */ function getCurrentVotes(address account) external view returns (uint96) { uint32 nCheckpoints = numCheckpoints[account]; return nCheckpoints > 0 ? checkpoints[account][nCheckpoints - 1].votes : 0; } /** * @notice Determine the prior number of votes for an account as of a block number * @dev Block number must be a finalized block or else this function will revert to prevent misinformation. * @param account The address of the account to check * @param blockNumber The block number to get the vote balance at * @return The number of votes the account had as of the given block */ function getPriorVotes(address account, uint256 blockNumber) public view returns (uint96) { require(blockNumber < block.number, "Comp::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), "Comp::_transferTokens: cannot transfer from the zero address"); require(dst != address(0), "Comp::_transferTokens: cannot transfer to the zero address"); balances[src] = sub96(balances[src], amount, "Comp::_transferTokens: transfer amount exceeds balance"); balances[dst] = add96(balances[dst], amount, "Comp::_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, "Comp::_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, "Comp::_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, "Comp::_writeCheckpoint: block number exceeds 32 bits"); if (nCheckpoints > 0 && checkpoints[delegatee][nCheckpoints - 1].fromBlock == blockNumber) { checkpoints[delegatee][nCheckpoints - 1].votes = newVotes; } else { checkpoints[delegatee][nCheckpoints] = Checkpoint(blockNumber, newVotes); numCheckpoints[delegatee] = nCheckpoints + 1; } emit DelegateVotesChanged(delegatee, oldVotes, newVotes); } function safe32(uint256 n, string memory errorMessage) internal pure returns (uint32) { require(n < 2**32, errorMessage); return uint32(n); } function safe96(uint256 n, string memory errorMessage) internal pure returns (uint96) { require(n < 2**96, errorMessage); return uint96(n); } function add96( uint96 a, uint96 b, string memory errorMessage ) internal pure returns (uint96) { uint96 c = a + b; require(c >= a, errorMessage); return c; } function sub96( uint96 a, uint96 b, string memory errorMessage ) internal pure returns (uint96) { require(b <= a, errorMessage); return a - b; } function getChainId() internal pure returns (uint256) { uint256 chainId; assembly { chainId := chainid() } return chainId; } } pragma solidity ^0.5.16; /** * @title Compound's InterestRateModel Interface * @author Compound */ contract InterestRateModel { /// @notice Indicator that this is an InterestRateModel contract (for inspection) bool public constant isInterestRateModel = true; /** * @notice Calculates the current borrow interest rate per block * @param cash The total amount of cash the market has * @param borrows The total amount of borrows the market has outstanding * @param reserves The total amnount of reserves the market has * @return The borrow rate per block (as a percentage, and scaled by 1e18) */ function getBorrowRate( uint256 cash, uint256 borrows, uint256 reserves ) external view returns (uint256); /** * @notice Calculates the current supply interest rate per block * @param cash The total amount of cash the market has * @param borrows The total amount of borrows the market has outstanding * @param reserves The total amnount of reserves the market has * @param reserveFactorMantissa The current reserve factor the market has * @return The supply rate per block (as a percentage, and scaled by 1e18) */ function getSupplyRate( uint256 cash, uint256 borrows, uint256 reserves, uint256 reserveFactorMantissa ) external view returns (uint256); } pragma solidity ^0.5.16; contract LiquidityMiningInterface { function comptroller() external view returns (address); function updateSupplyIndex(address cToken, address[] calldata accounts) external; function updateBorrowIndex(address cToken, address[] calldata accounts) external; } pragma solidity ^0.5.16; import "../CToken.sol"; contract PriceOracle { /** * @notice Get the underlying price of a cToken asset * @param cToken The cToken to get the underlying price of * @return The underlying asset price mantissa (scaled by 1e18). * Zero means the price is unavailable. */ function getUnderlyingPrice(CToken cToken) external view returns (uint256); } pragma solidity ^0.5.16; import "./ErrorReporter.sol"; import "./ComptrollerStorage.sol"; /** * @title ComptrollerCore * @dev Storage for the comptroller is at this address, while execution is delegated to the `comptrollerImplementation`. * CTokens should reference this contract as their comptroller. */ contract Unitroller is UnitrollerAdminStorage, ComptrollerErrorReporter { /** * @notice Emitted when pendingComptrollerImplementation is changed */ event NewPendingImplementation(address oldPendingImplementation, address newPendingImplementation); /** * @notice Emitted when pendingComptrollerImplementation is accepted, which means comptroller implementation is updated */ event NewImplementation(address oldImplementation, address newImplementation); /** * @notice Emitted when pendingAdmin is changed */ event NewPendingAdmin(address oldPendingAdmin, address newPendingAdmin); /** * @notice Emitted when pendingAdmin is accepted, which means admin is updated */ event NewAdmin(address oldAdmin, address newAdmin); constructor() public { // Set admin to caller admin = msg.sender; } /*** Admin Functions ***/ function _setPendingImplementation(address newPendingImplementation) public returns (uint256) { if (msg.sender != admin) { return fail(Error.UNAUTHORIZED, FailureInfo.SET_PENDING_IMPLEMENTATION_OWNER_CHECK); } address oldPendingImplementation = pendingComptrollerImplementation; pendingComptrollerImplementation = newPendingImplementation; emit NewPendingImplementation(oldPendingImplementation, pendingComptrollerImplementation); return uint256(Error.NO_ERROR); } /** * @notice Accepts new implementation of comptroller. msg.sender must be pendingImplementation * @dev Admin function for new implementation to accept it's role as implementation * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _acceptImplementation() public returns (uint256) { // Check caller is pendingImplementation and pendingImplementation ≠ address(0) if (msg.sender != pendingComptrollerImplementation || pendingComptrollerImplementation == address(0)) { return fail(Error.UNAUTHORIZED, FailureInfo.ACCEPT_PENDING_IMPLEMENTATION_ADDRESS_CHECK); } // Save current values for inclusion in log address oldImplementation = comptrollerImplementation; address oldPendingImplementation = pendingComptrollerImplementation; comptrollerImplementation = pendingComptrollerImplementation; pendingComptrollerImplementation = address(0); emit NewImplementation(oldImplementation, comptrollerImplementation); emit NewPendingImplementation(oldPendingImplementation, pendingComptrollerImplementation); return uint256(Error.NO_ERROR); } /** * @notice Begins transfer of admin rights. The newPendingAdmin must call `_acceptAdmin` to finalize the transfer. * @dev Admin function to begin change of admin. The newPendingAdmin must call `_acceptAdmin` to finalize the transfer. * @param newPendingAdmin New pending admin. * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _setPendingAdmin(address newPendingAdmin) public returns (uint256) { // Check caller = admin if (msg.sender != admin) { return fail(Error.UNAUTHORIZED, FailureInfo.SET_PENDING_ADMIN_OWNER_CHECK); } // Save current value, if any, for inclusion in log address oldPendingAdmin = pendingAdmin; // Store pendingAdmin with value newPendingAdmin pendingAdmin = newPendingAdmin; // Emit NewPendingAdmin(oldPendingAdmin, newPendingAdmin) emit NewPendingAdmin(oldPendingAdmin, newPendingAdmin); return uint256(Error.NO_ERROR); } /** * @notice Accepts transfer of admin rights. msg.sender must be pendingAdmin * @dev Admin function for pending admin to accept role and update admin * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _acceptAdmin() public returns (uint256) { // Check caller is pendingAdmin and pendingAdmin ≠ address(0) if (msg.sender != pendingAdmin || msg.sender == address(0)) { return fail(Error.UNAUTHORIZED, FailureInfo.ACCEPT_ADMIN_PENDING_ADMIN_CHECK); } // Save current values for inclusion in log address oldAdmin = admin; address oldPendingAdmin = pendingAdmin; // Store admin with value pendingAdmin admin = pendingAdmin; // Clear the pending value pendingAdmin = address(0); emit NewAdmin(oldAdmin, admin); emit NewPendingAdmin(oldPendingAdmin, pendingAdmin); return uint256(Error.NO_ERROR); } /** * @dev Delegates execution to an implementation contract. * It returns to the external caller whatever the implementation returns * or forwards reverts. */ function() external payable { // delegate all other functions to current implementation (bool success, ) = comptrollerImplementation.delegatecall(msg.data); assembly { let free_mem_ptr := mload(0x40) returndatacopy(free_mem_ptr, 0, returndatasize) switch success case 0 { revert(free_mem_ptr, returndatasize) } default { return(free_mem_ptr, returndatasize) } } } }
Set the given borrow caps for the given cToken markets. Borrowing that brings total borrows to or above borrow cap will revert. Admin or borrowCapGuardian function to set the borrow caps. A borrow cap of 0 corresponds to unlimited borrowing. If the total supplies already exceeded the cap, it will prevent anyone to mint. cTokens The addresses of the markets (tokens) to change the borrow caps for newBorrowCaps The new borrow cap values in underlying to be set. A value of 0 corresponds to unlimited borrowing./
function _setMarketBorrowCaps(CToken[] calldata cTokens, uint256[] calldata newBorrowCaps) external { require(msg.sender == admin || msg.sender == borrowCapGuardian, "admin or borrow cap guardian only"); uint256 numMarkets = cTokens.length; uint256 numBorrowCaps = newBorrowCaps.length; require(numMarkets != 0 && numMarkets == numBorrowCaps, "invalid input"); for (uint256 i = 0; i < numMarkets; i++) { borrowCaps[address(cTokens[i])] = newBorrowCaps[i]; emit NewBorrowCap(cTokens[i], newBorrowCaps[i]); } }
351,117
// SPDX-License-Identifier: MIT pragma solidity ^0.8.4; /** * (c) Fundum Capital https://fundum.capital/ */ /** * @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 Interface for the optional metadata functions from the ERC20 standard. * * _Available since v4.1._ */ interface IERC20Metadata is IERC20 { /** * @dev Returns the name of the token. */ function name() external view returns (string memory); /** * @dev Returns the symbol of the token. */ function symbol() external view returns (string memory); /** * @dev Returns the decimals places of the token. */ function decimals() external view returns (uint8); } /* * @dev 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; } } /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor () { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } /** * @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 Ownable, IERC20, IERC20Metadata { mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; uint8 private _decimals; string private _name; string private _symbol; /** * @dev Sets the values for {name},{symbol},{decimal} and {totalSupply}. * * All of these values are immutable: they can only be set once during * construction. */ constructor (string memory name_, string memory symbol_, uint8 decimals_, uint256 initialSupply_) { _name = name_; _symbol = symbol_; _decimals = decimals_; _totalSupply = initialSupply_ * (10 ** _decimals); _balances[owner()] = _totalSupply; } /** * @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 _decimals; } /** * @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 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"); unchecked { _balances[sender] = senderBalance - amount; } _balances[recipient] += amount; emit Transfer(sender, recipient, amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens. * * This internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve(address owner, address spender, uint256 amount) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be to transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { } /** * @dev Transfers received ERC20 tokens to owner wallet */ function transferTokens(address erc20TokenAddress, uint256 amount) public onlyOwner returns (bool) { return IERC20(erc20TokenAddress).transfer(owner(), amount); } }
Transfers received ERC20 tokens to owner wallet/
function transferTokens(address erc20TokenAddress, uint256 amount) public onlyOwner returns (bool) { return IERC20(erc20TokenAddress).transfer(owner(), amount); }
10,124,650
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /* * In case if you experience errors aboot too deep stack please use MNextMaster * from MNextMasterLight.sol. * * It performs less checks which means less security on one hand but * compatibility with common configured EVMs like this of Ethereum ecosystem * on the other hand. * * To see the differences please read the leading comment in the file * MNextMasterLight.sol. */ import './MNextDataModel.sol'; contract MNextMaster is MNextDataModel{ /* * ########### * # STRUCTS # * ########### */ // //////// // / BANK / // //////// struct BankWrapper { Bank bank; bool isLocked; } // ///////// // / CHECK / // ///////// struct CheckWrapper { Check check; bool isLocked; } // //////// // / USER / // //////// struct User { uint8 state; bool isLocked; } // ////////////// // / UTXO (BTC) / // ////////////// struct BTCutxo { address utxo; uint256 satoshi; uint16 bank; uint256 account; } /* * #################### * # PUBLIC VARIABLES # * #################### */ ////////////////////////////// // SYSTEM'S KEY DESCRIPTORS // ////////////////////////////// string public name; string public token; string public symbol; string public admin; string public api; string public site; string public explorer; mapping (uint8 => NoteType) public noteTypes; /* * ##################### * # PRIVATE VARIABLES # * ##################### */ ///////////////////////////// // SYSTEM'S KEY CONTAINERS // ///////////////////////////// mapping (uint16 => BankWrapper) private _banks; mapping (uint256 => CheckWrapper) private _checks; mapping (uint256 => Coin) private _coins; mapping (uint256 => Note) private _notes; mapping (address => User) private _users; mapping (uint256 => BTCutxo) private _utxos; ///////////////////////////// // SYSTEM'S KEY CONDITIONS // ///////////////////////////// uint256 private _satoshiBase; int32 private _reserveRatio; uint16 private _multiplier; ///////////////////////// // MAINTENANCE HELPERS // ///////////////////////// uint16 private _nextBankId; uint256 private _nextCoinId; uint256 private _nextNoteId; uint256 private _nextCheckId; uint256 private _utxoPointer; //////////////////////////////// // SYSTEM ADMIN'S CREDENTIALS // //////////////////////////////// address payable private _rootUser; bytes32 private _rootKey; /* * Contract constructor * -------------------- * Construct the contract * * @param string memory sentence * A sentence to protect master access. * @param uint256 satoshiBase_ * Value to set as system's base unit. * @param int32 reserveRatio_ * Value to set as system's reserve ratio. * @param uint16 multiplier_ * Value to set as system's multiplier. */ constructor(string memory sentence, uint256 satoshiBase_, int32 reserveRatio_, uint16 multiplier_) payable { _rootUser = payable(msg.sender); _rootKey = keccak256(abi.encodePacked(sentence)); _satoshiBase = satoshiBase_; _reserveRatio = reserveRatio_; _multiplier = multiplier_; /* * SETUP BTC GATEWAY. */ _nextBankId = 0; _nextCheckId = 0; _nextCoinId = 0; _nextNoteId = 0; } // C A U T I O N ! ! ! // // Don't forget to remove the section below in production to save the system // tokens. /* * ################## * # Mock functions # * ################## */ /* * Get mock coins * -------------- * Create mock coins to the caller * * @param uint256 amount * Amount of coins to create. */ function mockCreateCoins(uint256 amount) external { _users[msg.sender].state = USER_ACTIVE_AND_RESTRICTIONLESS; for (uint256 i=0; i<amount; i++) { _coins[i] = Coin(address(0), i, 0, msg.sender, COIN_ACTIVE_AND_FREE); _nextCoinId++; } } /* * Get mock coins * -------------- * Create mock coins to a foreign user * * @param address user * Address of the user to create mock coins for. * @param uint256 amount * Amount of coins to create. */ function mockCreateUserWithBalance(address user, uint256 amount) external { _users[user].state = USER_ACTIVE_AND_RESTRICTIONLESS; for (uint256 i=0; i<amount; i++) { _coins[i] = Coin(address(0), i, 0, user, COIN_ACTIVE_AND_FREE); _nextCoinId++; } } /* * Mock transaction between users * ------------------------------ * Perform mock transaction between foreign users * * @param address sender * Address of the user to send mock coins from. * @param address target * Address of the user to send mock coins to. * @param uint256 amount * Amount of coins to create. * * @note Please keep in mind, though it's a mock transaction function, it * calls the real inside _transact() function. So sender must have * enough coins to send. The function mockCreateCoins() is useful to * help you out. */ function mockTransact(address sender, address target, uint256 amount) external returns (bool) { return _transact(sender, target, amount); } /* * ######################### * # End of mock functions # * ######################### */ // Don't forget to remove the section above in production to save the system // tokens. // // C A U T I O N ! ! ! /* * ######################## * # System level actions # * ######################## */ /* * Review coin supply * ------------------ * Review the coin supply of the system */ function review() external { _utxoPointer = 0; for (uint16 i=0; i < _nextBankId; i++) __reviewBank(i); __reviewCoins(); } /* * Set system admin name * --------------------- * Set the name of the system's admin * * @param string calldata sentence * A sentence to protect master access. * @param string calldata newAdmin * The new name of the admin. */ function setAdmin(string calldata sentence, string calldata newAdmin) onlyAdmin(sentence) external { admin = newAdmin; } /* * Set system API root * ------------------- * Set the link to the system's API root * * @param string calldata sentence * A sentence to protect master access. * @param string calldata newApi * The new link to the API root. */ function setApi(string calldata sentence, string calldata newApi) onlyAdmin(sentence) external { api = newApi; } /* * Set system explorer * ------------------- * Set the link to the system's data explorer * * @param string calldata sentence * A sentence to protect master access. * @param string calldata newExplorer * The new link to the explorer. */ function setExplorer(string calldata sentence, string calldata newExplorer) onlyAdmin(sentence) external { explorer = newExplorer; } /* * Set multiplier * -------------- * Set the value of the system's multiplier * * @param string calldata sentence * A sentence to protect master access. * @param uint16 newMultiplier_ * The new multiplier value. */ function setMultiplier(string calldata sentence, uint16 newMultiplier_) onlyAdmin(sentence) external { _multiplier = newMultiplier_; this.review(); } /* * Set system name * -------------- * Set the name of the system * * @param string calldata sentence * A sentence to protect master access. * @param string calldata newName * The new name of the system. */ function setName(string calldata sentence, string calldata newName) onlyAdmin(sentence) external { name = newName; } /* * Set reserve ratio * ----------------- * Set the value of the system's reserve ratio * * @param string calldata sentence * A sentence to protect master access. * @param int32 newReserveRatio_ * The new reserve ratio value. * * @note Since solidity doesn't handle fractions, to set the percentage * value you have to multiply the original (fraction) value with 100. */ function setReserveRatio(string calldata sentence, int32 newReserveRatio_) onlyAdmin(sentence) external { _reserveRatio = newReserveRatio_; this.review(); } /* * Set satoshi base * ---------------- * Set the value of the system's Satoshi base * * @param string calldata sentence * A sentence to protect master access. * @param uint256 newSatoshiBase_ * The new Satoshi base value. */ function setSatoshiBase(string calldata sentence, uint256 newSatoshiBase_) onlyAdmin(sentence) external { _satoshiBase = newSatoshiBase_; this.review(); } /* * Set system homepage * ------------------- * Set the link to the system's homepage * * @param string calldata sentence * A sentence to protect master access. * @param string calldata newSite * The new link to the homepage. */ function setSite(string calldata sentence, string calldata newSite) onlyAdmin(sentence) external { site = newSite; } /* * Set token symbol * ---------------- * Set the symbol of the system's token * * @param string calldata sentence * A sentence to protect master access. * @param string calldata newSymbol * The new symbol of the token. */ function setSymbol(string calldata sentence, string calldata newSymbol) onlyAdmin(sentence) external { symbol = newSymbol; } /* * Set token name * -------------- * Set the name of the system's token * * @param string calldata sentence * A sentence to protect master access. * @param string calldata newToken * The new name of the token. */ function setToken(string calldata sentence, string calldata newToken) onlyAdmin(sentence) external { token = newToken; } /* * ############################ * # System level information # * ############################ */ /* * Get multiplier * -------------- * Get the value of the system's multiplier * * @return uint16 * The actual multiplier value. */ function getMultiplier() external view returns (uint16) { return _multiplier; } /* * Get reserve ratio * ----------------- * Get the value of the system's reserve ratio * * @return int32 * The actual reserve ratio value. * * @note Since solidity doesn't handle fractions, to receive the percentage * value you have to divide the returned value with 100. */ function getReserveRatio() external view returns (int32) { return _reserveRatio; } /* * Get satoshi base * ---------------- * Get the value of the system's Satoshi base * * @return uint256 * The actual Satoshi base value. */ function getSatoshiBase() external view returns (uint256) { return _satoshiBase; } /* * Get active coin count * --------------------- * Get the count of active coins in the system * * @return uint256 * The actual count of active coins. */ function getCoinCount() external view returns (uint256) { uint256 result = 0; for (uint256 i=0; i < _nextCoinId; i++) if (_coins[i].state == COIN_ACTIVE_AND_FREE || _coins[i].state == COIN_ACTIVE_IN_CHECK || _coins[i].state == COIN_ACTIVE_IN_NOTE) result++; return result; } /* * ######### * # Banks # * ######### */ //////////// // CREATE // //////////// /* * Create bank * ----------- * Create (register) a bank * * @param string calldata sentence * A sentence to protect master access. * @param string calldata bankName * The name of the bank to register. * @param address mainAccount * An address to be used as the bank's main account. * @param string calldata firstPassPhrase * A password phrase to be used as the first [0] security key. */ function createBank(string calldata sentence, string calldata bankName, address mainAccount, string calldata firstPassPhrase) onlyAdmin(sentence) lockBank(_nextBankId) external returns (uint16) { uint16 thisId = _nextBankId; bytes32[] memory keyArray = new bytes32[] (1); keyArray[0] = keccak256(abi.encodePacked(firstPassPhrase)); _banks[thisId].bank.name = bankName; _banks[thisId].bank.api = ''; _banks[thisId].bank.site = ''; delete _banks[thisId].bank.accountsBTC; _banks[thisId].bank.mainAccount = mainAccount; delete _banks[thisId].bank.accounts; delete _banks[thisId].bank.keys; _banks[thisId].bank.state = BANK_CREATED; _nextBankId++; return thisId; } ////////// // READ // ////////// /* * Get a bank * ---------- * Get data of a bank * * @param uint16 id * ID of the check. * * @return Bank memory * The data of the given bank. * * @note Keys of the bank rest hidden. */ function getBank(uint16 id) external view returns (Bank memory) { bytes32[] memory keyArray = new bytes32[] (0); Bank memory result = _banks[id].bank; result.keys = keyArray; return result; } /* * Get bank count * -------------- * Get the count of all banks. * * @return uin16 * The count of the banks. */ function getBankCount() external view returns (uint16) { return _nextBankId; } /* * Get all banks * ------------- * Get data of all banks * * @return Bank[] memory * List of data of all banks. * * @note Keys of banks rest hidden. */ function getBanks() external view returns (Bank[] memory) { Bank[] memory result = new Bank[](_nextBankId); bytes32[] memory keyArray = new bytes32[] (0); for (uint16 i=0; i < _nextBankId; i++) { result[i] = _banks[i].bank; result[i].keys = keyArray; } return result; } //////////// // UPDATE // //////////// /* * TODO IMPLEMENT * * BTC accounts: * - addBankBTCAccount(uint16 id, string calldata sentence, address btcAccount) * - addBankBTCAccount(uint16 id, uint256 keyId, string calldata passPhrase, address btcAccount) * - activateBankBTCAccount(uint16 id, uint256 accountId, string calldata sentence) * - activateBankBTCAccount(uint16 id, uint256 accountId, uint256 keyId, string calldata passPhrase) * - deleteBankBTCAccount(uint16 id, uint256 accountId, string calldata sentence) * - deleteBankBTCAccount(uint16 id, uint256 accountId, uint256 keyId, string calldata passPhrase) * - suspendBankBTCAccount(uint16 id, uint256 accountId, string calldata sentence) * - suspendBankBTCAccount(uint16 id, uint256 accountId, uint256 keyId, string calldata passPhrase) * * Note: BTC account related functions autamotically call review() * * System accounts: * - addBankAccount(uint16 id, string calldata sentence, address account) * - addBankAccount(uint16 id, uint256 keyId, string calldata passPhrase, address account) * - activateBankAccount(uint16 id, uint256 accountId, string calldata sentence) * - activateBankAccount(uint16 id, uint256 accountId, uint256 keyId, string calldata passPhrase) * - deleteBankAccount(uint16 id, uint256 accountId, string calldata sentence) * - deleteBankAccount(uint16 id, uint256 accountId, uint256 keyId, string calldata passPhrase) * - suspendBankAccount(uint16 id, uint256 accountId, string calldata sentence) * - suspendBankAccount(uint16 id, uint256 accountId, uint256 keyId, string calldata passPhrase) * * - addBankKey(string calldata sentence, string calldata passPhrase) * - addBankKey(uint256 keyId, string calldata passPhrase, string calldata passPhrase) * - changeBankKey(uint16 id, uint256 affectedKeyId, string calldata sentence, string calldata newPassPhrase) * - changeBankKey(uint16 id, uint256 affectedKeyId, uint256 keyId, string calldata passPhrase, string calldata newPassPhrase) * * TODO: CHANGE * * - More complex key validation system. */ /* * Activate bank * ------------- * Activate a non activated bank * * @param uint16 id * The ID of the bank to activate. * @param string calldata sentence * A sentence to protect master access. */ function activateBank(uint16 id, string calldata sentence) onlyAdmin(sentence) onlyExistingBank(id) lockBank(id) external { require(_banks[id].bank.state == BANK_CREATED, 'Cannot activate bank with a non appropriate state.'); _banks[id].bank.state = BANK_ACTIVE_AND_RESTRICTIONLESS; } /* * Set API site link of a bank * --------------------------- * Set the link to the API root of the bank * * @param uint16 id * The ID of the bank. * @param string calldata sentence * A sentence to protect master access. * @param string calldata newApi * The new API site link to set. */ function setBankApi(uint16 id, string calldata sentence, string calldata newApi) onlyAdmin(sentence) onlyExistingBank(id) lockBank(id) external { _banks[id].bank.api = newApi; } /* * Set API site link of a bank * --------------------------- * Set the link to the API root of the bank * * @param uint16 id * The ID of the bank. * @param uint256 keyId * The ID of the key to valIdate transaction with. * @param string calldata passPhrase * A password phrase that matches the key to grant access. * @param string calldata newApi * The new API site link to set. */ function setBankApi(uint16 id, uint256 keyId, string calldata passPhrase, string calldata newApi) onlyExistingBank(id) lockBank(id) onlyValIdBankAction(id, keyId, passPhrase) external { _banks[id].bank.api = newApi; } /* * Set name of a bank * ------------------ * Set the name of the bank * * @param uint16 id * The ID of the bank. * @param string calldata sentence * A sentence to protect master access. * @param string calldata newName * The new name to set. */ function setBankName(uint16 id, string calldata sentence, string calldata newName) onlyAdmin(sentence) onlyExistingBank(id) lockBank(id) external { _banks[id].bank.name = newName; } /* * Set name of a bank * ------------------ * Set the name of the bank * * @param uint16 id * The ID of the bank. * @param uint256 keyId * The ID of the key to valIdate transaction with. * @param string calldata passPhrase * A password phrase that matches the key to grant access. * @param string calldata newName * The new name to set. */ function setBankName(uint16 id, uint256 keyId, string calldata passPhrase, string calldata newName) onlyExistingBank(id) lockBank(id) onlyValIdBankAction(id, keyId, passPhrase) external { _banks[id].bank.name = newName; } /* * Set homepage link of a bank * --------------------------- * Set the link to the homepage of the bank * * @param uint16 id * The ID of the bank. * @param string calldata sentence * A sentence to protect master access. * @param string calldata newSite * The new homepage link to set. */ function setBankSite(uint16 id, string calldata sentence, string calldata newSite) onlyAdmin(sentence) onlyExistingBank(id) lockBank(id) external { _banks[id].bank.site = newSite; } /* * Set homepage link of a bank * --------------------------- * Set the link to the homepage of the bank * * @param uint16 id * The ID of the bank. * @param uint256 keyId * The ID of the key to valIdate transaction with. * @param string calldata passPhrase * A password phrase that matches the key to grant access. * @param string calldata newSite * The new homepage link to set. */ function setBankSite(uint16 id, uint256 keyId, string calldata passPhrase, string calldata newSite) onlyExistingBank(id) lockBank(id) onlyValIdBankAction(id, keyId, passPhrase) external { _banks[id].bank.site = newSite; } /* * Suspend bank * ------------ * Suspend am active bank * * @param uint16 id * The ID of the bank to suspend. * @param string calldata sentence * A sentence to protect master access. */ function suspendBank(uint16 id, string calldata sentence) onlyAdmin(sentence) onlyExistingBank(id) lockBank(id) external { require(_banks[id].bank.state == BANK_SUSPENDED || _banks[id].bank.state == BANK_DELETED, 'Cannot suspend a bank with a non appropriate state.'); _banks[id].bank.state = BANK_SUSPENDED; } //////////// // DELETE // //////////// /* * Delete bank * ----------- * Delete an existing bank * * @param uint16 id * The ID of the bank to delete. * @param string calldata sentence * A sentence to protect master access. */ function deleteBank(uint16 id, string calldata sentence) onlyAdmin(sentence) onlyExistingBank(id) lockBank(id) external { require(_banks[id].bank.state == BANK_DELETED, 'Cannot delete an already deleted bank.'); _banks[id].bank.state = BANK_DELETED; } /* * ########## * # Checks # * ########## */ //////////// // CREATE // //////////// /* * Create check * ------------ * Create a check without activation * * @param uint256 amount * The amount of the check. * @param string memory passPhrase * A pharese to secure the check. */ function createActiveCheck(uint256 amount, string calldata passPhrase) lockUser(msg.sender) external returns (uint256) { return _createCheck(amount, passPhrase, CHECK_ACTIVATED); } /* * Create check * ------------ * Create a check with activation * * @param uint256 amount * The amount of the check. * @param string memory passPhrase * A pharese to secure the check. */ function createCheck(uint256 amount, string calldata passPhrase) lockUser(msg.sender) external returns (uint256) { return _createCheck(amount, passPhrase, CHECK_CREATED); } ////////// // READ // ////////// /* * Get a check * ----------- * Get data of a check * * @param uint256 id * ID of the check. * * @note Check's key is hIdden. This way the key of the check cannot be * retrieved. This design decision pushes big responsibility to the * end-users' application. */ function getCheck(uint256 id) external view returns (Check memory) { return Check(_checks[id].check.owner, _checks[id].check.coins, '', _checks[id].check.state); } /* * Get check value * --------------- * Get the value of a check * * @param uint256 id * ID of the check. * * @return uint256 * The value of the given check. */ function getCheckValue(uint256 id) external view returns (uint256) { return _checks[id].check.coins.length; } //////////// // UPDATE // //////////// /* * Activate check * -------------- * Activate a non activated check * * @param uint256 id * ID of the check. * @param string memory passPhrase * A pharese to secure the check. */ function activateCheck(uint256 id, string calldata passPhrase) lockCheck(id) onlyValIdCheckAction(id, msg.sender, passPhrase) external { require(_checks[id].check.state == CHECK_CREATED || _checks[id].check.state == CHECK_SUSPENDED, 'Cannot activate a check from a non appropriate state.'); _checks[id].check.state = CHECK_ACTIVATED; } /* * Clear check * ----------- * Clear an active check * * @param uint256 id * ID of the check. * @param string memory passPhrase * A pharese to secure the check. */ function clearCeck(uint256 id, address from, string calldata passPhrase) lockUser(msg.sender) lockUser(from) lockCheck(id) onlyValIdCheckAction(id, from, passPhrase) external { require(_checks[id].check.state == CHECK_ACTIVATED, 'Cannot clear a non active check.'); require(_checks[id].check.owner == from, 'Original owner is needed to clear check.'); require(_checks[id].check.key == keccak256(abi.encodePacked(passPhrase)), 'Cannot clear a not opened check.'); // Note: consider to do this after the for loop. It is a hard decision. _checks[id].check.state = CHECK_SPENT; // There's no lack of {}s in the for loop and if selector below. :-) for (uint256 i=0; i < _checks[id].check.coins.length; i++) if (_coins[_checks[id].check.coins[i]].owner != from || _coins[_checks[id].check.coins[i]].state != COIN_ACTIVE_IN_CHECK) revert('Internal error: Check clearance refused, safety first.'); else _coins[_checks[id].check.coins[i]].owner = msg.sender; } /* * Suspend check * ------------- * Suspend an existing and non suspended check * * @param uint256 id * ID of the check. * @param string memory passPhrase * A pharese to secure the check. */ function suspendCheck(uint256 id, string calldata passPhrase) lockCheck(id) onlyValIdCheckAction(id, msg.sender, passPhrase) external { require((_checks[id].check.state == CHECK_CREATED || _checks[id].check.state == CHECK_ACTIVATED), 'Cannot perform suspending on check with non appropriate state.'); _checks[id].check.state = CHECK_SUSPENDED; } //////////// // DELETE // //////////// /* * Delete a check * -------------- * Delete a not yet cleared check * * @param uint256 id * ID of the check. * @param string memory passPhrase * A pharese to secure the check. */ function deleteCheck(uint256 id, string calldata passPhrase) lockCheck(id) onlyValIdCheckAction(id, msg.sender, passPhrase) external { require((_checks[id].check.state == CHECK_CREATED || _checks[id].check.state == CHECK_ACTIVATED || _checks[id].check.state == CHECK_SUSPENDED), 'Cannot perform deletioon on check with non appropriate state.'); // There's no lack of {} in the for loop below. :-) for (uint i=0; i < _checks[id].check.coins.length; i++) _coins[_checks[id].check.coins[i]].state = COIN_ACTIVE_AND_FREE; _checks[id].check.state = CHECK_DELETED; } /* * ######### * # Notes # * ######### */ // TODO: IMPLEMENT /* * ############## * # Note types # * ############## */ // TODO: IMPLEMENT /* * ############################### * # User balance and user coins # * ############################### */ /* * Get the balance of a user * ------------------------- * Get the total balance of a user * * @param address owner * The address of the user to get balance for. * * @return uint256 * The balance of the user. */ function getBalance(address owner) external view returns (uint256) { uint256 result = 0; // There's no lack of {} in the for loop below. :-) for (uint256 i=0; i < _nextCoinId; i++) if (_coins[i].owner == owner) result += 1; return result; } /* * Get the coins of a user * ----------------------- * Get the list of all coins of a user * * @param address owner * The address of the user to get coins for. * * @return uint256[] * List if IDs of the coins of the user. */ function getCoins(address owner) external view returns (uint256[] memory) { // Becuse .push() is not available on memory arrays, a non-gas-friendly // workaround should be used. uint256 counter = 0; // There's no lack of {} in the for loop below. :-) for (uint256 i=0; i < _nextCoinId; i++) if (_coins[i].owner == owner) counter++; uint256[] memory result = new uint256[](counter); counter = 0; // There's no lack of {} in the for loop below. :-) for (uint256 i=0; i < _nextCoinId; i++) if (_coins[i].owner == owner) { result[counter] = i; counter++; } return result; } /* * ################ * # TRANSACTIONS # * ################ */ /* * Transact between users * ---------------------- * Perform transaction between users * * @param address target * Target address to send coins to. * @param uint256 amount * Amount of coins to send. * * @return bool * True if the transaction was successful, false if not. * * @note In most cases like ERC20 token standard event is imetted on * successful transactions. In this ecosystem the function transact() * is called by MNextUser contract, therefore it is more convenient * to return bool instead of emitting an event. Emitting event can * happen in the user's contract depending on the implementation. */ function transact(address target, uint256 amount) lockUser(msg.sender) lockUser(target) external returns (bool) { return _transact(msg.sender, target, amount); } /* * Transact between banks * ---------------------- * Perform transaction between banks * * @param uint16 id * ID of a bank to transact from. * @param uint256 keyId * The ID of the key to valIdate transaction with. * @param string calldata passPhrase * A password phrase that matches the key to grant access. * @param uint16 target * ID of a bank to transact to. * @param uint256 amount * Amount of coins to send. * * @return bool * True if the transaction was successful, false if not. * * @note In most cases like ERC20 token standard event is imetted on * successful transactions. In this ecosystem the function transact() * is called by MNextBank contract, therefore it is more convenient * to return bool instead of emitting an event. Emitting event can * happen in the bank's contract depending on the implementation. */ function transactBankToBank(uint16 id, uint256 keyId, string calldata passPhrase, uint16 target, uint256 amount) onlyExistingBank(id) lockBank(id) onlyValIdBankAction(id, keyId, passPhrase) onlyExistingBank(target) lockBank(target) external returns (bool) { return _transact(_banks[id].bank.mainAccount, _banks[target].bank.mainAccount, amount); } /* * Transact from bank to user * -------------------------- * Perform transaction from a bank to a user * * @param uint16 id * ID of a bank to transact from. * @param uint256 keyId * The ID of the key to valIdate transaction with. * @param string calldata passPhrase * A password phrase that matches the key to grant access. * @param address target * Target address to send coins to. * @param uint256 amount * Amount of coins to send. * * @return bool * True if the transaction was successful, false if not. * * @note In most cases like ERC20 token standard event is imetted on * successful transactions. In this ecosystem the function transact() * is called by MNextBank contract, therefore it is more convenient * to return bool instead of emitting an event. Emitting event can * happen in the bank's contract depending on the implementation. */ function transactBankToUser(uint16 id, uint256 keyId, string calldata passPhrase, address target, uint256 amount) onlyExistingBank(id) lockBank(id) onlyValIdBankAction(id, keyId, passPhrase) onlyExistingUser(target) lockUser(target) external returns (bool) { return _transact(_banks[id].bank.mainAccount, target, amount); } /* * Transact from user to bank * -------------------------- * Perform transaction from a user to a bank * * @param uint16 target * ID of a bank to transact to. * @param uint256 amount * Amount of coins to send. * * @return bool * True if the transaction was successful, false if not. * * @note In most cases like ERC20 token standard event is imetted on * successful transactions. In this ecosystem the function transact() * is called by MNextUser contract, therefore it is more convenient * to return bool instead of emitting an event. Emitting event can * happen in the user's contract depending on the implementation. */ function transactUserToBank(uint16 target, uint256 amount) lockUser(msg.sender) lockBank(target) external returns (bool) { return _transact(msg.sender, _banks[target].bank.mainAccount, amount); } // TODO: IMPLEMENT if bank want to use other than mainAccount both for // bank->bank, bank->user and user->bank transactions. /* * ###################### * # INTERNAL FUNCTIONS # * ###################### */ /* * Create check with state * ----------------------- * Create a check with the given state * * @param uint256 amount * The amount of the check. * @param string memory passPhrase * A pharese to secure the check. * @param uint8 state * The state to create check with. */ function _createCheck(uint256 amount, string calldata passPhrase, uint8 state) lockCheck(_nextCheckId) private returns (uint256) { // Becuse .push() is not available on memory arrays, a non-gas-friendly // workaround should be used. uint256 counter = 0; // There's no lack of {} in the for loop below. :-) for (uint256 i=0; i < _nextCoinId; i++) if (_coins[i].owner == msg.sender && _coins[i].state == COIN_ACTIVE_AND_FREE) counter++; require(counter >= amount, 'Not enough balance to create chekk.'); uint256[] memory coins = new uint256[](counter); counter = 0; for (uint256 i=0; i < _nextCoinId; i++) if (_coins[i].owner == msg.sender && _coins[i].state == COIN_ACTIVE_AND_FREE) { _coins[i].state = COIN_ACTIVE_IN_CHECK; coins[counter] = i; counter++; if (counter > amount) break; } uint256 _thisId = _nextCheckId; if (_checks[_thisId].isLocked) revert('Internal error: Check creation refused, safety first.'); _checks[_thisId].check = Check(msg.sender, coins, keccak256(abi.encodePacked(passPhrase)), state); _nextCheckId++; return _thisId; } /* * Transact * -------- * Perform transaction between addresses * * @param address owner * Target address to send coins from. * @param address target * Target address to send coins to. * @param uint256 amount * Amount of coins to send. * * @return bool * True if the transaction was successful, false if not. */ function _transact(address owner, address target, uint256 amount) internal returns (bool) { bool result = false; uint256[] memory coinSupply = new uint256[] (amount); uint256 counter = 0; for (uint256 i=0; i < _nextCoinId; i++) if (_coins[i].owner == owner && _coins[i].state == COIN_ACTIVE_AND_FREE) { coinSupply[counter] = i; counter++; if (counter == amount) { result = true; break; } } if (result) { for (uint256 i=0; i < coinSupply.length; i++) _coins[i].owner = target; } return result; } /* * ##################### * # PRIVATE FUNCTIONS # * ##################### */ /* * Review utxo deposits of a bank * ------------------------------ * Collects information about presenting utxo deposits of the given bank * * @param uint16 id * The ID of the bank to review. */ function __reviewBank(uint16 id) onlyExistingBank(id) lockBank(id) private { for (uint256 i=0; i<_banks[id].bank.accountsBTC.length; i++) { /* * ACCES BTC GATEWAY. */ uint256 responseLength = 0; address[] memory utxoList = new address[] (responseLength); uint256[] memory amountList = new uint256[] (responseLength); require(utxoList.length == amountList.length, 'BTC gateway error.'); for (uint256 j=0; j < utxoList.length; j++) { _utxos[_utxoPointer] = BTCutxo(utxoList[j], amountList[j], id, i); _utxoPointer++; } } } /* * Review all the system coins * --------------------------- * Review system coins whether hey have the needed BTC deposits or not */ function __reviewCoins() private { // HOW IT WORKS? // 1. Gets all available utxos // 2. Loops over coins and marks missing utxos // 3. If there are coins without deposits, attempts to swap or delete them // 4. If there are utxos without coins, they might used to coin swap // 5. If there are utxos withoot coins after swaps, attempts to create coins // 6. If something important happen in this functions events are mitted } /* * ############# * # MODIFIERS # * ############# */ /* * Lock a bank * ----------- * Attempt to lock a bank during its data gets changed * * @param uint16 id * The ID of the bank to lock. */ modifier lockBank(uint16 id) { require(!_banks[id].isLocked, 'Cannot perform action on a locked bank.'); _banks[id].isLocked = true; _; _banks[id].isLocked = false; } /* * Lock a check * ------------ * Attempt to lock a check during its data gets changed * * @param uint256 id * The ID of the check to lock. */ modifier lockCheck(uint256 id) { require(!_checks[id].isLocked, 'Cannot perform action on a locked check.'); _checks[id].isLocked = true; _; _checks[id].isLocked = false; } /* * Lock a user * ----------- * Attempt to lock a user during its data gets changed * * @param address wallet * The wallet of the user to lock. */ modifier lockUser(address wallet) { require(!_users[wallet].isLocked, 'Cannot perform action on a locked user.'); _users[wallet].isLocked = true; _; _users[wallet].isLocked = false; } /* * ValIdate admin * -------------- * ValIdate access of the master contract owner * * @param string memory sentence * A sentence to protect master access. */ modifier onlyAdmin(string memory sentence) { require(msg.sender == _rootUser, 'Only admin can perform the action.'); require(keccak256(abi.encodePacked(sentence)) == _rootKey, 'Authorization failed.'); _; } /* * Check existence of a bank * ------------------------- * Check whether a bank exists or not * * @param uint16 id * The ID of the bank to check. */ modifier onlyExistingBank(uint16 id) { require(_banks[id].bank.state != STATE_UNAVAILABLE, 'Bank id must exist.'); _; } /* * Check existence of a check * -------------------------- * Check whether a check exists or not * * @param uint256 id * The ID of the check to check. */ modifier onlyExistingCheck(uint256 id) { require(_checks[id].check.state != STATE_UNAVAILABLE, 'Check id must exist.'); _; } /* * Check existence of a coin * ------------------------- * Check whether a coin exists or not * * @param uint256 id * The ID of the coin to check. */ modifier onlyExistingCoin(uint256 id) { require(_coins[id].state != STATE_UNAVAILABLE, 'Coin id must exist.'); _; } /* * Check existence of a note * ------------------------- * Check whether a note exists or not * * @param uint256 id * The ID of the note to check. */ modifier onlyExistingNote(uint256 id) { require(_notes[id].state != STATE_UNAVAILABLE, 'Note id must exist.'); _; } /* * Check existence of a user * ------------------------- * Check whether a user exists locally or not * * @param address who * The address of the user to check. */ modifier onlyExistingUser(address who) { require(_users[who].state != STATE_UNAVAILABLE && _users[who].state != USER_DELETED, 'User must exist.'); _; } modifier onlyValIdBankAction(uint16 id, uint256 keyId, string calldata passPhrase) { require(_banks[id].bank.keys.length < keyId, 'Cannot valIdate a non existing key.'); require(_banks[id].bank.keys[keyId] == keccak256(abi.encodePacked(passPhrase)), 'Authorization failed.'); _; } /* * ValIdate check access * --------------------- * ValIdate access credentials to perform actions on a check * * @param uint256 id * ID of the check. * @param address owner * The address of owner of the check. * @param string memory passPhrase * A pharese to secure the check. */ modifier onlyValIdCheckAction(uint256 id, address owner, string calldata passPhrase) { require(_checks[id].check.owner == owner, 'Cannot perform action on a foreign check.'); require(_checks[id].check.key == keccak256(abi.encodePacked(passPhrase)), 'Cannot perform action on a not opened check.'); _; } }
Set reserve ratio ----------------- Set the value of the system's reserve ratio string calldata sentence A sentence to protect master access. int32 newReserveRatio_ The new reserve ratio value. @note Since solidity doesn't handle fractions, to set the percentage value you have to multiply the original (fraction) value with 100./
function setReserveRatio(string calldata sentence, int32 newReserveRatio_) onlyAdmin(sentence) external { _reserveRatio = newReserveRatio_; this.review(); }
2,507,064
/** *Submitted for verification at Etherscan.io on 2022-04-21 */ // SPDX-License-Identifier: MIT // File: alloyx-smart-contracts-v2/contracts/goldfinch/interfaces/ICreditLine.sol pragma solidity ^0.8.7; pragma experimental ABIEncoderV2; interface ICreditLine { function borrower() external view returns (address); function limit() external view returns (uint256); function maxLimit() external view returns (uint256); function interestApr() external view returns (uint256); function paymentPeriodInDays() external view returns (uint256); function principalGracePeriodInDays() external view returns (uint256); function termInDays() external view returns (uint256); function lateFeeApr() external view returns (uint256); function isLate() external view returns (bool); function withinPrincipalGracePeriod() external view returns (bool); // Accounting variables function balance() external view returns (uint256); function interestOwed() external view returns (uint256); function principalOwed() external view returns (uint256); function termEndTime() external view returns (uint256); function nextDueTime() external view returns (uint256); function interestAccruedAsOf() external view returns (uint256); function lastFullPaymentTime() external view returns (uint256); } // File: alloyx-smart-contracts-v2/contracts/goldfinch/interfaces/IV2CreditLine.sol pragma solidity ^0.8.7; abstract contract IV2CreditLine is ICreditLine { function principal() external view virtual returns (uint256); function totalInterestAccrued() external view virtual returns (uint256); function termStartTime() external view virtual returns (uint256); function setLimit(uint256 newAmount) external virtual; function setMaxLimit(uint256 newAmount) external virtual; function setBalance(uint256 newBalance) external virtual; function setPrincipal(uint256 _principal) external virtual; function setTotalInterestAccrued(uint256 _interestAccrued) external virtual; function drawdown(uint256 amount) external virtual; function assess() external virtual returns ( uint256, uint256, uint256 ); function initialize( address _config, address owner, address _borrower, uint256 _limit, uint256 _interestApr, uint256 _paymentPeriodInDays, uint256 _termInDays, uint256 _lateFeeApr, uint256 _principalGracePeriodInDays ) public virtual; function setTermEndTime(uint256 newTermEndTime) external virtual; function setNextDueTime(uint256 newNextDueTime) external virtual; function setInterestOwed(uint256 newInterestOwed) external virtual; function setPrincipalOwed(uint256 newPrincipalOwed) external virtual; function setInterestAccruedAsOf(uint256 newInterestAccruedAsOf) external virtual; function setWritedownAmount(uint256 newWritedownAmount) external virtual; function setLastFullPaymentTime(uint256 newLastFullPaymentTime) external virtual; function setLateFeeApr(uint256 newLateFeeApr) external virtual; function updateGoldfinchConfig() external virtual; } // File: alloyx-smart-contracts-v2/contracts/goldfinch/interfaces/ITranchedPool.sol pragma solidity ^0.8.7; abstract contract ITranchedPool { IV2CreditLine public creditLine; uint256 public createdAt; enum Tranches { Reserved, Senior, Junior } struct TrancheInfo { uint256 id; uint256 principalDeposited; uint256 principalSharePrice; uint256 interestSharePrice; uint256 lockedUntil; } struct PoolSlice { TrancheInfo seniorTranche; TrancheInfo juniorTranche; uint256 totalInterestAccrued; uint256 principalDeployed; } struct SliceInfo { uint256 reserveFeePercent; uint256 interestAccrued; uint256 principalAccrued; } struct ApplyResult { uint256 interestRemaining; uint256 principalRemaining; uint256 reserveDeduction; uint256 oldInterestSharePrice; uint256 oldPrincipalSharePrice; } function initialize( address _config, address _borrower, uint256 _juniorFeePercent, uint256 _limit, uint256 _interestApr, uint256 _paymentPeriodInDays, uint256 _termInDays, uint256 _lateFeeApr, uint256 _principalGracePeriodInDays, uint256 _fundableAt, uint256[] calldata _allowedUIDTypes ) public virtual; function getTranche(uint256 tranche) external view virtual returns (TrancheInfo memory); function pay(uint256 amount) external virtual; function lockJuniorCapital() external virtual; function lockPool() external virtual; function initializeNextSlice(uint256 _fundableAt) external virtual; function totalJuniorDeposits() external view virtual returns (uint256); function drawdown(uint256 amount) external virtual; function setFundableAt(uint256 timestamp) external virtual; function deposit(uint256 tranche, uint256 amount) external virtual returns (uint256 tokenId); function assess() external virtual; function depositWithPermit( uint256 tranche, uint256 amount, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) external virtual returns (uint256 tokenId); function availableToWithdraw(uint256 tokenId) external view virtual returns (uint256 interestRedeemable, uint256 principalRedeemable); function withdraw(uint256 tokenId, uint256 amount) external virtual returns (uint256 interestWithdrawn, uint256 principalWithdrawn); function withdrawMax(uint256 tokenId) external virtual returns (uint256 interestWithdrawn, uint256 principalWithdrawn); function withdrawMultiple(uint256[] calldata tokenIds, uint256[] calldata amounts) external virtual; } // File: alloyx-smart-contracts-v2/contracts/goldfinch/interfaces/ISeniorPool.sol pragma solidity ^0.8.7; abstract contract ISeniorPool { uint256 public sharePrice; uint256 public totalLoansOutstanding; uint256 public totalWritedowns; function deposit(uint256 amount) external virtual returns (uint256 depositShares); function depositWithPermit( uint256 amount, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) external virtual returns (uint256 depositShares); function withdraw(uint256 usdcAmount) external virtual returns (uint256 amount); function withdrawInFidu(uint256 fiduAmount) external virtual returns (uint256 amount); function sweepToCompound() public virtual; function sweepFromCompound() public virtual; function invest(ITranchedPool pool) public virtual; function estimateInvestment(ITranchedPool pool) public view virtual returns (uint256); function redeem(uint256 tokenId) public virtual; function writedown(uint256 tokenId) public virtual; function calculateWritedown(uint256 tokenId) public view virtual returns (uint256 writedownAmount); function assets() public view virtual returns (uint256); function getNumShares(uint256 amount) public view virtual returns (uint256); } // File: @openzeppelin/contracts/utils/math/Math.sol // OpenZeppelin Contracts (last updated v4.5.0) (utils/math/Math.sol) pragma solidity ^0.8.0; /** * @dev Standard math utilities missing in the Solidity language. */ library Math { /** * @dev Returns the largest of two numbers. */ function max(uint256 a, uint256 b) internal pure returns (uint256) { return a >= b ? a : b; } /** * @dev Returns the smallest of two numbers. */ function min(uint256 a, uint256 b) internal pure returns (uint256) { return a < b ? a : b; } /** * @dev Returns the average of two numbers. The result is rounded towards * zero. */ function average(uint256 a, uint256 b) internal pure returns (uint256) { // (a + b) / 2 can overflow. return (a & b) + (a ^ b) / 2; } /** * @dev Returns the ceiling of the division of two numbers. * * This differs from standard division with `/` in that it rounds up instead * of rounding down. */ function ceilDiv(uint256 a, uint256 b) internal pure returns (uint256) { // (a + b - 1) / b can overflow on addition, so we distribute. return a / b + (a % b == 0 ? 0 : 1); } } // File: @openzeppelin/contracts/utils/math/SafeMath.sol // 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; } } } // File: @openzeppelin/contracts/token/ERC721/IERC721Receiver.sol // OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721Receiver.sol) pragma solidity ^0.8.0; /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ interface IERC721Receiver { /** * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom} * by `operator` from `from`, this function is called. * * It must return its Solidity selector to confirm the token transfer. * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted. * * The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`. */ function onERC721Received( address operator, address from, uint256 tokenId, bytes calldata data ) external returns (bytes4); } // File: @openzeppelin/contracts/token/ERC721/utils/ERC721Holder.sol // OpenZeppelin Contracts v4.4.1 (token/ERC721/utils/ERC721Holder.sol) pragma solidity ^0.8.0; /** * @dev Implementation of the {IERC721Receiver} interface. * * Accepts all token transfers. * Make sure the contract is able to use its token with {IERC721-safeTransferFrom}, {IERC721-approve} or {IERC721-setApprovalForAll}. */ contract ERC721Holder is IERC721Receiver { /** * @dev See {IERC721Receiver-onERC721Received}. * * Always returns `IERC721Receiver.onERC721Received.selector`. */ function onERC721Received( address, address, uint256, bytes memory ) public virtual override returns (bytes4) { return this.onERC721Received.selector; } } // File: @openzeppelin/contracts/utils/Context.sol // OpenZeppelin Contracts v4.4.1 (utils/Context.sol) pragma solidity ^0.8.0; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } // File: @openzeppelin/contracts/security/Pausable.sol // OpenZeppelin Contracts v4.4.1 (security/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 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()); } } // File: @openzeppelin/contracts/access/Ownable.sol // OpenZeppelin Contracts v4.4.1 (access/Ownable.sol) pragma solidity ^0.8.0; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() { _transferOwnership(_msgSender()); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { _transferOwnership(address(0)); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); _transferOwnership(newOwner); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Internal function without access restriction. */ function _transferOwnership(address newOwner) internal virtual { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } } // File: @openzeppelin/contracts/utils/introspection/IERC165.sol // OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol) pragma solidity ^0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // File: @openzeppelin/contracts/token/ERC721/IERC721.sol // OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721.sol) pragma solidity ^0.8.0; /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721 is IERC165 { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes calldata data ) external; } // File: @openzeppelin/contracts/token/ERC721/extensions/IERC721Enumerable.sol // OpenZeppelin Contracts (last updated v4.5.0) (token/ERC721/extensions/IERC721Enumerable.sol) pragma solidity ^0.8.0; /** * @title ERC-721 Non-Fungible Token Standard, optional enumeration extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Enumerable is IERC721 { /** * @dev Returns the total amount of tokens stored by the contract. */ function totalSupply() external view returns (uint256); /** * @dev Returns a token ID owned by `owner` at a given `index` of its token list. * Use along with {balanceOf} to enumerate all of ``owner``'s tokens. */ function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256); /** * @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: alloyx-smart-contracts-v2/contracts/goldfinch/interfaces/IPoolTokens.sol pragma solidity ^0.8.7; interface IPoolTokens is IERC721, IERC721Enumerable { event TokenMinted( address indexed owner, address indexed pool, uint256 indexed tokenId, uint256 amount, uint256 tranche ); event TokenRedeemed( address indexed owner, address indexed pool, uint256 indexed tokenId, uint256 principalRedeemed, uint256 interestRedeemed, uint256 tranche ); event TokenBurned(address indexed owner, address indexed pool, uint256 indexed tokenId); struct TokenInfo { address pool; uint256 tranche; uint256 principalAmount; uint256 principalRedeemed; uint256 interestRedeemed; } struct MintParams { uint256 principalAmount; uint256 tranche; } function mint(MintParams calldata params, address to) external returns (uint256); function redeem( uint256 tokenId, uint256 principalRedeemed, uint256 interestRedeemed ) external; function burn(uint256 tokenId) external; function onPoolCreated(address newPool) external; function getTokenInfo(uint256 tokenId) external view returns (TokenInfo memory); function validPool(address sender) external view returns (bool); function isApprovedOrOwner(address spender, uint256 tokenId) external view returns (bool); } // File: @openzeppelin/contracts/utils/Address.sol // OpenZeppelin Contracts (last updated v4.5.0) (utils/Address.sol) pragma solidity ^0.8.1; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== * * [IMPORTANT] * ==== * You shouldn't rely on `isContract` to protect against flash loan attacks! * * Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets * like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract * constructor. * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize/address.code.length, which returns 0 // for contracts in construction, since the code is only stored at the end // of the constructor execution. return account.code.length > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); (bool success, bytes memory returndata) = target.delegatecall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // File: @openzeppelin/contracts/token/ERC20/IERC20.sol // OpenZeppelin Contracts (last updated v4.5.0) (token/ERC20/IERC20.sol) pragma solidity ^0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `to`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address to, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `from` to `to` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom( address from, address to, uint256 amount ) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // File: @openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol // OpenZeppelin Contracts v4.4.1 (token/ERC20/extensions/IERC20Metadata.sol) pragma solidity ^0.8.0; /** * @dev Interface for the optional metadata functions from the ERC20 standard. * * _Available since v4.1._ */ interface IERC20Metadata is IERC20 { /** * @dev Returns the name of the token. */ function name() external view returns (string memory); /** * @dev Returns the symbol of the token. */ function symbol() external view returns (string memory); /** * @dev Returns the decimals places of the token. */ function decimals() external view returns (uint8); } // File: @openzeppelin/contracts/token/ERC20/ERC20.sol // OpenZeppelin Contracts (last updated v4.5.0) (token/ERC20/ERC20.sol) pragma solidity ^0.8.0; /** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20PresetMinterPauser}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin Contracts guidelines: functions revert * instead returning `false` on failure. This behavior is nonetheless * conventional and does not conflict with the expectations of ERC20 * applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */ contract ERC20 is Context, IERC20, IERC20Metadata { mapping(address => uint256) private _balances; mapping(address => mapping(address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; /** * @dev Sets the values for {name} and {symbol}. * * The default value of {decimals} is 18. To select a different value for * {decimals} you should overload it. * * All two of these values are immutable: they can only be set once during * construction. */ constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @dev Returns the name of the token. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5.05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless this function is * overridden; * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view virtual override returns (uint8) { return 18; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view virtual override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `to` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address to, uint256 amount) public virtual override returns (bool) { address owner = _msgSender(); _transfer(owner, to, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * NOTE: If `amount` is the maximum `uint256`, the allowance is not updated on * `transferFrom`. This is semantically equivalent to an infinite approval. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { address owner = _msgSender(); _approve(owner, spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}. * * NOTE: Does not update the allowance if the current allowance * is the maximum `uint256`. * * Requirements: * * - `from` and `to` cannot be the zero address. * - `from` must have a balance of at least `amount`. * - the caller must have allowance for ``from``'s tokens of at least * `amount`. */ function transferFrom( address from, address to, uint256 amount ) public virtual override returns (bool) { address spender = _msgSender(); _spendAllowance(from, spender, amount); _transfer(from, to, amount); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { address owner = _msgSender(); _approve(owner, spender, _allowances[owner][spender] + addedValue); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { address owner = _msgSender(); uint256 currentAllowance = _allowances[owner][spender]; require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero"); unchecked { _approve(owner, spender, currentAllowance - subtractedValue); } return true; } /** * @dev Moves `amount` of tokens from `sender` to `recipient`. * * This internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `from` must have a balance of at least `amount`. */ function _transfer( address from, address to, uint256 amount ) internal virtual { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(from, to, amount); uint256 fromBalance = _balances[from]; require(fromBalance >= amount, "ERC20: transfer amount exceeds balance"); unchecked { _balances[from] = fromBalance - amount; } _balances[to] += amount; emit Transfer(from, to, amount); _afterTokenTransfer(from, to, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply += amount; _balances[account] += amount; emit Transfer(address(0), account, amount); _afterTokenTransfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); uint256 accountBalance = _balances[account]; require(accountBalance >= amount, "ERC20: burn amount exceeds balance"); unchecked { _balances[account] = accountBalance - amount; } _totalSupply -= amount; emit Transfer(account, address(0), amount); _afterTokenTransfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens. * * This internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve( address owner, address spender, uint256 amount ) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Spend `amount` form the allowance of `owner` toward `spender`. * * Does not update the allowance amount in case of infinite allowance. * Revert if not enough allowance is available. * * Might emit an {Approval} event. */ function _spendAllowance( address owner, address spender, uint256 amount ) internal virtual { uint256 currentAllowance = allowance(owner, spender); if (currentAllowance != type(uint256).max) { require(currentAllowance >= amount, "ERC20: insufficient allowance"); unchecked { _approve(owner, spender, currentAllowance - amount); } } } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 amount ) internal virtual {} /** * @dev Hook that is called after any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * has been transferred to `to`. * - when `from` is zero, `amount` tokens have been minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens have been burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _afterTokenTransfer( address from, address to, uint256 amount ) internal virtual {} } // File: alloyx-smart-contracts-v2/contracts/alloyx/AlloyxTokenCRWN.sol pragma solidity ^0.8.2; contract AlloyxTokenCRWN is ERC20, Ownable { constructor() ERC20("Crown Gold", "CRWN") {} function mint(address _account, uint256 _amount) external onlyOwner returns (bool) { _mint(_account, _amount); return true; } function burn(address _account, uint256 _amount) external onlyOwner returns (bool) { _burn(_account, _amount); return true; } function contractName() external pure returns (string memory) { return "AlloyxTokenCRWN"; } } // File: alloyx-smart-contracts-v2/contracts/alloyx/AlloyxTokenDURA.sol pragma solidity ^0.8.2; contract AlloyxTokenDURA is ERC20, Ownable { constructor() ERC20("Duralumin", "DURA") {} function mint(address _account, uint256 _amount) external onlyOwner returns (bool) { _mint(_account, _amount); return true; } function burn(address _account, uint256 _amount) external onlyOwner returns (bool) { _burn(_account, _amount); return true; } function contractName() external pure returns (string memory) { return "AlloyxTokenDura"; } } // File: @openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol // OpenZeppelin Contracts v4.4.1 (token/ERC20/utils/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 Address for address; function safeTransfer( IERC20 token, address to, uint256 value ) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom( IERC20 token, address from, address to, uint256 value ) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove( IERC20 token, address spender, uint256 value ) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' require( (value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance( IERC20 token, address spender, uint256 value ) internal { uint256 newAllowance = token.allowance(address(this), spender) + value; _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance( IERC20 token, address spender, uint256 value ) internal { unchecked { uint256 oldAllowance = token.allowance(address(this), spender); require(oldAllowance >= value, "SafeERC20: decreased allowance below zero"); uint256 newAllowance = oldAllowance - value; _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // File: alloyx-smart-contracts-v2/contracts/alloyx/IGoldfinchDelegacy.sol pragma solidity ^0.8.7; /** * @title Goldfinch Delegacy Interface * @notice Middle layer to communicate with goldfinch contracts * @author AlloyX */ interface IGoldfinchDelegacy { /** * @notice GoldFinch PoolToken Value in Value in term of USDC */ function getGoldfinchDelegacyBalanceInUSDC() external view returns (uint256); /** * @notice Claim certain amount of reward token based on alloy silver token, the method will burn the silver token of * the amount of message sender, and transfer reward token to message sender * @param _rewardee the address of rewardee * @param _amount the amount of silver tokens used to claim * @param _totalSupply total claimable and claimed silver tokens of all stakeholders * @param _percentageFee the earning fee for redeeming silver token in percentage in terms of GFI */ function claimReward( address _rewardee, uint256 _amount, uint256 _totalSupply, uint256 _percentageFee ) external; /** * @notice Get gfi amount that should be transfered to the claimer for the amount of CRWN * @param _amount the amount of silver tokens used to claim * @param _totalSupply total claimable and claimed silver tokens of all stakeholders * @param _percentageFee the earning fee for redeeming silver token in percentage in terms of GFI */ function getRewardAmount( uint256 _amount, uint256 _totalSupply, uint256 _percentageFee ) external view returns (uint256); /** * @notice Purchase junior token through this delegacy to get pooltoken inside this delegacy * @param _amount the amount of usdc to purchase by * @param _poolAddress the pool address to buy from * @param _tranche the tranch id */ function purchaseJuniorToken( uint256 _amount, address _poolAddress, uint256 _tranche ) external; /** * @notice Sell junior token through this delegacy to get repayments * @param _tokenId the ID of token to sell * @param _amount the amount to withdraw * @param _poolAddress the pool address to withdraw from * @param _percentageBronzeRepayment the repayment fee for bronze token in percentage */ function sellJuniorToken( uint256 _tokenId, uint256 _amount, address _poolAddress, uint256 _percentageBronzeRepayment ) external; /** * @notice Purchase senior token through this delegacy to get FIDU inside this delegacy * @param _amount the amount of USDC to purchase by */ function purchaseSeniorTokens(uint256 _amount) external; /** * @notice sell senior token through delegacy to redeem fidu * @param _amount the amount of fidu to sell * @param _percentageBronzeRepayment the repayment fee for bronze token in percentage */ function sellSeniorTokens(uint256 _amount, uint256 _percentageBronzeRepayment) external; /** * @notice Validates the Pooltoken to be deposited and get the USDC value of the token * @param _tokenAddress the Pooltoken address * @param _depositor the person to deposit * @param _tokenID the ID of the Pooltoken */ function validatesTokenToDepositAndGetPurchasePrice( address _tokenAddress, address _depositor, uint256 _tokenID ) external returns (uint256); /** * @notice Pay USDC tokens to account * @param _to the address to pay to * @param _amount the amount to pay */ function payUsdc(address _to, uint256 _amount) external; /** * @notice Approve certain amount token of certain address to some other account * @param _account the address to approve * @param _amount the amount to approve * @param _tokenAddress the token address to approve */ function approve( address _tokenAddress, address _account, uint256 _amount ) external; } // File: alloyx-smart-contracts-v2/contracts/alloyx/v4.0/AlloyxVaultV4.0.sol pragma solidity ^0.8.7; /** * @title AlloyX Vault * @notice Initial vault for AlloyX. This vault holds loan tokens generated on Goldfinch * and emits AlloyTokens when a liquidity provider deposits supported stable coins. * @author AlloyX */ contract AlloyxVaultV4_0 is ERC721Holder, Ownable, Pausable { using SafeERC20 for IERC20; using SafeERC20 for AlloyxTokenDURA; using SafeMath for uint256; struct StakeInfo { uint256 amount; uint256 since; } bool private vaultStarted; IERC20 private usdcCoin; AlloyxTokenDURA private alloyxTokenDURA; AlloyxTokenCRWN private alloyxTokenCRWN; IGoldfinchDelegacy private goldfinchDelegacy; address[] internal stakeholders; mapping(address => StakeInfo) private stakesMapping; mapping(address => uint256) private pastRedeemableReward; mapping(address => bool) whitelistedAddresses; uint256 public percentageRewardPerYear = 2; uint256 public percentageDURARedemption = 1; uint256 public percentageDURARepayment = 2; uint256 public percentageCRWNEarning = 10; uint256 public redemptionFee = 0; event DepositStable(address _tokenAddress, address _tokenSender, uint256 _tokenAmount); event DepositNFT(address _tokenAddress, address _tokenSender, uint256 _tokenID); event DepositAlloyx(address _tokenAddress, address _tokenSender, uint256 _tokenAmount); event PurchaseSenior(uint256 amount); event SellSenior(uint256 amount); event PurchaseJunior(uint256 amount); event SellJunior(uint256 amount); event Mint(address _tokenReceiver, uint256 _tokenAmount); event Burn(address _tokenReceiver, uint256 _tokenAmount); event Reward(address _tokenReceiver, uint256 _tokenAmount); event Claim(address _tokenReceiver, uint256 _tokenAmount); event Stake(address _staker, uint256 _amount); event Unstake(address _unstaker, uint256 _amount); constructor( address _alloyxDURAAddress, address _alloyxCRWNAddress, address _usdcCoinAddress, address _goldfinchDelegacy ) { alloyxTokenDURA = AlloyxTokenDURA(_alloyxDURAAddress); alloyxTokenCRWN = AlloyxTokenCRWN(_alloyxCRWNAddress); usdcCoin = IERC20(_usdcCoinAddress); goldfinchDelegacy = IGoldfinchDelegacy(_goldfinchDelegacy); vaultStarted = false; } /** * @notice If vault is started */ modifier whenVaultStarted() { require(vaultStarted, "Vault has not start accepting deposits"); _; } /** * @notice If vault is not started */ modifier whenVaultNotStarted() { require(!vaultStarted, "Vault has already start accepting deposits"); _; } /** * @notice If address is whitelisted * @param _address The address to verify. */ modifier isWhitelisted(address _address) { require(whitelistedAddresses[_address], "You need to be whitelisted"); _; } /** * @notice If address is not whitelisted * @param _address The address to verify. */ modifier notWhitelisted(address _address) { require(!whitelistedAddresses[_address], "You are whitelisted"); _; } /** * @notice Initialize by minting the alloy brown tokens to owner */ function startVaultOperation() external onlyOwner whenVaultNotStarted returns (bool) { uint256 totalBalanceInUSDC = getAlloyxDURATokenBalanceInUSDC(); require(totalBalanceInUSDC > 0, "Vault must have positive value before start"); alloyxTokenDURA.mint( address(this), totalBalanceInUSDC.mul(alloyMantissa()).div(usdcMantissa()) ); vaultStarted = true; return true; } /** * @notice Pause all operations except migration of tokens */ function pause() external onlyOwner whenNotPaused { _pause(); } /** * @notice Unpause all operations */ function unpause() external onlyOwner whenPaused { _unpause(); } /** * @notice Add whitelist address * @param _addressToWhitelist The address to whitelist. */ function addWhitelistedUser(address _addressToWhitelist) public onlyOwner notWhitelisted(_addressToWhitelist) { whitelistedAddresses[_addressToWhitelist] = true; } /** * @notice Remove whitelist address * @param _addressToDeWhitelist The address to de-whitelist. */ function removeWhitelistedUser(address _addressToDeWhitelist) public onlyOwner isWhitelisted(_addressToDeWhitelist) { whitelistedAddresses[_addressToDeWhitelist] = false; } /** * @notice Check whether user is whitelisted * @param _whitelistedAddress The address to whitelist. */ function isUserWhitelisted(address _whitelistedAddress) public view returns (bool) { return whitelistedAddresses[_whitelistedAddress]; } /** * @notice Check if an address is a stakeholder. * @param _address The address to verify. * @return bool, uint256 Whether the address is a stakeholder, * and if so its position in the stakeholders array. */ function isStakeholder(address _address) public view returns (bool, uint256) { for (uint256 s = 0; s < stakeholders.length; s += 1) { if (_address == stakeholders[s]) return (true, s); } return (false, 0); } /** * @notice Add a stakeholder. * @param _stakeholder The stakeholder to add. */ function addStakeholder(address _stakeholder) internal { (bool _isStakeholder, ) = isStakeholder(_stakeholder); if (!_isStakeholder) stakeholders.push(_stakeholder); } /** * @notice Remove a stakeholder. * @param _stakeholder The stakeholder to remove. */ function removeStakeholder(address _stakeholder) internal { (bool _isStakeholder, uint256 s) = isStakeholder(_stakeholder); if (_isStakeholder) { stakeholders[s] = stakeholders[stakeholders.length - 1]; stakeholders.pop(); } } /** * @notice Retrieve the stake for a stakeholder. * @param _stakeholder The stakeholder to retrieve the stake for. * @return Stake The amount staked and the time since when it's staked. */ function stakeOf(address _stakeholder) public view returns (StakeInfo memory) { return stakesMapping[_stakeholder]; } /** * @notice A method for a stakeholder to reset the timestamp of the stake. */ function resetStakeTimestamp() internal { if (stakesMapping[msg.sender].amount == 0) addStakeholder(msg.sender); addPastRedeemableReward(msg.sender, stakesMapping[msg.sender]); stakesMapping[msg.sender] = StakeInfo(stakesMapping[msg.sender].amount, block.timestamp); } /** * @notice Add stake for a staker * @param _staker The person intending to stake * @param _stake The size of the stake to be created. */ function addStake(address _staker, uint256 _stake) internal { if (stakesMapping[_staker].amount == 0) addStakeholder(_staker); addPastRedeemableReward(_staker, stakesMapping[_staker]); stakesMapping[_staker] = StakeInfo(stakesMapping[_staker].amount.add(_stake), block.timestamp); } /** * @notice Remove stake for a staker * @param _staker The person intending to remove stake * @param _stake The size of the stake to be removed. */ function removeStake(address _staker, uint256 _stake) internal { require(stakeOf(_staker).amount >= _stake, "User has insufficient dura coin staked"); if (stakesMapping[_staker].amount == 0) addStakeholder(_staker); addPastRedeemableReward(_staker, stakesMapping[_staker]); stakesMapping[_staker] = StakeInfo(stakesMapping[_staker].amount.sub(_stake), block.timestamp); } /** * @notice Add the stake to past redeemable reward * @param _stake the stake to be added into the reward */ function addPastRedeemableReward(address _staker, StakeInfo storage _stake) internal { uint256 additionalPastRedeemableReward = calculateRewardFromStake(_stake); pastRedeemableReward[_staker] = pastRedeemableReward[_staker].add( additionalPastRedeemableReward ); } /** * @notice Stake more into the vault, which will cause the user's DURA token to transfer to vault * @param _amount the amount the message sender intending to stake in */ function stake(uint256 _amount) external whenNotPaused whenVaultStarted returns (bool) { addStake(msg.sender, _amount); alloyxTokenDURA.safeTransferFrom(msg.sender, address(this), _amount); emit Stake(msg.sender, _amount); return true; } /** * @notice Unstake some from the vault, which will cause the vault to transfer DURA token back to message sender * @param _amount the amount the message sender intending to unstake */ function unstake(uint256 _amount) external whenNotPaused whenVaultStarted returns (bool) { removeStake(msg.sender, _amount); alloyxTokenDURA.safeTransfer(msg.sender, _amount); emit Unstake(msg.sender, _amount); return true; } /** * @notice A method for a stakeholder to clear a stake. */ function clearStake() internal { resetStakeTimestamp(); } /** * @notice A method for a stakeholder to clear a stake with some leftover reward * @param _reward the leftover reward the staker owns */ function resetStakeTimestampWithRewardLeft(uint256 _reward) internal { resetStakeTimestamp(); pastRedeemableReward[msg.sender] = _reward; } function calculateRewardFromStake(StakeInfo memory _stake) internal view returns (uint256) { return _stake .amount .mul(block.timestamp.sub(_stake.since)) .mul(percentageRewardPerYear) .div(100) .div(365 days); } /** * @notice Claimable CRWN token amount of an address * @param _receiver the address of receiver */ function claimableCRWNToken(address _receiver) public view returns (uint256) { StakeInfo memory stakeValue = stakeOf(_receiver); return pastRedeemableReward[_receiver] + calculateRewardFromStake(stakeValue); } /** * @notice Total claimable CRWN tokens of all stakeholders */ function totalClaimableCRWNToken() public view returns (uint256) { uint256 total = 0; for (uint256 i = 0; i < stakeholders.length; i++) { total = total.add(claimableCRWNToken(stakeholders[i])); } return total; } /** * @notice Total claimable and claimed CRWN tokens of all stakeholders */ function totalClaimableAndClaimedCRWNToken() public view returns (uint256) { return totalClaimableCRWNToken().add(alloyxTokenCRWN.totalSupply()); } /** * @notice Claim all alloy CRWN tokens of the message sender, the method will mint the CRWN token of the claimable * amount to message sender, and clear the past rewards to zero */ function claimAllAlloyxCRWN() external whenNotPaused whenVaultStarted returns (bool) { uint256 reward = claimableCRWNToken(msg.sender); alloyxTokenCRWN.mint(msg.sender, reward); resetStakeTimestampWithRewardLeft(0); emit Claim(msg.sender, reward); return true; } /** * @notice Claim certain amount of alloy CRWN tokens of the message sender, the method will mint the CRWN token of * the claimable amount to message sender, and clear the past rewards to the remainder * @param _amount the amount to claim */ function claimAlloyxCRWN(uint256 _amount) external whenNotPaused whenVaultStarted returns (bool) { uint256 allReward = claimableCRWNToken(msg.sender); require(allReward >= _amount, "User has claimed more than he's entitled"); alloyxTokenCRWN.mint(msg.sender, _amount); resetStakeTimestampWithRewardLeft(allReward.sub(_amount)); emit Claim(msg.sender, _amount); return true; } /** * @notice Claim certain amount of reward token based on alloy CRWN token, the method will burn the CRWN token of * the amount of message sender, and transfer reward token to message sender * @param _amount the amount to claim */ function claimReward(uint256 _amount) external whenNotPaused whenVaultStarted returns (bool) { require( alloyxTokenCRWN.balanceOf(address(msg.sender)) >= _amount, "Balance of crown coin must be larger than the amount to claim" ); goldfinchDelegacy.claimReward( msg.sender, _amount, totalClaimableAndClaimedCRWNToken(), percentageCRWNEarning ); alloyxTokenCRWN.burn(msg.sender, _amount); emit Reward(msg.sender, _amount); return true; } /** * @notice Get reward token count if the amount of CRWN tokens are claimed * @param _amount the amount to claim */ function getRewardTokenCount(uint256 _amount) external view returns (uint256) { return goldfinchDelegacy.getRewardAmount( _amount, totalClaimableAndClaimedCRWNToken(), percentageCRWNEarning ); } /** * @notice Request the delegacy to approve certain tokens on certain account for certain amount, it is most used for * buying the goldfinch tokens, they need to be able to transfer usdc to them * @param _tokenAddress the leftover reward the staker owns * @param _account the account the delegacy going to approve * @param _amount the amount the delegacy going to approve */ function approveDelegacy( address _tokenAddress, address _account, uint256 _amount ) external onlyOwner { goldfinchDelegacy.approve(_tokenAddress, _account, _amount); } /** * @notice Alloy DURA Token Value in terms of USDC */ function getAlloyxDURATokenBalanceInUSDC() public view returns (uint256) { uint256 totalValue = getUSDCBalance().add( goldfinchDelegacy.getGoldfinchDelegacyBalanceInUSDC() ); require( totalValue > redemptionFee, "the value of vault is not larger than redemption fee, something went wrong" ); return getUSDCBalance().add(goldfinchDelegacy.getGoldfinchDelegacyBalanceInUSDC()).sub( redemptionFee ); } /** * @notice USDC Value in Vault */ function getUSDCBalance() internal view returns (uint256) { return usdcCoin.balanceOf(address(this)); } /** * @notice Convert Alloyx DURA to USDC amount * @param _amount the amount of DURA token to convert to usdc */ function alloyxDURAToUSDC(uint256 _amount) public view returns (uint256) { uint256 alloyDURATotalSupply = alloyxTokenDURA.totalSupply(); uint256 totalVaultAlloyxDURAValueInUSDC = getAlloyxDURATokenBalanceInUSDC(); return _amount.mul(totalVaultAlloyxDURAValueInUSDC).div(alloyDURATotalSupply); } /** * @notice Convert USDC Amount to Alloyx DURA * @param _amount the amount of usdc to convert to DURA token */ function usdcToAlloyxDURA(uint256 _amount) public view returns (uint256) { uint256 alloyDURATotalSupply = alloyxTokenDURA.totalSupply(); uint256 totalVaultAlloyxDURAValueInUSDC = getAlloyxDURATokenBalanceInUSDC(); return _amount.mul(alloyDURATotalSupply).div(totalVaultAlloyxDURAValueInUSDC); } /** * @notice Set percentageRewardPerYear which is the reward per year in percentage * @param _percentageRewardPerYear the reward per year in percentage */ function setPercentageRewardPerYear(uint256 _percentageRewardPerYear) external onlyOwner { percentageRewardPerYear = _percentageRewardPerYear; } /** * @notice Set percentageDURARedemption which is the redemption fee for DURA token in percentage * @param _percentageDURARedemption the redemption fee for DURA token in percentage */ function setPercentageDURARedemption(uint256 _percentageDURARedemption) external onlyOwner { percentageDURARedemption = _percentageDURARedemption; } /** * @notice Set percentageDURARepayment which is the repayment fee for DURA token in percentage * @param _percentageDURARepayment the repayment fee for DURA token in percentage */ function setPercentageDURARepayment(uint256 _percentageDURARepayment) external onlyOwner { percentageDURARepayment = _percentageDURARepayment; } /** * @notice Set percentageCRWNEarning which is the earning fee for redeeming CRWN token in percentage in terms of gfi * @param _percentageCRWNEarning the earning fee for redeeming CRWN token in percentage in terms of gfi */ function setPercentageCRWNEarning(uint256 _percentageCRWNEarning) external onlyOwner { percentageCRWNEarning = _percentageCRWNEarning; } /** * @notice Alloy token with 18 decimals */ function alloyMantissa() internal pure returns (uint256) { return uint256(10)**uint256(18); } /** * @notice USDC mantissa with 6 decimals */ function usdcMantissa() internal pure returns (uint256) { return uint256(10)**uint256(6); } /** * @notice Change DURA token address * @param _alloyxAddress the address to change to */ function changeAlloyxDURAAddress(address _alloyxAddress) external onlyOwner { alloyxTokenDURA = AlloyxTokenDURA(_alloyxAddress); } function changeGoldfinchDelegacyAddress(address _goldfinchDelegacy) external onlyOwner { goldfinchDelegacy = IGoldfinchDelegacy(_goldfinchDelegacy); } /** * @notice An Alloy token holder can deposit their tokens and redeem them for USDC * @param _tokenAmount Number of Alloy Tokens */ function depositAlloyxDURATokens(uint256 _tokenAmount) external whenNotPaused whenVaultStarted isWhitelisted(msg.sender) returns (bool) { require( alloyxTokenDURA.balanceOf(msg.sender) >= _tokenAmount, "User has insufficient alloyx coin." ); require( alloyxTokenDURA.allowance(msg.sender, address(this)) >= _tokenAmount, "User has not approved the vault for sufficient alloyx coin" ); uint256 amountToWithdraw = alloyxDURAToUSDC(_tokenAmount); uint256 withdrawalFee = amountToWithdraw.mul(percentageDURARedemption).div(100); require(amountToWithdraw > 0, "The amount of stable coin to get is not larger than 0"); require( usdcCoin.balanceOf(address(this)) >= amountToWithdraw, "The vault does not have sufficient stable coin" ); alloyxTokenDURA.burn(msg.sender, _tokenAmount); usdcCoin.safeTransfer(msg.sender, amountToWithdraw.sub(withdrawalFee)); redemptionFee = redemptionFee.add(withdrawalFee); emit DepositAlloyx(address(alloyxTokenDURA), msg.sender, _tokenAmount); emit Burn(msg.sender, _tokenAmount); return true; } /** * @notice A Liquidity Provider can deposit supported stable coins for Alloy Tokens * @param _tokenAmount Number of stable coin */ function depositUSDCCoin(uint256 _tokenAmount) external whenNotPaused whenVaultStarted isWhitelisted(msg.sender) returns (bool) { require(usdcCoin.balanceOf(msg.sender) >= _tokenAmount, "User has insufficient stable coin"); require( usdcCoin.allowance(msg.sender, address(this)) >= _tokenAmount, "User has not approved the vault for sufficient stable coin" ); uint256 amountToMint = usdcToAlloyxDURA(_tokenAmount); require(amountToMint > 0, "The amount of alloyx DURA coin to get is not larger than 0"); usdcCoin.safeTransferFrom(msg.sender, address(goldfinchDelegacy), _tokenAmount); alloyxTokenDURA.mint(msg.sender, amountToMint); emit DepositStable(address(usdcCoin), msg.sender, amountToMint); emit Mint(msg.sender, amountToMint); return true; } /** * @notice A Liquidity Provider can deposit supported stable coins for Alloy Tokens * @param _tokenAmount Number of stable coin */ function depositUSDCCoinWithStake(uint256 _tokenAmount) external whenNotPaused whenVaultStarted isWhitelisted(msg.sender) returns (bool) { require(usdcCoin.balanceOf(msg.sender) >= _tokenAmount, "User has insufficient stable coin"); require( usdcCoin.allowance(msg.sender, address(this)) >= _tokenAmount, "User has not approved the vault for sufficient stable coin" ); uint256 amountToMint = usdcToAlloyxDURA(_tokenAmount); require(amountToMint > 0, "The amount of alloyx DURA coin to get is not larger than 0"); usdcCoin.safeTransferFrom(msg.sender, address(this), _tokenAmount); alloyxTokenDURA.mint(address(this), amountToMint); addStake(msg.sender, amountToMint); emit DepositStable(address(usdcCoin), msg.sender, amountToMint); emit Mint(address(this), amountToMint); return true; } /** * @notice A Junior token holder can deposit their NFT for stable coin * @param _tokenAddress NFT Address * @param _tokenID NFT ID */ function depositNFTToken(address _tokenAddress, uint256 _tokenID) external whenNotPaused whenVaultStarted isWhitelisted(msg.sender) returns (bool) { uint256 purchasePrice = goldfinchDelegacy.validatesTokenToDepositAndGetPurchasePrice( _tokenAddress, msg.sender, _tokenID ); IERC721(_tokenAddress).safeTransferFrom(msg.sender, address(goldfinchDelegacy), _tokenID); goldfinchDelegacy.payUsdc(msg.sender, purchasePrice); emit DepositNFT(_tokenAddress, msg.sender, _tokenID); return true; } /** * @notice Purchase junior token through delegacy to get pooltoken inside the delegacy * @param _amount the amount of usdc to purchase by * @param _poolAddress the pool address to buy from * @param _tranche the tranch id */ function purchaseJuniorToken( uint256 _amount, address _poolAddress, uint256 _tranche ) external onlyOwner { require(_amount > 0, "Must deposit more than zero"); goldfinchDelegacy.purchaseJuniorToken(_amount, _poolAddress, _tranche); emit PurchaseJunior(_amount); } /** * @notice Sell junior token through delegacy to get repayments * @param _tokenId the ID of token to sell * @param _amount the amount to withdraw * @param _poolAddress the pool address to withdraw from */ function sellJuniorToken( uint256 _tokenId, uint256 _amount, address _poolAddress ) external onlyOwner { require(_amount > 0, "Must sell more than zero"); goldfinchDelegacy.sellJuniorToken(_tokenId, _amount, _poolAddress, percentageDURARepayment); emit SellSenior(_amount); } /** * @notice Purchase senior token through delegacy to get fidu inside the delegacy * @param _amount the amount of usdc to purchase by */ function purchaseSeniorTokens(uint256 _amount) external onlyOwner { require(_amount > 0, "Must deposit more than zero"); goldfinchDelegacy.purchaseSeniorTokens(_amount); emit PurchaseSenior(_amount); } /** * @notice Sell senior token through delegacy to redeem fidu * @param _amount the amount of fidu to sell */ function sellSeniorTokens(uint256 _amount) external onlyOwner { require(_amount > 0, "Must sell more than zero"); goldfinchDelegacy.sellSeniorTokens(_amount, percentageDURARepayment); emit SellSenior(_amount); } /** * @notice Destroy the contract */ function destroy() external onlyOwner whenPaused { require(usdcCoin.balanceOf(address(this)) == 0, "Balance of stable coin must be 0"); address payable addr = payable(address(owner())); selfdestruct(addr); } /** * @notice Migrate certain ERC20 to an address * @param _tokenAddress the token address to migrate * @param _to the address to transfer tokens to */ function migrateERC20(address _tokenAddress, address _to) external onlyOwner whenPaused { uint256 balance = IERC20(_tokenAddress).balanceOf(address(this)); IERC20(_tokenAddress).safeTransfer(_to, balance); } /** * @notice Transfer redemption fee to some other address * @param _to the address to transfer to */ function transferRedemptionFee(address _to) external onlyOwner whenNotPaused { usdcCoin.safeTransfer(_to, redemptionFee); redemptionFee = 0; } /** * @notice Transfer the ownership of alloy CRWN and DURA token contract to some other address * @param _to the address to transfer ownership to */ function transferAlloyxOwnership(address _to) external onlyOwner whenPaused { alloyxTokenDURA.transferOwnership(_to); alloyxTokenCRWN.transferOwnership(_to); } }
Claim certain amount of alloy CRWN tokens of the message sender, the method will mint the CRWN token of the claimable amount to message sender, and clear the past rewards to the remainder _amount the amount to claim/
function claimAlloyxCRWN(uint256 _amount) external whenNotPaused whenVaultStarted returns (bool) { uint256 allReward = claimableCRWNToken(msg.sender); require(allReward >= _amount, "User has claimed more than he's entitled"); alloyxTokenCRWN.mint(msg.sender, _amount); resetStakeTimestampWithRewardLeft(allReward.sub(_amount)); emit Claim(msg.sender, _amount); return true; }
10,762,067
./full_match/1/0x26Ee982dEE36Df3FA0D0db37798F8d0bD4c305Ed/sources/contracts/RatKingSociety.sol
Function required to override by DefaultOperatorFilterer/
function safeTransferFrom(address from, address to, uint256 tokenId, bytes memory data) public override(ERC721, IERC721) onlyAllowedOperator(from) { super.safeTransferFrom(from, to, tokenId, data); }
4,929,611
pragma solidity ^0.5.3; /// @title DaiDaddy: secondary market to let people sell CDP's with outstanding debt /// @author Chris Maree import "./SaiTubInterface.sol"; import "./MedianizerInterface.sol"; contract DebtMarket { enum Status {LISTED, BOUGHT, CANCLED} struct Debt { bytes32 cupId; address payable seller; address buyer; uint256 discount; //percentage discount (no decimal) Status status; } struct Cup { address lad; // CDP owner uint256 ink; // Locked collateral (in SKR) uint256 art; // Outstanding normalised debt (tax only) uint256 ire; // Outstanding normalised debt } // debt mappings and orders Debt[] public debtBook; mapping(bytes32 => uint256) cupsToDebt; uint256 public debtItems; mapping(address => uint256[]) addressToDebtSellers; // contract instances SaiTub public saiTubContract; Medianizer public medianizerContract; constructor(address _saiTubAddress, address _medianizerAddress) public { saiTubContract = SaiTub(_saiTubAddress); medianizerContract = Medianizer(_medianizerAddress); } function sellCDP(bytes32 _cupId, uint256 _discount) public { //transfer the CDP to the DaiDaddy Contract saiTubContract.give(_cupId, address(this)); // add the sale to the order book. uint256 index = debtBook.push( Debt(_cupId, msg.sender, address(0), _discount, Status.LISTED) ) - 1; cupsToDebt[_cupId] = index; addressToDebtSellers[msg.sender].push(index); } function buyCDP(uint256 _debtId) public payable returns (uint256) { //ensure write value is sent with tx require( msg.value == debtPositionPriceInEth(_debtId), "Wrong value sent with tx" ); bytes32 _cupId = debtBook[_debtId].cupId; //transfer the CDP to the new owner saiTubContract.give(_cupId, msg.sender); //transfer ether to seller debtBook[_debtId].seller.transfer(msg.value); //update debt book debtBook[_debtId].buyer = msg.sender; debtBook[_debtId].status = Status.BOUGHT; } function cancelCDPSale(uint256 _debtId) public { require( debtBook[_debtId].seller == msg.sender, "Not your CDP sale to cancel" ); require( debtBook[_debtId].status == Status.LISTED, "Wrong sell order status" ); bytes32 _cupId = debtBook[_debtId].cupId; // transfer sell order and change status saiTubContract.give(_cupId, msg.sender); debtBook[_debtId].status = Status.CANCLED; } function debtPositionPriceInEth(uint256 _debtId) public view returns (uint256) { Cup memory cup; (cup.lad, cup.ink, cup.art, cup.ire) = saiTubContract.cups( debtBook[_debtId].cupId ); uint256 cdpValueUSD = debtPrice( cup.art, cup.ire, debtBook[_debtId].discount ); return (cdpValueUSD * 10**18) / getEtherPrice(); } function debtPrice(uint256 _art, uint256 _ire, uint256 _discount) public pure returns (uint256) { return (_art * (_ire / 10 - 10**18) * (100 - _discount)) / 10**20; } function saiTubAddress() public view returns (address) { return address(saiTubContract); } function getEtherPrice() public view returns (uint256) { return uint256(medianizerContract.read()); } function getDebtSalesForAddress(address _address) public view returns (uint256[] memory) { return addressToDebtSellers[_address]; } }
transfer sell order and change status
function cancelCDPSale(uint256 _debtId) public { require( debtBook[_debtId].seller == msg.sender, "Not your CDP sale to cancel" ); require( debtBook[_debtId].status == Status.LISTED, "Wrong sell order status" ); bytes32 _cupId = debtBook[_debtId].cupId; saiTubContract.give(_cupId, msg.sender); debtBook[_debtId].status = Status.CANCLED; }
12,985,732
pragma solidity ^0.4.21; /** * @title Description: This code is for creating a token contract * This contract is mintable, pausable, burnable, administered, admin-transferrable and * has safety Maths and security operations checks done and yet have been kept short and simple * It has got 3 contracts * 1. Manager Contract - This contract gives a user the power to manage the token functions * 2. ERC20 Standard Contract - It implements ERC20 pre requisites * 3. WIMT Token Contract - It is a custom contract that inherits from the above two contracts * This source code was tested with Remix and solidity compiler version 0.4.21 * The source code was adapted and modified by wims.io * source : https://github.com/tintinweb/smart-contract-sanctuary/blob/master/contracts/ropsten/46/46b8357a9a9361258358308d3668e2072d6732a9_AxelToken.sol */ /** * @notice Manager contract */ contract Manager { address public contractManager; //address to manage the token contract bool public paused = false; // Indicates whether the token contract is paused or not. event NewContractManager(address newManagerAddress); //Will display change of token manager /** * @notice Function constructor for contract Manager with no parameters * */ function Manager() public { contractManager = msg.sender; //address that creates contracts will manage it } /** * @notice onlyManager restrict management operations to the Manager of contract */ modifier onlyManager() { require(msg.sender == contractManager); _; } /** * @notice Manager set a new manager */ function newManager(address newManagerAddress) public onlyManager { require(newManagerAddress != 0); contractManager = newManagerAddress; emit NewContractManager(newManagerAddress); } /** * @dev Event fired when the token contracts gets paused. */ event Pause(); /** * @notice Event fired when the token contracts gets unpaused. */ event Unpause(); /** * @notice Allows a function to be called only when the token contract is not paused. */ modifier whenNotPaused() { require(!paused); _; } /** * @dev Pauses the token contract. */ function pause() public onlyManager whenNotPaused { paused = true; emit Pause(); } /** * @notice Unpauses the token contract. */ function unpause() public onlyManager { require(paused); paused = false; emit Unpause(); } } /** *@notice ERC20 This is the traditional ERC20 contract */ contract ERC20 is Manager { mapping(address => uint256) public balanceOf; //this variable displays users balances string public name;//this variable displays token contract name string public symbol;//this variable displays token contract ticker symbol uint256 public decimal; //this variable displays the number of decimals for the token uint256 public totalSupply;//this variable displays the total supply of tokens mapping(address => mapping(address => uint256)) public allowance;//this will list of addresses a user will allow to Transfer his/her tokens event Transfer(address indexed from, address indexed to, uint256 value); //this event will notifies Transfers event Approval(address indexed owner, address indexed spender, uint256 value);//this event will notifies Approval /** * @notice Function constructor for ERC20 contract */ function ERC20(uint256 initialSupply, string _name, string _symbol, uint256 _decimal) public { require(initialSupply >= 0);//prevent negative numbers require(_decimal >= 0);//no negative decimals allowed balanceOf[msg.sender] = initialSupply;//give the contract creator address the total created tokens name = _name; //When the contract is being created give it a name symbol = _symbol;//When the contract is being created give it a symbol decimal = _decimal;//When the contract is being created give it decimals standard is 18 totalSupply = initialSupply; //When the contract is being created set the token total supply } /** * @notice function transfer which will move tokens from user account to an address specified at to parameter * */ function transfer(address _to, uint256 _value)public whenNotPaused returns (bool success) { require(_value > 0);//prevent transferring nothing require(balanceOf[msg.sender] >= _value);//the token sender must have tokens to transfer require(balanceOf[_to] + _value >= balanceOf[_to]);//the token receiver balance must change and be bigger balanceOf[msg.sender] -= _value;//the balance of the token sender must decrease accordingly balanceOf[_to] += _value;//effect the actual transfer of tokens emit Transfer(msg.sender, _to, _value);//publish addresses and amount Transferred return true; } /** * @notice function approve gives an address power to spend specified amount * */ function approve(address _spender, uint256 _value) public whenNotPaused returns (bool success) { require(_value > 0); //approved amount must be greater than zero allowance[msg.sender][_spender] = _value;//_spender will be approved to spend _value from as user's address that called this function emit Approval(msg.sender, _spender, _value);//broadcast the activity return true; } /** * @notice function allowance : displays address allow to transfer tokens from owner * */ function allowance(address _owner, address _spender) public view returns (uint256 remaining) { return allowance[_owner][_spender]; } /** * @notice function transferFrom : moves tokens from one address to another * */ function transferFrom(address _from, address _to, uint256 _value)public whenNotPaused returns (bool success) { require(_value > 0); //move at least 1 token require(balanceOf[_from] >= _value);//check that there tokens to move require(balanceOf[_to] + _value >= balanceOf[_to]);//after the move the new value must be greater require(_value <= allowance[_from][msg.sender]); //only authorized addresses can transferFrom balanceOf[_from] -= _value;//remove tokens from _from address balanceOf[_to] += _value;//add these tokens to _to address allowance[_from][msg.sender] -= _value; //change the base token balance emit Transfer(_from, _to, _value);//publish transferFrom activity to network return true; } /** * @notice function balanceOf will display balance of given address * */ function balanceOf(address _owner)public constant returns (uint256 balance) { return balanceOf[_owner]; } } /** *@notice WIMT Token implements Manager and ERC contracts */ contract WIMT is Manager, ERC20 { /** * @notice function constructor for the WIMT contract */ function WIMT(uint256 _totalSupply, string _name, string _symbol, uint8 _decimal ) public ERC20(_totalSupply, _name, _symbol, _decimal) { contractManager = msg.sender; balanceOf[contractManager] = _totalSupply; totalSupply = _totalSupply; decimal = _decimal; } /** * @notice function mint to be executed by Manager of token * */ function mint(address target, uint256 mintedAmount)public onlyManager whenNotPaused { require(target != 0);//check executor is supplied require(mintedAmount > 0);//disallow negative minting require(balanceOf[target] + mintedAmount >= balanceOf[target]);//after the move the new value must be greater require(totalSupply + mintedAmount >= totalSupply);//after the move the new value must be greater balanceOf[target] += mintedAmount;//add tokens to address target totalSupply += mintedAmount;//increase totalSupply emit Transfer(0, this, mintedAmount);//publish transfer emit Transfer(this, target, mintedAmount);//publish transfer } /** * @notice function burn decrease total Supply of tokens * */ function burn(uint256 mintedAmount) public onlyManager whenNotPaused { require(mintedAmount > 0);//at least 1 token must be destroyed require(totalSupply - mintedAmount <= totalSupply);//after the move the new value must be greater require(balanceOf[msg.sender] - mintedAmount <= balanceOf[msg.sender]);//after the move the new value must be greater balanceOf[msg.sender] -= mintedAmount;//decrease balance of destroyer totalSupply -= mintedAmount;//decrease totalSupply by destroyed tokens emit Transfer(0, msg.sender, mintedAmount);//publish burn activity } }
function approve gives an address power to spend specified amount/
function approve(address _spender, uint256 _value) public whenNotPaused returns (bool success) { return true; }
6,452,581
./full_match/1/0x57852e8e787ff5af7c0E1d0b156ec491eC78Ec92/sources/ShibAnon.sol
uint256 DeveloperShare = _buyDeveloperFee.add(_sellDeveloperFee);
function swapAndLiquify(uint256 tAmount) private lockTheSwap { uint256 totalShares = _totalTaxIfBuying.add(_totalTaxIfSelling); uint256 liquidityShare = _buyLiquidityFee.add(_sellLiquidityFee); uint256 MarketingShare = _buyMarketingFee.add(_sellMarketingFee); uint256 tokenForLp = tAmount.mul(liquidityShare).div(totalShares).div(2); uint256 tokenForSwap = tAmount.sub(tokenForLp); uint256 initialBalance = address(this).balance; swapTokensForEth(tokenForSwap); uint256 recievedBalance = address(this).balance.sub(initialBalance); uint256 totalETHFee = totalShares.sub(liquidityShare.div(2)); uint256 amountETHLiquidity = recievedBalance.mul(liquidityShare).div(totalETHFee).div(2); uint256 amountETHMarketing = recievedBalance.mul(MarketingShare).div(totalETHFee); uint256 amountETHDeveloper = recievedBalance.sub(amountETHLiquidity).sub(amountETHMarketing); if(amountETHMarketing > 0) { payable(marketingWallet).transfer(amountETHMarketing); } if(amountETHDeveloper > 0) { payable(DeveloperWallet).transfer(amountETHDeveloper); } if(amountETHLiquidity > 0 && tokenForLp > 0) { addLiquidity(tokenForLp, amountETHLiquidity); } }
3,029,980
./full_match/137/0xCF77e2E32EDDc54d29cF8BF106024b1012bFbcCC/sources/home/hellwolf/Projects/superfluid/protocol-monorepo/packages/ethereum-contracts/contracts/utils/CallUtils.sol
It the data encoded correctly with abi.encode(bytesData) Expected ABI Encode Layout: | word 1 | word 2 | word 3 | the rest... | data length | bytesData offset | bytesData length | bytesData + padLength32 zeros |/ bytes offset is always expected to be 32 the data length should be bytesData.length + 64 + padded bytes length
function isValidAbiEncodedBytes(bytes memory data) internal pure returns (bool) { if (data.length < 64) return false; uint bytesOffset; uint bytesLen; if (bytesOffset != 32) return false; return data.length == 64 + padLength32(bytesLen); }
4,754,775
pragma solidity 0.4.24; import "zeppelin-solidity/contracts/math/SafeMath.sol"; import "zeppelin-solidity/contracts/ownership/Ownable.sol"; import "zeppelin-solidity/contracts/token/ERC20/ERC20.sol"; import 'zeppelin-solidity/contracts/lifecycle/Destructible.sol'; import "./SwapController.sol"; contract SwapContract is Ownable, Destructible { using SafeMath for uint256; address public tokenOwner; address public tokenAddress; address public controllerTokenAddress; bool public reset = true; struct TransferRequest { address toAddress; address txAddress; uint256 amount; bool completed; uint index; } uint256 private constant decimalFactor = 10**uint256(18); uint _numRequests; mapping (uint => TransferRequest) _requests; event RequestToTransfer(uint numRequests, uint requestId, address investor, uint256 amount); event TransferExecuted(uint idx, address indexed investor, uint256 amount); /** * @dev only the token owner and owner of the contract * can execute with this modifier */ modifier onlyTokenOwner() { require( msg.sender == tokenOwner || msg.sender == owner ); _; } /** * @dev constructor * @param _tokenAddress address of the swap controller contract * @param _tokenOwner address of the owner of the token */ constructor( address _tokenAddress, address _controllerTokenAddress, address _tokenOwner ) Ownable() public { require(_tokenAddress != address(0)); require(_controllerTokenAddress != address(0)); require(_tokenOwner != address(0)); tokenAddress = _tokenAddress; controllerTokenAddress = _controllerTokenAddress; tokenOwner = _tokenOwner; } /** * @dev main function for creating transfer requests in bulk * @param _toAddresses address[] destination to send SHOPIN tokens * @param _txAddresses address[] addresses of SHOP transactions * @param _amounts uint[] amount of tokens requested in swap * @return bool success boolean */ function requestTransfers( address[] _toAddresses, address[] _txAddresses, uint[] _amounts ) public returns (bool) { // Both arrays must be same length require(_toAddresses.length == _txAddresses.length); require(_txAddresses.length == _amounts.length); // Perform each request for (uint256 i=0; i < _amounts.length; i++) { requestTransfer(_toAddresses[i], _txAddresses[i], _amounts[i]); } return true; } /** * @dev main function for creating transfer requests * @param _toAddress address destination to send SHOPIN tokens * @param _txAddress address address of SHOP transaction * @param _amount uint amount of tokens requested in swap * @return bool success boolean */ function requestTransfer( address _toAddress, address _txAddress, uint _amount ) public returns (bool) { // request cannot already exist for this transaction require(!requestTransferExists(_txAddress)); // cannot request transfer of 0 SHOP tokens require(_amount > 0); // ensure no zero address require(_txAddress != address(0)); uint _requestId = _numRequests++; TransferRequest memory req = TransferRequest( _toAddress, _txAddress, _amount, false, _requestId ); _requests[_requestId] = req; // emit emit RequestToTransfer(_numRequests, _requestId, _txAddress, _amount); return true; } /** * @dev is address in list of transfer requests? * @param _txAddress addr address we're checking * @return bool if the address has already submitted a transfer request */ function requestTransferExists(address _txAddress) public view returns (bool) { if (_numRequests == 0) { return false; } for (uint i=0; i<_numRequests; i++) { TransferRequest memory req = _requests[i]; if (req.txAddress == _txAddress) { return true; } } return false; } /** * @dev can the transfer request get swapped? * @param req TransferRequest we're checking on * @return bool if the transfer request can be executed */ function canSwap(TransferRequest req) internal view returns (bool) { SwapController controller = SwapController(controllerTokenAddress); return controller.canSwap(req.toAddress); } /** * @dev execute transfers for all unexecuted ones that can be swapped * @return boolean if the entire operation completed successfully or not */ function executeTransfers() onlyTokenOwner public returns (bool) { if (_numRequests == 0) return false; uint numRequests = _numRequests; ERC20 token = ERC20(tokenAddress); for (uint i = 0; i < numRequests; i++) { TransferRequest storage req = _requests[i]; if (!req.completed && canSwap(req)) { // Execute transfer token.transfer(req.toAddress, req.amount); emit TransferExecuted(i, req.toAddress, req.amount); _requests[i].completed = true; } } return true; } function withdrawAllTokens() onlyTokenOwner external returns (bool) { ERC20 token = ERC20(tokenAddress); uint256 balance = token.balanceOf(this); token.transfer(owner, balance); } function withdrawAllEth() onlyTokenOwner public returns (bool) { tokenOwner.transfer(address(this).balance); } /** * @dev get the token owner address * @return address of the token owner */ function getTokenOwnerAddress() public view returns (address) { return tokenOwner; } /** * @dev get controller token address * @return address of the original token address */ function getControllerTokenAddress() public view returns (address) { return controllerTokenAddress; } function getTokenAddress() public view returns (address) { return tokenAddress; } /** * @dev get transfer request amount for a transfer request * @param idx index of the transfer request in the list * @return uint the amount requested in the transfer */ function getTransferRequestAmount( uint idx ) onlyTokenOwner public view returns (uint256) { return _requests[idx].amount; } /** * @dev get the transfer request investor address * @param idx the index of the transfer request in the list * @return address the address of the investor */ function getTransferRequestInvestor( uint idx ) onlyTokenOwner public view returns (address) { return _requests[idx].toAddress; } /** * @dev get the completed status of the transfer request * @param idx the index of the transfer request * @return bool the status of the completed transfer request */ function getTransferRequestCompleted( uint idx ) onlyTokenOwner public view returns (bool) { return _requests[idx].completed; } /** * @dev get the txaddress * @param idx the index of the transfer request * @return tx address */ function getTransferRequestTxHash( uint idx ) onlyTokenOwner public view returns (address) { return _requests[idx].txAddress; } /** * @dev get the number of all transfer requests * @return uint the amount of transfer requests */ function getTransferRequestCount() onlyTokenOwner public view returns (uint) { return _numRequests; } }
get the completed status of the transfer request idx the index of the transfer request return bool the status of the completed transfer request/
function getTransferRequestCompleted( uint idx ) onlyTokenOwner public view returns (bool) { return _requests[idx].completed; }
14,070,651
// SPDX-License-Identifier: Apache-2.0 pragma solidity >=0.6.4 <0.8.0; pragma experimental ABIEncoderV2; //import "https://github.com/vigilance91/solidarity/ERC/introspection/ERC165/eventsERC165.sol"; /// /// @title Mixin for the ERC-165 Interface Library /// @author Tyler R. Drury <[email protected]> (www.twitter.com/StudiosVigil) - copyright 24/3/2021, All Rights Reserved /// library mixinERC165 { //using LogicConstraints for bool; //using eventsERC165 for bytes4; bytes32 internal constant STORAGE_SLOT = keccak256("ERC-165.mixin.storage"); //string internal constant _LIB_NAME = ' mixinERC165: '; struct ERC165Storage { mapping(bytes4=>bool) supportedInterfaces; } /// ///getters /// function storageERC165( )internal pure returns( ERC165Storage storage ret ){ bytes32 position = STORAGE_SLOT; assembly { ret_slot := position } } function supportedInterfaces( )internal view returns( mapping(bytes4=>bool) storage ){ return storageERC165().supportedInterfaces; } function supportsInterface( bytes4 interfaceId )internal view returns( bool ){ return supportedInterfaces()[interfaceId]; //return storageERC165().supportedInterfaces[interfaceId]; } /// ///setters /// function setSupportsInterface( bytes4 interfaceId, bool supported )internal { require( interfaceId != 0xffffffff, //&& interfaceId != 0x00000000 "invalid interface id" ); storageERC165().supportedInterfaces[interfaceId] = supported; //interfaceId.emitInterfaceSupported(supported); //return supportedInterfaces()[interfaceId]; } }
return storageERC165().supportedInterfaces[interfaceId];
function supportsInterface( bytes4 interfaceId )internal view returns( bool ){ return supportedInterfaces()[interfaceId]; }
1,804,906
./full_match/11155111/0xbE3d97A00b4bE98A626a5c6DEc64f74F5F28da1f/sources/contracts/honeycast.sol
See {IERC721-getApproved}./
function getApproved(uint256 tokenId) public view virtual override returns (address) { _requireMinted(tokenId); return _tokenApprovals[tokenId]; }
3,815,513
./partial_match/1/0x968348C6135C25e7160AD0671C8C9CA2eD2bb982/sources/contracts/eclp/GyroECLPMath.sol
calculate At \cdot A chi, ignores rounding direction. We will later compensate for the rounding error. to save gas, pre-compute dSq^2 as it will be used 3 times (cx - sy) (w/lambda + z) / lambda account for 2 factors of dSq (4 s,c factors) (x lambda s + y lambda c) u, note u > 0 (sx+cy) v, note v > 0
function calcAtAChi( int256 x, int256 y, Params memory p, DerivedParams memory d ) internal pure returns (int256 val) { int256 dSq2 = d.dSq.mulXpU(d.dSq); int256 termXp = (d.w.divDownMagU(p.lambda) + d.z).divDownMagU(p.lambda).divXpU(dSq2); val = (x.mulDownMagU(p.c) - y.mulDownMagU(p.s)).mulDownXpToNpU(termXp); int256 termNp = x.mulDownMagU(p.lambda).mulDownMagU(p.s) + y.mulDownMagU(p.lambda).mulDownMagU(p.c); val = val + termNp.mulDownXpToNpU(d.u.divXpU(dSq2)); termNp = x.mulDownMagU(p.s) + y.mulDownMagU(p.c); val = val + termNp.mulDownXpToNpU(d.v.divXpU(dSq2)); }
15,967,265
pragma solidity ^0.5.0; import "./SupplyChain.sol"; /** @title Mortal. Here I have inhereted the modifiers ***from the SupplyChain contract */ contract Mortal is SupplyChain { /**@dev enables the creator of the contract to desctroy it */ function destroy() public isOwner { selfdestruct(owner); } /**@dev sends the remaining ether stored within the contract ***to a designated target address */ function destroyAndSend(address payable recipient) public isOwner { selfdestruct(recipient); } }
enables the creator of the contract to desctroy it /
function destroy() public isOwner { selfdestruct(owner); }
6,382,665
./partial_match/1/0xa22cf004eD5105608b39c48bE688BD9B9026a046/sources/FeePool.sol
Claim fees for last period when available or not already withdrawn. currencyKey Synth currency you wish to receive the fees in./
function claimFees(bytes4 currencyKey) external optionalProxy returns (bool) { return _claimFees(messageSender, currencyKey); }
4,057,445
pragma solidity 0.4.26; import "./ISovrynSwapNetwork.sol"; import "./IConversionPathFinder.sol"; import "./converter/interfaces/IConverter.sol"; import "./converter/interfaces/IConverterAnchor.sol"; import "./converter/interfaces/ISovrynSwapFormula.sol"; import "./utility/ContractRegistryClient.sol"; import "./utility/ReentrancyGuard.sol"; import "./utility/TokenHolder.sol"; import "./utility/SafeMath.sol"; import "./token/interfaces/IEtherToken.sol"; import "./token/interfaces/ISmartToken.sol"; import "./sovrynswapx/interfaces/ISovrynSwapX.sol"; // interface of older converters for backward compatibility contract ILegacyConverter { function change( IERC20Token _sourceToken, IERC20Token _targetToken, uint256 _amount, uint256 _minReturn ) public returns (uint256); } /** * @dev The SovrynSwapNetwork contract is the main entry point for SovrynSwap token conversions. * It also allows for the conversion of any token in the SovrynSwap Network to any other token in a single * transaction by providing a conversion path. * * A note on Conversion Path: Conversion path is a data structure that is used when converting a token * to another token in the SovrynSwap Network, when the conversion cannot necessarily be done by a single * converter and might require multiple 'hops'. * The path defines which converters should be used and what kind of conversion should be done in each step. * * The path format doesn't include complex structure; instead, it is represented by a single array * in which each 'hop' is represented by a 2-tuple - converter anchor & target token. * In addition, the first element is always the source token. * The converter anchor is only used as a pointer to a converter (since converter addresses are more * likely to change as opposed to anchor addresses). * * Format: * [source token, converter anchor, target token, converter anchor, target token...] */ contract SovrynSwapNetwork is ISovrynSwapNetwork, TokenHolder, ContractRegistryClient, ReentrancyGuard { using SafeMath for uint256; uint256 private constant CONVERSION_FEE_RESOLUTION = 1000000; uint256 private constant AFFILIATE_FEE_RESOLUTION = 1000000; address private constant ETH_RESERVE_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; struct ConversionStep { IConverter converter; IConverterAnchor anchor; IERC20Token sourceToken; IERC20Token targetToken; address beneficiary; bool isV28OrHigherConverter; bool processAffiliateFee; } uint256 public maxAffiliateFee = 30000; // maximum affiliate-fee mapping(address => bool) public etherTokens; // list of all supported ether tokens /** * @dev triggered when a conversion between two tokens occurs * * @param _smartToken anchor governed by the converter * @param _fromToken source ERC20 token * @param _toToken target ERC20 token * @param _fromAmount amount converted, in the source token * @param _toAmount amount returned, minus conversion fee * @param _trader wallet that initiated the trade */ event Conversion( address indexed _smartToken, address indexed _fromToken, address indexed _toToken, uint256 _fromAmount, uint256 _toAmount, address _trader ); /** * @dev initializes a new SovrynSwapNetwork instance * * @param _registry address of a contract registry contract */ constructor(IContractRegistry _registry) public ContractRegistryClient(_registry) { etherTokens[ETH_RESERVE_ADDRESS] = true; } /** * @dev allows the owner to update the maximum affiliate-fee * * @param _maxAffiliateFee maximum affiliate-fee */ function setMaxAffiliateFee(uint256 _maxAffiliateFee) public ownerOnly { require(_maxAffiliateFee <= AFFILIATE_FEE_RESOLUTION, "ERR_INVALID_AFFILIATE_FEE"); maxAffiliateFee = _maxAffiliateFee; } /** * @dev allows the owner to register/unregister ether tokens * * @param _token ether token contract address * @param _register true to register, false to unregister */ function registerEtherToken(IEtherToken _token, bool _register) public ownerOnly validAddress(_token) notThis(_token) { etherTokens[_token] = _register; } /** * @dev returns the conversion path between two tokens in the network * note that this method is quite expensive in terms of gas and should generally be called off-chain * * @param _sourceToken source token address * @param _targetToken target token address * * @return conversion path between the two tokens */ function conversionPath(IERC20Token _sourceToken, IERC20Token _targetToken) public view returns (address[]) { IConversionPathFinder pathFinder = IConversionPathFinder(addressOf(CONVERSION_PATH_FINDER)); return pathFinder.findPath(_sourceToken, _targetToken); } /** * @dev returns the expected target amount of converting a given amount on a given path * note that there is no support for circular paths * * @param _path conversion path (see conversion path format above) * @param _amount amount of _path[0] tokens received from the sender * * @return expected target amount */ function rateByPath(IERC20Token[] _path, uint256 _amount) public view returns (uint256) { uint256 amount; uint256 fee; uint256 supply; uint256 balance; uint32 weight; IConverter converter; ISovrynSwapFormula formula = ISovrynSwapFormula(addressOf(SOVRYNSWAP_FORMULA)); amount = _amount; // verify that the number of elements is larger than 2 and odd require(_path.length > 2 && _path.length % 2 == 1, "ERR_INVALID_PATH"); // iterate over the conversion path for (uint256 i = 2; i < _path.length; i += 2) { IERC20Token sourceToken = _path[i - 2]; IERC20Token anchor = _path[i - 1]; IERC20Token targetToken = _path[i]; converter = IConverter(IConverterAnchor(anchor).owner()); // backward compatibility sourceToken = getConverterTokenAddress(converter, sourceToken); targetToken = getConverterTokenAddress(converter, targetToken); if (targetToken == anchor) { // buy the smart token // check if the current smart token has changed if (i < 3 || anchor != _path[i - 3]) supply = ISmartToken(anchor).totalSupply(); // get the amount & the conversion fee balance = converter.getConnectorBalance(sourceToken); (, weight, , , ) = converter.connectors(sourceToken); amount = formula.purchaseTargetAmount(supply, balance, weight, amount); fee = amount.mul(converter.conversionFee()).div(CONVERSION_FEE_RESOLUTION); amount -= fee; // update the smart token supply for the next iteration supply = supply.add(amount); } else if (sourceToken == anchor) { // sell the smart token // check if the current smart token has changed if (i < 3 || anchor != _path[i - 3]) supply = ISmartToken(anchor).totalSupply(); // get the amount & the conversion fee balance = converter.getConnectorBalance(targetToken); (, weight, , , ) = converter.connectors(targetToken); amount = formula.saleTargetAmount(supply, balance, weight, amount); fee = amount.mul(converter.conversionFee()).div(CONVERSION_FEE_RESOLUTION); amount -= fee; // update the smart token supply for the next iteration supply = supply.sub(amount); } else { // cross reserve conversion (amount, fee) = getReturn(converter, sourceToken, targetToken, amount); } } return amount; } /** * @dev converts the token to any other token in the sovrynSwap network by following * a predefined conversion path and transfers the result tokens to a target account * affiliate account/fee can also be passed in to receive a conversion fee (on top of the liquidity provider fees) * note that the network should already have been given allowance of the source token (if not ETH) * * @param _path conversion path, see conversion path format above * @param _amount amount to convert from, in the source token * @param _minReturn if the conversion results in an amount smaller than the minimum return - it is cancelled, must be greater than zero * @param _beneficiary account that will receive the conversion result or 0x0 to send the result to the sender account * @param _affiliateAccount wallet address to receive the affiliate fee or 0x0 to disable affiliate fee * @param _affiliateFee affiliate fee in PPM or 0 to disable affiliate fee * * @return amount of tokens received from the conversion */ function convertByPath( IERC20Token[] _path, uint256 _amount, uint256 _minReturn, address _beneficiary, address _affiliateAccount, uint256 _affiliateFee ) public payable protected greaterThanZero(_minReturn) returns (uint256) { // verify that the path contrains at least a single 'hop' and that the number of elements is odd require(_path.length > 2 && _path.length % 2 == 1, "ERR_INVALID_PATH"); // validate msg.value and prepare the source token for the conversion handleSourceToken(_path[0], IConverterAnchor(_path[1]), _amount); // check if affiliate fee is enabled bool affiliateFeeEnabled = false; if (address(_affiliateAccount) == 0) { require(_affiliateFee == 0, "ERR_INVALID_AFFILIATE_FEE"); } else { require(0 < _affiliateFee && _affiliateFee <= maxAffiliateFee, "ERR_INVALID_AFFILIATE_FEE"); affiliateFeeEnabled = true; } // check if beneficiary is set address beneficiary = msg.sender; if (_beneficiary != address(0)) beneficiary = _beneficiary; // convert and get the resulting amount ConversionStep[] memory data = createConversionData(_path, beneficiary, affiliateFeeEnabled); uint256 amount = doConversion(data, _amount, _minReturn, _affiliateAccount, _affiliateFee); // handle the conversion target tokens handleTargetToken(data, amount, beneficiary); return amount; } /** * @dev converts any other token to BNT in the sovrynSwap network by following a predefined conversion path and transfers the result to an account on a different blockchain * note that the network should already have been given allowance of the source token (if not ETH) * * @param _path conversion path, see conversion path format above * @param _amount amount to convert from, in the source token * @param _minReturn if the conversion results in an amount smaller than the minimum return - it is cancelled, must be greater than zero * @param _targetBlockchain blockchain BNT will be issued on * @param _targetAccount address/account on the target blockchain to send the BNT to * @param _conversionId pre-determined unique (if non zero) id which refers to this transaction * * @return the amount of BNT received from this conversion */ function xConvert( IERC20Token[] _path, uint256 _amount, uint256 _minReturn, bytes32 _targetBlockchain, bytes32 _targetAccount, uint256 _conversionId ) public payable returns (uint256) { return xConvert2(_path, _amount, _minReturn, _targetBlockchain, _targetAccount, _conversionId, address(0), 0); } /** * @dev converts any other token to BNT in the sovrynSwap network by following a predefined conversion path and transfers the result to an account on a different blockchain * note that the network should already have been given allowance of the source token (if not ETH) * * @param _path conversion path, see conversion path format above * @param _amount amount to convert from, in the source token * @param _minReturn if the conversion results in an amount smaller than the minimum return - it is cancelled, must be greater than zero * @param _targetBlockchain blockchain BNT will be issued on * @param _targetAccount address/account on the target blockchain to send the BNT to * @param _conversionId pre-determined unique (if non zero) id which refers to this transaction * @param _affiliateAccount affiliate account * @param _affiliateFee affiliate fee in PPM * * @return the amount of BNT received from this conversion */ function xConvert2( IERC20Token[] _path, uint256 _amount, uint256 _minReturn, bytes32 _targetBlockchain, bytes32 _targetAccount, uint256 _conversionId, address _affiliateAccount, uint256 _affiliateFee ) public payable greaterThanZero(_minReturn) returns (uint256) { IERC20Token targetToken = _path[_path.length - 1]; ISovrynSwapX sovrynSwapX = ISovrynSwapX(addressOf(SOVRYNSWAP_X)); // verify that the destination token is BNT require(targetToken == addressOf(BNT_TOKEN), "ERR_INVALID_TARGET_TOKEN"); // convert and get the resulting amount uint256 amount = convertByPath(_path, _amount, _minReturn, this, _affiliateAccount, _affiliateFee); // grant SovrynSwapX allowance ensureAllowance(targetToken, sovrynSwapX, amount); // transfer the resulting amount to SovrynSwapX sovrynSwapX.xTransfer(_targetBlockchain, _targetAccount, amount, _conversionId); return amount; } /** * @dev allows a user to convert a token that was sent from another blockchain into any other * token on the SovrynSwapNetwork * ideally this transaction is created before the previous conversion is even complete, so * so the input amount isn't known at that point - the amount is actually take from the * SovrynSwapX contract directly by specifying the conversion id * * @param _path conversion path * @param _sovrynSwapX address of the SovrynSwapX contract for the source token * @param _conversionId pre-determined unique (if non zero) id which refers to this conversion * @param _minReturn if the conversion results in an amount smaller than the minimum return - it is cancelled, must be nonzero * @param _beneficiary wallet to receive the conversion result * * @return amount of tokens received from the conversion */ function completeXConversion( IERC20Token[] _path, ISovrynSwapX _sovrynSwapX, uint256 _conversionId, uint256 _minReturn, address _beneficiary ) public returns (uint256) { // verify that the source token is the SovrynSwapX token require(_path[0] == _sovrynSwapX.token(), "ERR_INVALID_SOURCE_TOKEN"); // get conversion amount from SovrynSwapX contract uint256 amount = _sovrynSwapX.getXTransferAmount(_conversionId, msg.sender); // perform the conversion return convertByPath(_path, amount, _minReturn, _beneficiary, address(0), 0); } /** * @dev executes the actual conversion by following the conversion path * * @param _data conversion data, see ConversionStep struct above * @param _amount amount to convert from, in the source token * @param _minReturn if the conversion results in an amount smaller than the minimum return - it is cancelled, must be greater than zero * @param _affiliateAccount affiliate account * @param _affiliateFee affiliate fee in PPM * * @return amount of tokens received from the conversion */ function doConversion( ConversionStep[] _data, uint256 _amount, uint256 _minReturn, address _affiliateAccount, uint256 _affiliateFee ) private returns (uint256) { uint256 toAmount; uint256 fromAmount = _amount; // iterate over the conversion data for (uint256 i = 0; i < _data.length; i++) { ConversionStep memory stepData = _data[i]; // newer converter if (stepData.isV28OrHigherConverter) { // transfer the tokens to the converter only if the network contract currently holds the tokens // not needed with ETH or if it's the first conversion step if (i != 0 && _data[i - 1].beneficiary == address(this) && !etherTokens[stepData.sourceToken]) safeTransfer(stepData.sourceToken, stepData.converter, fromAmount); } // older converter // if the source token is the smart token, no need to do any transfers as the converter controls it else if (stepData.sourceToken != ISmartToken(stepData.anchor)) { // grant allowance for it to transfer the tokens from the network contract ensureAllowance(stepData.sourceToken, stepData.converter, fromAmount); } // do the conversion if (!stepData.isV28OrHigherConverter) toAmount = ILegacyConverter(stepData.converter).change(stepData.sourceToken, stepData.targetToken, fromAmount, 1); else if (etherTokens[stepData.sourceToken]) toAmount = stepData.converter.convert.value(msg.value)( stepData.sourceToken, stepData.targetToken, fromAmount, msg.sender, stepData.beneficiary ); else toAmount = stepData.converter.convert(stepData.sourceToken, stepData.targetToken, fromAmount, msg.sender, stepData.beneficiary); // pay affiliate-fee if needed if (stepData.processAffiliateFee) { uint256 affiliateAmount = toAmount.mul(_affiliateFee).div(AFFILIATE_FEE_RESOLUTION); require(stepData.targetToken.transfer(_affiliateAccount, affiliateAmount), "ERR_FEE_TRANSFER_FAILED"); toAmount -= affiliateAmount; } emit Conversion(stepData.anchor, stepData.sourceToken, stepData.targetToken, fromAmount, toAmount, msg.sender); fromAmount = toAmount; } // ensure the trade meets the minimum requested amount require(toAmount >= _minReturn, "ERR_RETURN_TOO_LOW"); return toAmount; } /** * @dev validates msg.value and prepares the conversion source token for the conversion * * @param _sourceToken source token of the first conversion step * @param _anchor converter anchor of the first conversion step * @param _amount amount to convert from, in the source token */ function handleSourceToken( IERC20Token _sourceToken, IConverterAnchor _anchor, uint256 _amount ) private { IConverter firstConverter = IConverter(_anchor.owner()); bool isNewerConverter = isV28OrHigherConverter(firstConverter); // ETH if (msg.value > 0) { // validate msg.value require(msg.value == _amount, "ERR_ETH_AMOUNT_MISMATCH"); // EtherToken converter - deposit the ETH into the EtherToken // note that it can still be a non ETH converter if the path is wrong // but such conversion will simply revert if (!isNewerConverter) IEtherToken(getConverterEtherTokenAddress(firstConverter)).deposit.value(msg.value)(); } // EtherToken else if (etherTokens[_sourceToken]) { // claim the tokens - if the source token is ETH reserve, this call will fail // since in that case the transaction must be sent with msg.value safeTransferFrom(_sourceToken, msg.sender, this, _amount); // ETH converter - withdraw the ETH if (isNewerConverter) IEtherToken(_sourceToken).withdraw(_amount); } // other ERC20 token else { // newer converter - transfer the tokens from the sender directly to the converter // otherwise claim the tokens if (isNewerConverter) safeTransferFrom(_sourceToken, msg.sender, firstConverter, _amount); else safeTransferFrom(_sourceToken, msg.sender, this, _amount); } } /** * @dev handles the conversion target token if the network still holds it at the end of the conversion * * @param _data conversion data, see ConversionStep struct above * @param _amount conversion target amount * @param _beneficiary wallet to receive the conversion result */ function handleTargetToken( ConversionStep[] _data, uint256 _amount, address _beneficiary ) private { ConversionStep memory stepData = _data[_data.length - 1]; // network contract doesn't hold the tokens, do nothing if (stepData.beneficiary != address(this)) return; IERC20Token targetToken = stepData.targetToken; // ETH / EtherToken if (etherTokens[targetToken]) { // newer converter should send ETH directly to the beneficiary assert(!stepData.isV28OrHigherConverter); // EtherToken converter - withdraw the ETH and transfer to the beneficiary IEtherToken(targetToken).withdrawTo(_beneficiary, _amount); } // other ERC20 token else { safeTransfer(targetToken, _beneficiary, _amount); } } /** * @dev creates a memory cache of all conversion steps data to minimize logic and external calls during conversions * * @param _conversionPath conversion path, see conversion path format above * @param _beneficiary wallet to receive the conversion result * @param _affiliateFeeEnabled true if affiliate fee was requested by the sender, false if not * * @return cached conversion data to be ingested later on by the conversion flow */ function createConversionData( IERC20Token[] _conversionPath, address _beneficiary, bool _affiliateFeeEnabled ) private view returns (ConversionStep[]) { ConversionStep[] memory data = new ConversionStep[](_conversionPath.length / 2); bool affiliateFeeProcessed = false; address bntToken = addressOf(BNT_TOKEN); // iterate the conversion path and create the conversion data for each step uint256 i; for (i = 0; i < _conversionPath.length - 1; i += 2) { IConverterAnchor anchor = IConverterAnchor(_conversionPath[i + 1]); IConverter converter = IConverter(anchor.owner()); IERC20Token targetToken = _conversionPath[i + 2]; // check if the affiliate fee should be processed in this step bool processAffiliateFee = _affiliateFeeEnabled && !affiliateFeeProcessed && targetToken == bntToken; if (processAffiliateFee) affiliateFeeProcessed = true; data[i / 2] = ConversionStep({ anchor: // set the converter anchor anchor, converter: // set the converter converter, sourceToken: // set the source/target tokens _conversionPath[i], targetToken: targetToken, beneficiary: // requires knowledge about the next step, so initialize in the next phase address(0), isV28OrHigherConverter: // set flags isV28OrHigherConverter(converter), processAffiliateFee: processAffiliateFee }); } // ETH support // source is ETH ConversionStep memory stepData = data[0]; if (etherTokens[stepData.sourceToken]) { // newer converter - replace the source token address with ETH reserve address if (stepData.isV28OrHigherConverter) stepData.sourceToken = IERC20Token(ETH_RESERVE_ADDRESS); // older converter - replace the source token with the EtherToken address used by the converter else stepData.sourceToken = IERC20Token(getConverterEtherTokenAddress(stepData.converter)); } // target is ETH stepData = data[data.length - 1]; if (etherTokens[stepData.targetToken]) { // newer converter - replace the target token address with ETH reserve address if (stepData.isV28OrHigherConverter) stepData.targetToken = IERC20Token(ETH_RESERVE_ADDRESS); // older converter - replace the target token with the EtherToken address used by the converter else stepData.targetToken = IERC20Token(getConverterEtherTokenAddress(stepData.converter)); } // set the beneficiary for each step for (i = 0; i < data.length; i++) { stepData = data[i]; // first check if the converter in this step is newer as older converters don't even support the beneficiary argument if (stepData.isV28OrHigherConverter) { // if affiliate fee is processed in this step, beneficiary is the network contract if (stepData.processAffiliateFee) stepData.beneficiary = this; // if it's the last step, beneficiary is the final beneficiary else if (i == data.length - 1) stepData.beneficiary = _beneficiary; // if the converter in the next step is newer, beneficiary is the next converter else if (data[i + 1].isV28OrHigherConverter) stepData.beneficiary = data[i + 1].converter; // the converter in the next step is older, beneficiary is the network contract else stepData.beneficiary = this; } else { // converter in this step is older, beneficiary is the network contract stepData.beneficiary = this; } } return data; } /** * @dev utility, checks whether allowance for the given spender exists and approves one if it doesn't. * Note that we use the non standard erc-20 interface in which `approve` has no return value so that * this function will work for both standard and non standard tokens * * @param _token token to check the allowance in * @param _spender approved address * @param _value allowance amount */ function ensureAllowance( IERC20Token _token, address _spender, uint256 _value ) private { uint256 allowance = _token.allowance(this, _spender); if (allowance < _value) { if (allowance > 0) safeApprove(_token, _spender, 0); safeApprove(_token, _spender, _value); } } // legacy - returns the address of an EtherToken used by the converter function getConverterEtherTokenAddress(IConverter _converter) private view returns (address) { uint256 reserveCount = _converter.connectorTokenCount(); for (uint256 i = 0; i < reserveCount; i++) { address reserveTokenAddress = _converter.connectorTokens(i); if (etherTokens[reserveTokenAddress]) return reserveTokenAddress; } return ETH_RESERVE_ADDRESS; } // legacy - if the token is an ether token, returns the ETH reserve address // used by the converter, otherwise returns the input token address function getConverterTokenAddress(IConverter _converter, IERC20Token _token) private view returns (IERC20Token) { if (!etherTokens[_token]) return _token; if (isV28OrHigherConverter(_converter)) return IERC20Token(ETH_RESERVE_ADDRESS); return IERC20Token(getConverterEtherTokenAddress(_converter)); } bytes4 private constant GET_RETURN_FUNC_SELECTOR = bytes4(keccak256("getReturn(address,address,uint256)")); // using assembly code since older converter versions have different return values function getReturn( address _dest, address _sourceToken, address _targetToken, uint256 _amount ) internal view returns (uint256, uint256) { uint256[2] memory ret; bytes memory data = abi.encodeWithSelector(GET_RETURN_FUNC_SELECTOR, _sourceToken, _targetToken, _amount); assembly { let success := staticcall( gas, // gas remaining _dest, // destination address add(data, 32), // input buffer (starts after the first 32 bytes in the `data` array) mload(data), // input length (loaded from the first 32 bytes in the `data` array) ret, // output buffer 64 // output length ) if iszero(success) { revert(0, 0) } } return (ret[0], ret[1]); } bytes4 private constant IS_V28_OR_HIGHER_FUNC_SELECTOR = bytes4(keccak256("isV28OrHigher()")); // using assembly code to identify converter version // can't rely on the version number since the function had a different signature in older converters function isV28OrHigherConverter(IConverter _converter) internal view returns (bool) { bool success; uint256[1] memory ret; bytes memory data = abi.encodeWithSelector(IS_V28_OR_HIGHER_FUNC_SELECTOR); assembly { success := staticcall( 5000, // isV28OrHigher consumes 190 gas, but just for extra safety _converter, // destination address add(data, 32), // input buffer (starts after the first 32 bytes in the `data` array) mload(data), // input length (loaded from the first 32 bytes in the `data` array) ret, // output buffer 32 // output length ) } return success && ret[0] != 0; } /** * @dev deprecated, backward compatibility */ function getReturnByPath(IERC20Token[] _path, uint256 _amount) public view returns (uint256, uint256) { return (rateByPath(_path, _amount), 0); } /** * @dev deprecated, backward compatibility */ function convert( IERC20Token[] _path, uint256 _amount, uint256 _minReturn ) public payable returns (uint256) { return convertByPath(_path, _amount, _minReturn, address(0), address(0), 0); } /** * @dev deprecated, backward compatibility */ function convert2( IERC20Token[] _path, uint256 _amount, uint256 _minReturn, address _affiliateAccount, uint256 _affiliateFee ) public payable returns (uint256) { return convertByPath(_path, _amount, _minReturn, address(0), _affiliateAccount, _affiliateFee); } /** * @dev deprecated, backward compatibility */ function convertFor( IERC20Token[] _path, uint256 _amount, uint256 _minReturn, address _beneficiary ) public payable returns (uint256) { return convertByPath(_path, _amount, _minReturn, _beneficiary, address(0), 0); } /** * @dev deprecated, backward compatibility */ function convertFor2( IERC20Token[] _path, uint256 _amount, uint256 _minReturn, address _beneficiary, address _affiliateAccount, uint256 _affiliateFee ) public payable greaterThanZero(_minReturn) returns (uint256) { return convertByPath(_path, _amount, _minReturn, _beneficiary, _affiliateAccount, _affiliateFee); } /** * @dev deprecated, backward compatibility */ function claimAndConvert( IERC20Token[] _path, uint256 _amount, uint256 _minReturn ) public returns (uint256) { return convertByPath(_path, _amount, _minReturn, address(0), address(0), 0); } /** * @dev deprecated, backward compatibility */ function claimAndConvert2( IERC20Token[] _path, uint256 _amount, uint256 _minReturn, address _affiliateAccount, uint256 _affiliateFee ) public returns (uint256) { return convertByPath(_path, _amount, _minReturn, address(0), _affiliateAccount, _affiliateFee); } /** * @dev deprecated, backward compatibility */ function claimAndConvertFor( IERC20Token[] _path, uint256 _amount, uint256 _minReturn, address _beneficiary ) public returns (uint256) { return convertByPath(_path, _amount, _minReturn, _beneficiary, address(0), 0); } /** * @dev deprecated, backward compatibility */ function claimAndConvertFor2( IERC20Token[] _path, uint256 _amount, uint256 _minReturn, address _beneficiary, address _affiliateAccount, uint256 _affiliateFee ) public returns (uint256) { return convertByPath(_path, _amount, _minReturn, _beneficiary, _affiliateAccount, _affiliateFee); } }
deprecated, backward compatibility/
function convert2( IERC20Token[] _path, uint256 _amount, uint256 _minReturn, address _affiliateAccount, uint256 _affiliateFee ) public payable returns (uint256) { return convertByPath(_path, _amount, _minReturn, address(0), _affiliateAccount, _affiliateFee); }
12,943,220
./full_match/5/0x201e479D966a08f2B0E9c886c9cb9E3e5c1d0A65/sources/contracts/DAOToken.sol
Returns whether owner can be set in the given execution context.
function _canSetOwner() internal view override returns (bool) { return msg.sender == owner(); }
1,898,442
// SPDX-License-Identifier: Apache-2.0 pragma solidity >=0.6.4 <0.8.0; pragma experimental ABIEncoderV2; //import "https://github.com/vigilance91/solidarity/contracts/token/TokenSupply/iEncoderTokenSupply.sol"; import "https://github.com/vigilance91/solidarity/contracts/token/TokenIdentifier/encoder/iEncoderTokenIdentifier.sol"; /// /// @dev EIP1153 License Transaction Encoder Interface /// @author Tyler R. Drury <[email protected]> (www.twitter.com/StudiosVigil) - copyright 29/8/2021, All Rights Reserved /// //Ethereum Improvments Proposal: Smart Contract Interface for Licences[sic]: https://eips.ethereum.org/EIPS/eip-1753 interface iEncoderEIP1753 is iEncoderTokenIdentifier //iEncoderTokenSupply { //read-only interface //current circulating supply(licnese which have been issued) //function circulatingSupply( //)external pure returns( //bytes memory //); //totalSupply - issued //function remainingSupply( //)public view returns( //uint256 //); //does client currently hold a valid license function hasValidLicense( address client )external pure returns( bytes memory ); //amount of seconds from now client has until their license is expired //function durationRemaining( //address client //)external pure returns( //bytes memory //); /// does client have authority to issue/revoke licenses function hasAuthority( address client )external pure returns( bytes memory ); /// ///mutable interface /// ///owner grants account elevated privellages (such as issuing and revoking licenses) ///issuing authorities can NOT themselves grant or revoke authority, ///that should be an owner/admin privellage ONLY function grantAuthority( address account )external pure returns( bytes memory ); //revoke account's elevated privellages as an issuing authority function revokeAuthority( address account )external pure returns( bytes memory ); ///an issuing authority issues client a license which is valid between the timestamp from, ///until the timestamp to from can be retroactive (in the past) but to MUST always be in the future function issue( address client, uint from, uint to )external pure returns( bytes memory ); ///issuing authority revokes client's license ///reverts if client does not have a license or if caller is not an issuing authority function revoke( address client )external pure returns( bytes memory ); /** ///notice interfaces can not have payable functions for some reason /// ///caller purchases a license, if one is available, otherwise reverts function purchase( uint validFrom, uint validTo )external pure returns( bytes memory ); ///renew an active license, extending to timestamp time function renewTime( address client, uint time )external pure returns( bytes memory ); ///renew an active license, extending by duration seconds function renewDuration( address client, uint duration )external pure returns( bytes memory ); */ }
iEncoderTokenSupplyread-only interfacecurrent circulating supply(licnese which have been issued)function circulatingSupply()external pure returns(bytes memory);totalSupply - issuedfunction remainingSupply()public view returns(uint256);does client currently hold a valid licenseamount of seconds from now client has until their license is expiredfunction durationRemaining(address client)external pure returns(bytes memory);revoke account's elevated privellages as an issuing authority
{ function hasValidLicense( address client )external pure returns( bytes memory ); function hasAuthority( address client )external pure returns( bytes memory ); function grantAuthority( address account )external pure returns( bytes memory ); function revokeAuthority( address account )external pure returns( bytes memory ); function issue( address client, uint from, uint to )external pure returns( bytes memory ); function revoke( address client )external pure returns( bytes memory ); function purchase( uint validFrom, uint validTo )external pure returns( bytes memory ); function renewTime( address client, uint time )external pure returns( bytes memory ); function renewDuration( address client, uint duration )external pure returns( bytes memory ); interface iEncoderEIP1753 is iEncoderTokenIdentifier }
14,077,773
./full_match/11155111/0x8Ba8302A07D050F34cCCBC8c8F9ff43595206576/sources/contracts/TournamentFactory.sol
This function retrieves the address of a Tournament contract
function getTournament(uint index) public view returns (address) { require(index < tournaments.length, "Tournament index out of bounds"); return tournaments[index]; }
3,798,501
./full_match/8453/0x5F8d42635A2fa74D03b5F91c825dE6F44c443dA5/sources/contracts/lendingpool/StakingRewards.sol
Withdraw `amount` of staked assets amount The amount of assets to withdraw to The address that will receive the staked assets, same as msg.sender if the user wants to receive them on his own wallet./
function withdraw( uint amount, address to ) external nonReentrant updateReward(msg.sender) { require(amount > 0, "amount = 0"); balanceOf[msg.sender] -= amount; totalStaked -= amount; require(stakedToken.transfer(to, amount), "transfer failed"); emit Withdraw(msg.sender, to, amount); }
11,555,253
./full_match/1/0xda3Bb6122BDC762Fb83D37AD2b09e7F2Cf6612f5/sources/src/Originals.sol
Used to burn token(s) of a release for a one account./
function burn( uint256 __tokenID ) public override onlyExistingToken(__tokenID) { super.burn(__tokenID); Token memory token = _tokens[__tokenID]; _releases[token.releaseID].tokenIDs[token.index] = 0; _releases[token.releaseID].totalSupply -= 1; }
4,843,991
pragma solidity ^0.4.19; contract SupportedContract { // Members can call any contract that exposes a `theCyberMessage` method. function theCyberMessage(string) public; } contract ERC20 { // We want to be able to recover & donate any tokens sent to the contract. function balanceOf(address _who) public view returns (uint256); function transfer(address _to, uint256 _value) public returns (bool); } contract theCyber { // theCyber is a decentralized club. It does not support equity memberships, // payment of dues, or payouts to the members. Instead, it is meant to enable // dapps that allow members to communicate with one another or that provide // arbitrary incentives or special access to the club's members. To become a // member of theCyber, you must be added by an existing member. Furthermore, // existing memberships can be revoked if a given member becomes inactive for // too long. Total membership is capped and unique addresses are required. event NewMember(uint8 indexed memberId, bytes32 memberName, address indexed memberAddress); event NewMemberName(uint8 indexed memberId, bytes32 newMemberName); event NewMemberKey(uint8 indexed memberId, string newMemberKey); event MembershipTransferred(uint8 indexed memberId, address newMemberAddress); event MemberProclaimedInactive(uint8 indexed memberId, uint8 indexed proclaimingMemberId); event MemberHeartbeated(uint8 indexed memberId); event MembershipRevoked(uint8 indexed memberId, uint8 indexed revokingMemberId); event BroadcastMessage(uint8 indexed memberId, string message); event DirectMessage(uint8 indexed memberId, uint8 indexed toMemberId, string message); event Call(uint8 indexed memberId, address indexed contractAddress, string message); event FundsDonated(uint8 indexed memberId, uint256 value); event TokensDonated(uint8 indexed memberId, address tokenContractAddress, uint256 value); // There can only be 256 members (member number 0 to 255) in theCyber. uint16 private constant MAXMEMBERS_ = 256; // A membership that has been marked as inactive for 90 days may be revoked. uint64 private constant INACTIVITYTIMEOUT_ = 90 days; // Set the ethereum tip jar (ethereumfoundation.eth) as the donation address. address private constant DONATIONADDRESS_ = 0xfB6916095ca1df60bB79Ce92cE3Ea74c37c5d359; // A member has a name, a public key, a date they joined, and a date they were // marked as inactive (which is equial to 0 if they are currently active). struct Member { bool member; bytes32 name; string pubkey; uint64 memberSince; uint64 inactiveSince; } // Set up a fixed array of members indexed by member id. Member[MAXMEMBERS_] internal members_; // Map addresses to booleans designating that they control the membership. mapping (address => bool) internal addressIsMember_; // Map addresses to member ids. mapping (address => uint8) internal addressToMember_; // Map member ids to addresses that own the membership. mapping (uint => address) internal memberToAddress_; // Most methods of the contract, like adding new members or revoking existing // inactive members, can only be called by a valid member. modifier membersOnly() { // Only allow transactions originating from a designated member address. require(addressIsMember_[msg.sender]); _; } // In the constructor function, set up the contract creator as the first // member so that other new members can be added. function theCyber() public { // Log the addition of the first member (contract creator). NewMember(0, "", msg.sender); // Set up the member: status, name, key, member since & inactive since. members_[0] = Member(true, bytes32(""), "", uint64(now), 0); // Set up the address associated with the member. memberToAddress_[0] = msg.sender; // Point the address to member's id. addressToMember_[msg.sender] = 0; // Grant members-only access to the new member. addressIsMember_[msg.sender] = true; } // Existing members can designate new users by specifying an unused member id // and address. The new member's initial member name should also be supplied. function newMember(uint8 _memberId, bytes32 _memberName, address _memberAddress) public membersOnly { // Members need a non-null address. require(_memberAddress != address(0)); // Existing members (that have not fallen inactive) cannot be replaced. require (!members_[_memberId].member); // One address cannot hold more than one membership. require (!addressIsMember_[_memberAddress]); // Log the addition of a new member: (member id, name, address). NewMember(_memberId, _memberName, _memberAddress); // Set up the member: status, name, `member since` & `inactive since`. members_[_memberId] = Member(true, _memberName, "", uint64(now), 0); // Set up the address associated with the member id. memberToAddress_[_memberId] = _memberAddress; // Point the address to the member id. addressToMember_[_memberAddress] = _memberId; // Grant members-only access to the new member. addressIsMember_[_memberAddress] = true; } // Members can set a name (encoded as a hex value) that will be associated // with their membership. function changeName(bytes32 _newMemberName) public membersOnly { // Log the member's name change: (member id, new name). NewMemberName(addressToMember_[msg.sender], _newMemberName); // Change the member's name. members_[addressToMember_[msg.sender]].name = _newMemberName; } // Members can set a public key that will be used for verifying signed // messages from the member or encrypting messages intended for the member. function changeKey(string _newMemberKey) public membersOnly { // Log the member's key change: (member id, new member key). NewMemberKey(addressToMember_[msg.sender], _newMemberKey); // Change the member's public key. members_[addressToMember_[msg.sender]].pubkey = _newMemberKey; } // Members can transfer their membership to a new address; when they do, the // fields on the membership are all reset. function transferMembership(address _newMemberAddress) public membersOnly { // Members need a non-null address. require(_newMemberAddress != address(0)); // Memberships cannot be transferred to existing members. require (!addressIsMember_[_newMemberAddress]); // Log transfer of membership: (member id, new address). MembershipTransferred(addressToMember_[msg.sender], _newMemberAddress); // Revoke members-only access for the old member. delete addressIsMember_[msg.sender]; // Reset fields on the membership. members_[addressToMember_[msg.sender]].memberSince = uint64(now); members_[addressToMember_[msg.sender]].inactiveSince = 0; members_[addressToMember_[msg.sender]].name = bytes32(""); members_[addressToMember_[msg.sender]].pubkey = ""; // Replace the address associated with the member id. memberToAddress_[addressToMember_[msg.sender]] = _newMemberAddress; // Point the new address to the member id and clean up the old pointer. addressToMember_[_newMemberAddress] = addressToMember_[msg.sender]; delete addressToMember_[msg.sender]; // Grant members-only access to the new member. addressIsMember_[_newMemberAddress] = true; } // As a mechanism to remove members that are no longer active due to lost keys // or a lack of engagement, other members may proclaim them as inactive. function proclaimInactive(uint8 _memberId) public membersOnly { // Members must exist and be currently active to proclaim inactivity. require(members_[_memberId].member); require(memberIsActive(_memberId)); // Members cannot proclaim themselves as inactive (safety measure). require(addressToMember_[msg.sender] != _memberId); // Log proclamation of inactivity: (inactive member id, member id, time). MemberProclaimedInactive(_memberId, addressToMember_[msg.sender]); // Set the `inactiveSince` field on the inactive member. members_[_memberId].inactiveSince = uint64(now); } // Members that have erroneously been marked as inactive may send a heartbeat // to prove that they are still active, voiding the `inactiveSince` property. function heartbeat() public membersOnly { // Log that the member has heartbeated and is still active. MemberHeartbeated(addressToMember_[msg.sender]); // Designate member as active by voiding their `inactiveSince` field. members_[addressToMember_[msg.sender]].inactiveSince = 0; } // If a member has been marked inactive for the duration of the inactivity // timeout, another member may revoke their membership and delete them. function revokeMembership(uint8 _memberId) public membersOnly { // Members must exist in order to be revoked. require(members_[_memberId].member); // Members must be designated as inactive. require(!memberIsActive(_memberId)); // Members cannot revoke themselves (safety measure). require(addressToMember_[msg.sender] != _memberId); // Members must be inactive for the duration of the inactivity timeout. require(now >= members_[_memberId].inactiveSince + INACTIVITYTIMEOUT_); // Log that the membership has been revoked. MembershipRevoked(_memberId, addressToMember_[msg.sender]); // Revoke members-only access for the member. delete addressIsMember_[memberToAddress_[_memberId]]; // Delete the pointer linking the address to the member id. delete addressToMember_[memberToAddress_[_memberId]]; // Delete the address associated with the member id. delete memberToAddress_[_memberId]; // Finally, delete the member. delete members_[_memberId]; } // While most messaging is intended to occur off-chain using supplied keys, // members can also broadcast a message as an on-chain event. function broadcastMessage(string _message) public membersOnly { // Log the message. BroadcastMessage(addressToMember_[msg.sender], _message); } // In addition, members can send direct messagees as an on-chain event. These // messages are intended to be encrypted using the recipient's public key. function directMessage(uint8 _toMemberId, string _message) public membersOnly { // Log the message. DirectMessage(addressToMember_[msg.sender], _toMemberId, _message); } // Members can also pass a message to any contract that supports it (via the // `theCyberMessage(string)` function), designated by the contract address. function passMessage(address _contractAddress, string _message) public membersOnly { // Log that another contract has been called and passed a message. Call(addressToMember_[msg.sender], _contractAddress, _message); // call the method of the target contract and pass in the message. SupportedContract(_contractAddress).theCyberMessage(_message); } // The contract is not payable by design, but could end up with a balance as // a recipient of a selfdestruct / coinbase of a mined block. function donateFunds() public membersOnly { // Log the donation of any funds that have made their way into the contract. FundsDonated(addressToMember_[msg.sender], this.balance); // Send all available funds to the donation address. DONATIONADDRESS_.transfer(this.balance); } // We also want to be able to access any tokens that are sent to the contract. function donateTokens(address _tokenContractAddress) public membersOnly { // Make sure that we didn't pass in the current contract address by mistake. require(_tokenContractAddress != address(this)); // Log the donation of any tokens that have been sent into the contract. TokensDonated(addressToMember_[msg.sender], _tokenContractAddress, ERC20(_tokenContractAddress).balanceOf(this)); // Send all available tokens at the given contract to the donation address. ERC20(_tokenContractAddress).transfer(DONATIONADDRESS_, ERC20(_tokenContractAddress).balanceOf(this)); } function getMembershipStatus(address _memberAddress) public view returns (bool member, uint8 memberId) { return ( addressIsMember_[_memberAddress], addressToMember_[_memberAddress] ); } function getMemberInformation(uint8 _memberId) public view returns (bytes32 memberName, string memberKey, uint64 memberSince, uint64 inactiveSince, address memberAddress) { return ( members_[_memberId].name, members_[_memberId].pubkey, members_[_memberId].memberSince, members_[_memberId].inactiveSince, memberToAddress_[_memberId] ); } function maxMembers() public pure returns(uint16) { return MAXMEMBERS_; } function inactivityTimeout() public pure returns(uint64) { return INACTIVITYTIMEOUT_; } function donationAddress() public pure returns(address) { return DONATIONADDRESS_; } function memberIsActive(uint8 _memberId) internal view returns (bool) { return (members_[_memberId].inactiveSince == 0); } }
In the constructor function, set up the contract creator as the first member so that other new members can be added. Log the addition of the first member (contract creator). Set up the member: status, name, key, member since & inactive since. Set up the address associated with the member. Point the address to member's id. Grant members-only access to the new member.
function theCyber() public { NewMember(0, "", msg.sender); members_[0] = Member(true, bytes32(""), "", uint64(now), 0); memberToAddress_[0] = msg.sender; addressToMember_[msg.sender] = 0; addressIsMember_[msg.sender] = true; }
5,480,626
./partial_match/1/0xa52c0Bb1b802e9d6A483072d56fd22B58B964455/sources/contracts/mixins/shared/FoundationTreasuryNode.sol
Gets the Foundation treasury contract. This call is used in the royalty registry contract. return treasuryAddress The address of the Foundation treasury contract./
function getFoundationTreasury() public view returns (address payable treasuryAddress) { treasuryAddress = treasury; }
2,625,146
pragma solidity 0.7.5; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; /** * @dev YzerChain token of ERC20 standard. * * name : YzerChain * symbol : YZR * decimal : 18 * initial supply : 10,000,000 YZR */ contract YzerChain is Ownable, ERC20 { mapping (address => bool) public minters; /** * @dev Initialize token with name, symbol, and mint supply. */ constructor() public Ownable() ERC20('YzerChain', 'YZR') { _mint(msg.sender, 10000000 * 1e18); } /** * @dev Mint `amount` token to `account`. * * Only minter can mint. */ function mint(address account, uint amount) external { require(minters[msg.sender], "not minter"); _mint(account, amount); } /** * @dev Burn `amount` token. * * Only minter can burn. */ function burn(uint amount) external { require(minters[msg.sender], "not minter"); _burn(address(this), amount); } /** * @dev Add `minter` to the minters list. * * Only owner can add minter. */ function addMinter(address minter) external onlyOwner { minters[minter] = true; } /** * @dev Remove `minter` from the minters list. * * Only owner can remove minter */ function removeMinter(address minter) external onlyOwner { minters[minter] = false; } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.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. */ 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 pragma solidity >=0.6.0 <0.8.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "../../GSN/Context.sol"; import "./IERC20.sol"; import "../../math/SafeMath.sol"; /** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {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 { } } // 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); }
Burn `amount` token. Only minter can burn./
function burn(uint amount) external { require(minters[msg.sender], "not minter"); _burn(address(this), amount); }
1,356,055
./partial_match/1/0x6893491CeCF9309e445fE10f49CEd15CBb08652F/sources/Migration_Schedar.sol
trips the breaker and returns boolean, where true means the breaker has tripped state
function _verifyCircuitBreakers() internal returns (bool) { address debtRatioAggregator = requireAndGetAddress(CONTRACT_EXT_AGGREGATOR_DEBT_RATIO); (, int256 rawRatio, , , ) = AggregatorV2V3Interface(debtRatioAggregator).latestRoundData(); (, bool broken, ) = exchangeRates().rateWithSafetyChecks(SNX); return circuitBreaker().probeCircuitBreaker(debtRatioAggregator, uint(rawRatio)) || broken; }
4,485,300
./partial_match/1/0x95F6FC8511675a30BEA4Eda1a797FEb0ac619468/sources/PendulumArt.sol
Private function to add a token to this extension's ownership-tracking data structures. to address representing the new owner of the given token ID 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; }
3,919,973
./partial_match/1/0x7d000609a3c0C6Ba13DD318E56934CB5523Ba431/sources/SolomonSale.sol
Exchange the value of ETH sent in the transaction for ERC20 tokens
function exchange() public payable { require(!_paused, "Sale is paused"); require(msg.value >= _minimum, "Value less than minimum"); uint256 contributed = _contributions[msg.sender] + msg.value; require((_maximum == 0) || (contributed <= _maximum), "Contribution limit exceeded"); uint256 tokenAmount = msg.value * _exchangeRate; require(availableTokens() >= tokenAmount, "Sale funds low"); _contributions[msg.sender] = contributed; _token.transfer(msg.sender, tokenAmount); emit Exchange(msg.sender, msg.value, tokenAmount); }
4,344,252
/** *Submitted for verification at Etherscan.io on 2020-08-23 */ // File: contracts/spec_interfaces/IContractRegistry.sol pragma solidity 0.5.16; interface IContractRegistry { event ContractAddressUpdated(string contractName, address addr); /// @dev updates the contracts address and emits a corresponding event function set(string calldata contractName, address addr) external /* onlyGovernor */; /// @dev returns the current address of the function get(string calldata contractName) external view returns (address); } // File: contracts/spec_interfaces/ICertification.sol pragma solidity 0.5.16; /// @title Elections contract interface interface ICertification /* is Ownable */ { event GuardianCertificationUpdate(address guardian, bool isCertified); /* * External methods */ /// @dev Called by a guardian as part of the automatic vote unready flow /// Used by the Election contract function isGuardianCertified(address addr) external view returns (bool isCertified); /// @dev Called by a guardian as part of the automatic vote unready flow /// Used by the Election contract function setGuardianCertification(address addr, bool isCertified) external /* Owner only */ ; /* * Governance */ /// @dev Updates the address calldata of the contract registry function setContractRegistry(IContractRegistry _contractRegistry) external /* onlyMigrationOwner */; } // File: contracts/spec_interfaces/IProtocol.sol pragma solidity 0.5.16; interface IProtocol { event ProtocolVersionChanged(string deploymentSubset, uint256 currentVersion, uint256 nextVersion, uint256 fromTimestamp); /* * External methods */ /// @dev returns true if the given deployment subset exists (i.e - is registered with a protocol version) function deploymentSubsetExists(string calldata deploymentSubset) external view returns (bool); /// @dev returns the current protocol version for the given deployment subset. function getProtocolVersion(string calldata deploymentSubset) external view returns (uint256); /* * Governor methods */ /// @dev create a new deployment subset. function createDeploymentSubset(string calldata deploymentSubset, uint256 initialProtocolVersion) external /* onlyFunctionalOwner */; /// @dev schedules a protocol version upgrade for the given deployment subset. function setProtocolVersion(string calldata deploymentSubset, uint256 nextVersion, uint256 fromTimestamp) external /* onlyFunctionalOwner */; } // File: contracts/spec_interfaces/ICommittee.sol pragma solidity 0.5.16; /// @title Elections contract interface interface ICommittee { event GuardianCommitteeChange(address addr, uint256 weight, bool certification, bool inCommittee); event CommitteeSnapshot(address[] addrs, uint256[] weights, bool[] certification); // No external functions /* * Methods restricted to other Orbs contracts */ /// @dev Called by: Elections contract /// Notifies a weight change for sorting to a relevant committee member. /// weight = 0 indicates removal of the member from the committee (for exmaple on unregister, voteUnready, voteOut) function memberWeightChange(address addr, uint256 weight) external returns (bool committeeChanged) /* onlyElectionContract */; /// @dev Called by: Elections contract /// Notifies a guardian certification change function memberCertificationChange(address addr, bool isCertified) external returns (bool committeeChanged) /* onlyElectionsContract */; /// @dev Called by: Elections contract /// Notifies a a member removal for exampl e due to voteOut / voteUnready function removeMember(address addr) external returns (bool committeeChanged) /* onlyElectionContract */; /// @dev Called by: Elections contract /// Notifies a new member applicable for committee (due to registration, unbanning, certification change) function addMember(address addr, uint256 weight, bool isCertified) external returns (bool committeeChanged) /* onlyElectionsContract */; /// @dev Called by: Elections contract /// Returns the committee members and their weights function getCommittee() external view returns (address[] memory addrs, uint256[] memory weights, bool[] memory certification); /* * Governance */ function setMaxTimeBetweenRewardAssignments(uint32 maxTimeBetweenRewardAssignments) external /* onlyFunctionalOwner onlyWhenActive */; function setMaxCommittee(uint8 maxCommitteeSize) external /* onlyFunctionalOwner onlyWhenActive */; event MaxTimeBetweenRewardAssignmentsChanged(uint32 newValue, uint32 oldValue); event MaxCommitteeSizeChanged(uint8 newValue, uint8 oldValue); /// @dev Updates the address calldata of the contract registry function setContractRegistry(IContractRegistry _contractRegistry) external /* onlyMigrationOwner */; /* * Getters */ /// @dev returns the current committee /// used also by the rewards and fees contracts function getCommitteeInfo() external view returns (address[] memory addrs, uint256[] memory weights, address[] memory orbsAddrs, bool[] memory certification, bytes4[] memory ips); /// @dev returns the current settings of the committee contract function getSettings() external view returns (uint32 maxTimeBetweenRewardAssignments, uint8 maxCommitteeSize); } // File: contracts/IStakeChangeNotifier.sol pragma solidity 0.5.16; /// @title An interface for notifying of stake change events (e.g., stake, unstake, partial unstake, restate, etc.). interface IStakeChangeNotifier { /// @dev Notifies of stake change event. /// @param _stakeOwner address The address of the subject stake owner. /// @param _amount uint256 The difference in the total staked amount. /// @param _sign bool The sign of the added (true) or subtracted (false) amount. /// @param _updatedStake uint256 The updated total staked amount. function stakeChange(address _stakeOwner, uint256 _amount, bool _sign, uint256 _updatedStake) external; /// @dev Notifies of multiple stake change events. /// @param _stakeOwners address[] The addresses of subject stake owners. /// @param _amounts uint256[] The differences in total staked amounts. /// @param _signs bool[] The signs of the added (true) or subtracted (false) amounts. /// @param _updatedStakes uint256[] The updated total staked amounts. function stakeChangeBatch(address[] calldata _stakeOwners, uint256[] calldata _amounts, bool[] calldata _signs, uint256[] calldata _updatedStakes) external; /// @dev Notifies of stake migration event. /// @param _stakeOwner address The address of the subject stake owner. /// @param _amount uint256 The migrated amount. function stakeMigration(address _stakeOwner, uint256 _amount) external; } // File: contracts/interfaces/IElections.sol pragma solidity 0.5.16; /// @title Elections contract interface interface IElections /* is IStakeChangeNotifier */ { // Election state change events event GuardianVotedUnready(address guardian); event GuardianVotedOut(address guardian); // Function calls event VoteUnreadyCasted(address voter, address subject); event VoteOutCasted(address voter, address subject); event StakeChanged(address addr, uint256 selfStake, uint256 delegated_stake, uint256 effective_stake); event GuardianStatusUpdated(address addr, bool readyToSync, bool readyForCommittee); // Governance event VoteUnreadyTimeoutSecondsChanged(uint32 newValue, uint32 oldValue); event MinSelfStakePercentMilleChanged(uint32 newValue, uint32 oldValue); event VoteOutPercentageThresholdChanged(uint8 newValue, uint8 oldValue); event VoteUnreadyPercentageThresholdChanged(uint8 newValue, uint8 oldValue); /* * External methods */ /// @dev Called by a guardian as part of the automatic vote-out flow function voteUnready(address subject_addr) external; /// @dev casts a voteOut vote by the sender to the given address function voteOut(address subjectAddr) external; /// @dev Called by a guardian when ready to start syncing with other nodes function readyToSync() external; /// @dev Called by a guardian when ready to join the committee, typically after syncing is complete or after being voted out function readyForCommittee() external; /* * Methods restricted to other Orbs contracts */ /// @dev Called by: delegation contract /// Notifies a delegated stake change event /// total_delegated_stake = 0 if addr delegates to another guardian function delegatedStakeChange(address addr, uint256 selfStake, uint256 delegatedStake, uint256 totalDelegatedStake) external /* onlyDelegationContract */; /// @dev Called by: guardian registration contract /// Notifies a new guardian was registered function guardianRegistered(address addr) external /* onlyGuardiansRegistrationContract */; /// @dev Called by: guardian registration contract /// Notifies a new guardian was unregistered function guardianUnregistered(address addr) external /* onlyGuardiansRegistrationContract */; /// @dev Called by: guardian registration contract /// Notifies on a guardian certification change function guardianCertificationChanged(address addr, bool isCertified) external /* onlyCertificationContract */; /* * Governance */ /// @dev Updates the address of the contract registry function setContractRegistry(IContractRegistry _contractRegistry) external /* onlyMigrationOwner */; function setVoteUnreadyTimeoutSeconds(uint32 voteUnreadyTimeoutSeconds) external /* onlyFunctionalOwner onlyWhenActive */; function setMinSelfStakePercentMille(uint32 minSelfStakePercentMille) external /* onlyFunctionalOwner onlyWhenActive */; function setVoteOutPercentageThreshold(uint8 voteUnreadyPercentageThreshold) external /* onlyFunctionalOwner onlyWhenActive */; function setVoteUnreadyPercentageThreshold(uint8 voteUnreadyPercentageThreshold) external /* onlyFunctionalOwner onlyWhenActive */; function getSettings() external view returns ( uint32 voteUnreadyTimeoutSeconds, uint32 minSelfStakePercentMille, uint8 voteUnreadyPercentageThreshold, uint8 voteOutPercentageThreshold ); } // File: contracts/spec_interfaces/IGuardiansRegistration.sol pragma solidity 0.5.16; /// @title Elections contract interface interface IGuardiansRegistration { event GuardianRegistered(address addr); event GuardianDataUpdated(address addr, bytes4 ip, address orbsAddr, string name, string website, string contact); event GuardianUnregistered(address addr); event GuardianMetadataChanged(address addr, string key, string newValue, string oldValue); /* * External methods */ /// @dev Called by a participant who wishes to register as a guardian function registerGuardian(bytes4 ip, address orbsAddr, string calldata name, string calldata website, string calldata contact) external; /// @dev Called by a participant who wishes to update its propertires function updateGuardian(bytes4 ip, address orbsAddr, string calldata name, string calldata website, string calldata contact) external; /// @dev Called by a participant who wishes to update its IP address (can be call by both main and Orbs addresses) function updateGuardianIp(bytes4 ip) external /* onlyWhenActive */; /// @dev Called by a participant to update additional guardian metadata properties. function setMetadata(string calldata key, string calldata value) external; /// @dev Called by a participant to get additional guardian metadata properties. function getMetadata(address addr, string calldata key) external view returns (string memory); /// @dev Called by a participant who wishes to unregister function unregisterGuardian() external; /// @dev Returns a guardian's data /// Used also by the Election contract function getGuardianData(address addr) external view returns (bytes4 ip, address orbsAddr, string memory name, string memory website, string memory contact, uint registration_time, uint last_update_time); /// @dev Returns the Orbs addresses of a list of guardians /// Used also by the committee contract function getGuardiansOrbsAddress(address[] calldata addrs) external view returns (address[] memory orbsAddrs); /// @dev Returns a guardian's ip /// Used also by the Election contract function getGuardianIp(address addr) external view returns (bytes4 ip); /// @dev Returns guardian ips function getGuardianIps(address[] calldata addr) external view returns (bytes4[] memory ips); /// @dev Returns true if the given address is of a registered guardian /// Used also by the Election contract function isRegistered(address addr) external view returns (bool); /* * Methods restricted to other Orbs contracts */ /// @dev Translates a list guardians Ethereum addresses to Orbs addresses /// Used by the Election contract function getOrbsAddresses(address[] calldata ethereumAddrs) external view returns (address[] memory orbsAddr); /// @dev Translates a list guardians Orbs addresses to Ethereum addresses /// Used by the Election contract function getEthereumAddresses(address[] calldata orbsAddrs) external view returns (address[] memory ethereumAddr); /// @dev Resolves the ethereum address for a guardian, given an Ethereum/Orbs address function resolveGuardianAddress(address ethereumOrOrbsAddress) external view returns (address mainAddress); } // File: contracts/spec_interfaces/ISubscriptions.sol pragma solidity 0.5.16; /// @title Subscriptions contract interface interface ISubscriptions { event SubscriptionChanged(uint256 vcid, uint256 genRefTime, uint256 expiresAt, string tier, string deploymentSubset); event Payment(uint256 vcid, address by, uint256 amount, string tier, uint256 rate); event VcConfigRecordChanged(uint256 vcid, string key, string value); event SubscriberAdded(address subscriber); event VcCreated(uint256 vcid, address owner); // TODO what about isCertified, deploymentSubset? event VcOwnerChanged(uint256 vcid, address previousOwner, address newOwner); /* * Methods restricted to other Orbs contracts */ /// @dev Called by: authorized subscriber (plan) contracts /// Creates a new VC function createVC(string calldata tier, uint256 rate, uint256 amount, address owner, bool isCertified, string calldata deploymentSubset) external returns (uint, uint); /// @dev Called by: authorized subscriber (plan) contracts /// Extends the subscription of an existing VC. function extendSubscription(uint256 vcid, uint256 amount, address payer) external; /// @dev called by VC owner to set a VC config record. Emits a VcConfigRecordChanged event. function setVcConfigRecord(uint256 vcid, string calldata key, string calldata value) external /* onlyVcOwner */; /// @dev returns the value of a VC config record function getVcConfigRecord(uint256 vcid, string calldata key) external view returns (string memory); /// @dev Transfers VC ownership to a new owner (can only be called by the current owner) function setVcOwner(uint256 vcid, address owner) external /* onlyVcOwner */; /// @dev Returns the genesis ref time delay function getGenesisRefTimeDelay() external view returns (uint256); /* * Governance methods */ /// @dev Called by the owner to authorize a subscriber (plan) function addSubscriber(address addr) external /* onlyFunctionalOwner */; /// @dev Called by the owner to set the genesis ref time delay function setGenesisRefTimeDelay(uint256 newGenesisRefTimeDelay) external /* onlyFunctionalOwner */; /// @dev Updates the address of the contract registry function setContractRegistry(IContractRegistry _contractRegistry) external /* onlyMigrationOwner */; } // File: contracts/spec_interfaces/IDelegation.sol pragma solidity 0.5.16; /// @title Elections contract interface interface IDelegations /* is IStakeChangeNotifier */ { // Delegation state change events event DelegatedStakeChanged(address indexed addr, uint256 selfDelegatedStake, uint256 delegatedStake, address[] delegators, uint256[] delegatorTotalStakes); // Function calls event Delegated(address indexed from, address indexed to); /* * External methods */ /// @dev Stake delegation function delegate(address to) external /* onlyWhenActive */; function refreshStakeNotification(address addr) external /* onlyWhenActive */; /* * Governance */ /// @dev Updates the address calldata of the contract registry function setContractRegistry(IContractRegistry _contractRegistry) external /* onlyMigrationOwner */; function importDelegations(address[] calldata from, address[] calldata to, bool notifyElections) external /* onlyMigrationOwner onlyDuringDelegationImport */; function finalizeDelegationImport() external /* onlyMigrationOwner onlyDuringDelegationImport */; event DelegationsImported(address[] from, address[] to, bool notifiedElections); event DelegationImportFinalized(); /* * Getters */ function getDelegatedStakes(address addr) external view returns (uint256); function getSelfDelegatedStake(address addr) external view returns (uint256); function getDelegation(address addr) external view returns (address); function getTotalDelegatedStake() external view returns (uint256) ; } // 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: contracts/IMigratableStakingContract.sol pragma solidity 0.5.16; /// @title An interface for staking contracts which support stake migration. interface IMigratableStakingContract { /// @dev Returns the address of the underlying staked token. /// @return IERC20 The address of the token. function getToken() external view returns (IERC20); /// @dev Stakes ORBS tokens on behalf of msg.sender. This method assumes that the user has already approved at least /// the required amount using ERC20 approve. /// @param _stakeOwner address The specified stake owner. /// @param _amount uint256 The number of tokens to stake. function acceptMigration(address _stakeOwner, uint256 _amount) external; event AcceptedMigration(address indexed stakeOwner, uint256 amount, uint256 totalStakedAmount); } // File: contracts/IStakingContract.sol pragma solidity 0.5.16; /// @title An interface for staking contracts. interface IStakingContract { /// @dev Stakes ORBS tokens on behalf of msg.sender. This method assumes that the user has already approved at least /// the required amount using ERC20 approve. /// @param _amount uint256 The amount of tokens to stake. function stake(uint256 _amount) external; /// @dev Unstakes ORBS tokens from msg.sender. If successful, this will start the cooldown period, after which /// msg.sender would be able to withdraw all of his tokens. /// @param _amount uint256 The amount of tokens to unstake. function unstake(uint256 _amount) external; /// @dev Requests to withdraw all of staked ORBS tokens back to msg.sender. Stake owners can withdraw their ORBS /// tokens only after previously unstaking them and after the cooldown period has passed (unless the contract was /// requested to release all stakes). function withdraw() external; /// @dev Restakes unstaked ORBS tokens (in or after cooldown) for msg.sender. function restake() external; /// @dev Distributes staking rewards to a list of addresses by directly adding rewards to their stakes. This method /// assumes that the user has already approved at least the required amount using ERC20 approve. Since this is a /// convenience method, we aren't concerned about reaching block gas limit by using large lists. We assume that /// callers will be able to properly batch/paginate their requests. /// @param _totalAmount uint256 The total amount of rewards to distributes. /// @param _stakeOwners address[] The addresses of the stake owners. /// @param _amounts uint256[] The amounts of the rewards. function distributeRewards(uint256 _totalAmount, address[] calldata _stakeOwners, uint256[] calldata _amounts) external; /// @dev Returns the stake of the specified stake owner (excluding unstaked tokens). /// @param _stakeOwner address The address to check. /// @return uint256 The total stake. function getStakeBalanceOf(address _stakeOwner) external view returns (uint256); /// @dev Returns the total amount staked tokens (excluding unstaked tokens). /// @return uint256 The total staked tokens of all stake owners. function getTotalStakedTokens() external view returns (uint256); /// @dev Returns the time that the cooldown period ends (or ended) and the amount of tokens to be released. /// @param _stakeOwner address The address to check. /// @return cooldownAmount uint256 The total tokens in cooldown. /// @return cooldownEndTime uint256 The time when the cooldown period ends (in seconds). function getUnstakeStatus(address _stakeOwner) external view returns (uint256 cooldownAmount, uint256 cooldownEndTime); /// @dev Migrates the stake of msg.sender from this staking contract to a new approved staking contract. /// @param _newStakingContract IMigratableStakingContract The new staking contract which supports stake migration. /// @param _amount uint256 The amount of tokens to migrate. function migrateStakedTokens(IMigratableStakingContract _newStakingContract, uint256 _amount) external; event Staked(address indexed stakeOwner, uint256 amount, uint256 totalStakedAmount); event Unstaked(address indexed stakeOwner, uint256 amount, uint256 totalStakedAmount); event Withdrew(address indexed stakeOwner, uint256 amount, uint256 totalStakedAmount); event Restaked(address indexed stakeOwner, uint256 amount, uint256 totalStakedAmount); event MigratedStake(address indexed stakeOwner, uint256 amount, uint256 totalStakedAmount); } // File: contracts/interfaces/IRewards.sol pragma solidity 0.5.16; /// @title Rewards contract interface interface IRewards { function assignRewards() external; function assignRewardsToCommittee(address[] calldata generalCommittee, uint256[] calldata generalCommitteeWeights, bool[] calldata certification) external /* onlyCommitteeContract */; // staking event StakingRewardsDistributed(address indexed distributer, uint256 fromBlock, uint256 toBlock, uint split, uint txIndex, address[] to, uint256[] amounts); event StakingRewardsAssigned(address[] assignees, uint256[] amounts); // todo balance? event StakingRewardsAddedToPool(uint256 added, uint256 total); event MaxDelegatorsStakingRewardsChanged(uint32 maxDelegatorsStakingRewardsPercentMille); /// @return Returns the currently unclaimed orbs token reward balance of the given address. function getStakingRewardBalance(address addr) external view returns (uint256 balance); /// @dev Distributes msg.sender's orbs token rewards to a list of addresses, by transferring directly into the staking contract. /// @dev `to[0]` must be the sender's main address /// @dev Total delegators reward (`to[1:n]`) must be less then maxDelegatorsStakingRewardsPercentMille of total amount function distributeOrbsTokenStakingRewards(uint256 totalAmount, uint256 fromBlock, uint256 toBlock, uint split, uint txIndex, address[] calldata to, uint256[] calldata amounts) external; /// @dev Transfers the given amount of orbs tokens form the sender to this contract an update the pool. function topUpStakingRewardsPool(uint256 amount) external; /* * Reward-governor methods */ /// @dev Assigns rewards and sets a new monthly rate for the pro-rata pool. function setAnnualStakingRewardsRate(uint256 annual_rate_in_percent_mille, uint256 annual_cap) external /* onlyFunctionalOwner */; // fees event FeesAssigned(uint256 generalGuardianAmount, uint256 certifiedGuardianAmount); event FeesWithdrawn(address guardian, uint256 amount); event FeesWithdrawnFromBucket(uint256 bucketId, uint256 withdrawn, uint256 total, bool isCertified); event FeesAddedToBucket(uint256 bucketId, uint256 added, uint256 total, bool isCertified); /* * External methods */ /// @return Returns the currently unclaimed orbs token reward balance of the given address. function getFeeBalance(address addr) external view returns (uint256 balance); /// @dev Transfer all of msg.sender's outstanding balance to their account function withdrawFeeFunds() external; /// @dev Called by: subscriptions contract /// Top-ups the certification fee pool with the given amount at the given rate (typically called by the subscriptions contract) function fillCertificationFeeBuckets(uint256 amount, uint256 monthlyRate, uint256 fromTimestamp) external; /// @dev Called by: subscriptions contract /// Top-ups the general fee pool with the given amount at the given rate (typically called by the subscriptions contract) function fillGeneralFeeBuckets(uint256 amount, uint256 monthlyRate, uint256 fromTimestamp) external; function getTotalBalances() external view returns (uint256 feesTotalBalance, uint256 stakingRewardsTotalBalance, uint256 bootstrapRewardsTotalBalance); // bootstrap event BootstrapRewardsAssigned(uint256 generalGuardianAmount, uint256 certifiedGuardianAmount); event BootstrapAddedToPool(uint256 added, uint256 total); event BootstrapRewardsWithdrawn(address guardian, uint256 amount); /* * External methods */ /// @return Returns the currently unclaimed bootstrap balance of the given address. function getBootstrapBalance(address addr) external view returns (uint256 balance); /// @dev Transfer all of msg.sender's outstanding balance to their account function withdrawBootstrapFunds() external; /// @return The timestamp of the last reward assignment. function getLastRewardAssignmentTime() external view returns (uint256 time); /// @dev Transfers the given amount of bootstrap tokens form the sender to this contract and update the pool. /// Assumes the tokens were approved for transfer function topUpBootstrapPool(uint256 amount) external; /* * Reward-governor methods */ /// @dev Assigns rewards and sets a new monthly rate for the geenral commitee bootstrap. function setGeneralCommitteeAnnualBootstrap(uint256 annual_amount) external /* onlyFunctionalOwner */; /// @dev Assigns rewards and sets a new monthly rate for the certification commitee bootstrap. function setCertificationCommitteeAnnualBootstrap(uint256 annual_amount) external /* onlyFunctionalOwner */; event EmergencyWithdrawal(address addr); function emergencyWithdraw() external /* onlyMigrationManager */; /* * General governance */ /// @dev Updates the address of the contract registry function setContractRegistry(IContractRegistry _contractRegistry) external /* onlyMigrationOwner */; } // 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: contracts/WithClaimableMigrationOwnership.sol pragma solidity 0.5.16; /** * @title Claimable * @dev Extension for the Ownable contract, where the ownership needs to be claimed. * This allows the new owner to accept the transfer. */ contract WithClaimableMigrationOwnership is Context{ address private _migrationOwner; address pendingMigrationOwner; event MigrationOwnershipTransferred(address indexed previousMigrationOwner, address indexed newMigrationOwner); /** * @dev Initializes the contract setting the deployer as the initial migrationMigrationOwner. */ constructor () internal { address msgSender = _msgSender(); _migrationOwner = msgSender; emit MigrationOwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current migrationOwner. */ function migrationOwner() public view returns (address) { return _migrationOwner; } /** * @dev Throws if called by any account other than the migrationOwner. */ modifier onlyMigrationOwner() { require(isMigrationOwner(), "WithClaimableMigrationOwnership: caller is not the migrationOwner"); _; } /** * @dev Returns true if the caller is the current migrationOwner. */ function isMigrationOwner() public view returns (bool) { return _msgSender() == _migrationOwner; } /** * @dev Leaves the contract without migrationOwner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current migrationOwner. * * NOTE: Renouncing migrationOwnership will leave the contract without an migrationOwner, * thereby removing any functionality that is only available to the migrationOwner. */ function renounceMigrationOwnership() public onlyMigrationOwner { emit MigrationOwnershipTransferred(_migrationOwner, address(0)); _migrationOwner = address(0); } /** * @dev Transfers migrationOwnership of the contract to a new account (`newOwner`). */ function _transferMigrationOwnership(address newMigrationOwner) internal { require(newMigrationOwner != address(0), "MigrationOwner: new migrationOwner is the zero address"); emit MigrationOwnershipTransferred(_migrationOwner, newMigrationOwner); _migrationOwner = newMigrationOwner; } /** * @dev Modifier throws if called by any account other than the pendingOwner. */ modifier onlyPendingMigrationOwner() { require(msg.sender == pendingMigrationOwner, "Caller is not the pending migrationOwner"); _; } /** * @dev Allows the current migrationOwner to set the pendingOwner address. * @param newMigrationOwner The address to transfer migrationOwnership to. */ function transferMigrationOwnership(address newMigrationOwner) public onlyMigrationOwner { pendingMigrationOwner = newMigrationOwner; } /** * @dev Allows the pendingMigrationOwner address to finalize the transfer. */ function claimMigrationOwnership() external onlyPendingMigrationOwner { _transferMigrationOwnership(pendingMigrationOwner); pendingMigrationOwner = address(0); } } // File: contracts/Lockable.sol pragma solidity 0.5.16; /** * @title Claimable * @dev Extension for the Ownable contract, where the ownership needs to be claimed. * This allows the new owner to accept the transfer. */ contract Lockable is WithClaimableMigrationOwnership { bool public locked; event Locked(); event Unlocked(); function lock() external onlyMigrationOwner { locked = true; emit Locked(); } function unlock() external onlyMigrationOwner { locked = false; emit Unlocked(); } modifier onlyWhenActive() { require(!locked, "contract is locked for this operation"); _; } } // File: contracts/spec_interfaces/IProtocolWallet.sol pragma solidity 0.5.16; pragma solidity 0.5.16; /// @title Protocol Wallet interface interface IProtocolWallet { event FundsAddedToPool(uint256 added, uint256 total); event ClientSet(address client); event MaxAnnualRateSet(uint256 maxAnnualRate); event EmergencyWithdrawal(address addr); /// @dev Returns the address of the underlying staked token. /// @return IERC20 The address of the token. function getToken() external view returns (IERC20); /// @dev Returns the address of the underlying staked token. /// @return IERC20 The address of the token. function getBalance() external view returns (uint256 balance); /// @dev Transfers the given amount of orbs tokens form the sender to this contract an update the pool. function topUp(uint256 amount) external; /// @dev Withdraw from pool to a the sender's address, limited by the pool's MaxRate. /// A maximum of MaxRate x time period since the last Orbs transfer may be transferred out. /// Flow: /// PoolWallet.approveTransfer(amount); /// ERC20.transferFrom(PoolWallet, client, amount) function withdraw(uint256 amount) external; /* onlyClient */ /* Governance */ /// @dev Sets a new transfer rate for the Orbs pool. function setMaxAnnualRate(uint256 annual_rate) external; /* onlyMigrationManager */ /// @dev transfer the entire pool's balance to a new wallet. function emergencyWithdraw() external; /* onlyMigrationManager */ /// @dev sets the address of the new contract function setClient(address client) external; /* onlyFunctionalManager */ } // File: contracts/ContractRegistryAccessor.sol pragma solidity 0.5.16; contract ContractRegistryAccessor is WithClaimableMigrationOwnership { IContractRegistry contractRegistry; event ContractRegistryAddressUpdated(address addr); function setContractRegistry(IContractRegistry _contractRegistry) external onlyMigrationOwner { contractRegistry = _contractRegistry; emit ContractRegistryAddressUpdated(address(_contractRegistry)); } function getProtocolContract() public view returns (IProtocol) { return IProtocol(contractRegistry.get("protocol")); } function getRewardsContract() public view returns (IRewards) { return IRewards(contractRegistry.get("rewards")); } function getCommitteeContract() public view returns (ICommittee) { return ICommittee(contractRegistry.get("committee")); } function getElectionsContract() public view returns (IElections) { return IElections(contractRegistry.get("elections")); } function getDelegationsContract() public view returns (IDelegations) { return IDelegations(contractRegistry.get("delegations")); } function getGuardiansRegistrationContract() public view returns (IGuardiansRegistration) { return IGuardiansRegistration(contractRegistry.get("guardiansRegistration")); } function getCertificationContract() public view returns (ICertification) { return ICertification(contractRegistry.get("certification")); } function getStakingContract() public view returns (IStakingContract) { return IStakingContract(contractRegistry.get("staking")); } function getSubscriptionsContract() public view returns (ISubscriptions) { return ISubscriptions(contractRegistry.get("subscriptions")); } function getStakingRewardsWallet() public view returns (IProtocolWallet) { return IProtocolWallet(contractRegistry.get("stakingRewardsWallet")); } function getBootstrapRewardsWallet() public view returns (IProtocolWallet) { return IProtocolWallet(contractRegistry.get("bootstrapRewardsWallet")); } } // File: contracts/WithClaimableFunctionalOwnership.sol pragma solidity 0.5.16; /** * @title Claimable * @dev Extension for the Ownable contract, where the ownership needs to be claimed. * This allows the new owner to accept the transfer. */ contract WithClaimableFunctionalOwnership is Context{ address private _functionalOwner; address pendingFunctionalOwner; event FunctionalOwnershipTransferred(address indexed previousFunctionalOwner, address indexed newFunctionalOwner); /** * @dev Initializes the contract setting the deployer as the initial functionalFunctionalOwner. */ constructor () internal { address msgSender = _msgSender(); _functionalOwner = msgSender; emit FunctionalOwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current functionalOwner. */ function functionalOwner() public view returns (address) { return _functionalOwner; } /** * @dev Throws if called by any account other than the functionalOwner. */ modifier onlyFunctionalOwner() { require(isFunctionalOwner(), "WithClaimableFunctionalOwnership: caller is not the functionalOwner"); _; } /** * @dev Returns true if the caller is the current functionalOwner. */ function isFunctionalOwner() public view returns (bool) { return _msgSender() == _functionalOwner; } /** * @dev Leaves the contract without functionalOwner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current functionalOwner. * * NOTE: Renouncing functionalOwnership will leave the contract without an functionalOwner, * thereby removing any functionality that is only available to the functionalOwner. */ function renounceFunctionalOwnership() public onlyFunctionalOwner { emit FunctionalOwnershipTransferred(_functionalOwner, address(0)); _functionalOwner = address(0); } /** * @dev Transfers functionalOwnership of the contract to a new account (`newOwner`). */ function _transferFunctionalOwnership(address newFunctionalOwner) internal { require(newFunctionalOwner != address(0), "FunctionalOwner: new functionalOwner is the zero address"); emit FunctionalOwnershipTransferred(_functionalOwner, newFunctionalOwner); _functionalOwner = newFunctionalOwner; } /** * @dev Modifier throws if called by any account other than the pendingOwner. */ modifier onlyPendingFunctionalOwner() { require(msg.sender == pendingFunctionalOwner, "Caller is not the pending functionalOwner"); _; } /** * @dev Allows the current functionalOwner to set the pendingOwner address. * @param newFunctionalOwner The address to transfer functionalOwnership to. */ function transferFunctionalOwnership(address newFunctionalOwner) public onlyFunctionalOwner { pendingFunctionalOwner = newFunctionalOwner; } /** * @dev Allows the pendingFunctionalOwner address to finalize the transfer. */ function claimFunctionalOwnership() external onlyPendingFunctionalOwner { _transferFunctionalOwnership(pendingFunctionalOwner); pendingFunctionalOwner = address(0); } } // File: ../contracts/Certification.sol pragma solidity 0.5.16; contract Certification is ICertification, ContractRegistryAccessor, WithClaimableFunctionalOwnership, Lockable { mapping (address => bool) guardianCertification; /* * External methods */ function isGuardianCertified(address addr) external view returns (bool isCertified) { return guardianCertification[addr]; } function setGuardianCertification(address addr, bool isCertified) external onlyFunctionalOwner onlyWhenActive { guardianCertification[addr] = isCertified; emit GuardianCertificationUpdate(addr, isCertified); getElectionsContract().guardianCertificationChanged(addr, isCertified); } }
Leaves the contract without migrationOwner. It will not be possible to call `onlyOwner` functions anymore. Can only be called by the current migrationOwner. NOTE: Renouncing migrationOwnership will leave the contract without an migrationOwner, thereby removing any functionality that is only available to the migrationOwner./
function renounceMigrationOwnership() public onlyMigrationOwner { emit MigrationOwnershipTransferred(_migrationOwner, address(0)); _migrationOwner = address(0); }
947,802
./full_match/80001/0x6c24eaa45a3502807523BAD0A9f5389cBFe83927/sources/contracts/SonicaERC721Drop.sol
Valid who can change the Lazy Mint.
function _canLazyMint() internal view virtual override returns (bool) { return hasRole(DEFAULT_ADMIN_ROLE, msg.sender); }
843,093
pragma solidity ^0.5.0; import "openzeppelin-solidity/contracts/ownership/Ownable.sol"; import "openzeppelin-solidity/contracts/math/Math.sol"; import "./ICryptoArcadeGame.sol"; import "./RewardSplitter.sol"; /** * @title CryptoArcadeGame * @dev This contract represents the logic and data for each game on the platform. * It implements an public interface and the ownable pattern so most operations can only be executed * by the owner (the CryptoArcade contract) to reduce the attacking surface. * * There is a circuit breaker implemented that can only be operated by the owner * account, in case a serious issue is detected. */ contract CryptoArcadeGame is Ownable, ICryptoArcadeGame { event LogMatchPlayed( address indexed player, string gameName, uint256 score ); // The default match price uint256 public MATCH_PRICE; // A match can be in 2 states: NotPlayed (when purchased) and Played enum MatchStatus {NotPlayed, Played} // A game contains the player address, the status of the game and the score attained struct GameMatch { address player; MatchStatus status; uint256 score; } // The name of the game string private name; // The address of the game owner address private creator; // The game's top 10 players uint256[] private topScores; // The contract that contains the reward balance and the shares for each of the players that made it to the top 10 RewardSplitter private rewardShare; // Whether the contract is active or not bool private active; // The counter for the number of matches uint256 private numOfMatches; // The hashmap for all the matches purchased mapping(uint256 => GameMatch) private matches; // The hashmap for the IDs of all the matches that belong to a given player mapping(address => uint256[]) private playerAvailableMatches; // Restricts the function if the game is not active modifier isActiveGame() { require(active, "CryptoArcadeGame: The game is not active"); _; } // Requires the payment to be at least the match price modifier paidEnough() { require( msg.value >= MATCH_PRICE, "The amount paid is not sufficient to purchase the match" ); _; } // Returns ether paid in excess by the player modifier refundExcess() { _; uint256 paidInExcess = msg.value - MATCH_PRICE; if (paidInExcess > 0) { msg.sender.transfer(paidInExcess); } } /** * @dev Creates a new instance associated to the game creator address and sets * the price players will have to pay to play. * * @param _name The name of the game * @param _creator The account address of the game creator * @param _price The price per match */ constructor(string memory _name, address _creator, uint256 _price) public { name = _name; creator = _creator; topScores = new uint256[](10); numOfMatches = 0; rewardShare = new RewardSplitter(); active = true; MATCH_PRICE = _price * 1 wei; } /** * @dev Method that retrieves the price per match in wei * * @return The price per match in wei */ function getMatchPrice() public view returns (uint256) { return MATCH_PRICE; } /** * @dev This methods retrieves the state of the game. * The game can be deactivated without being removed, in case an issue is detected. * * @return True if active, false otherwise */ function isActive() external view returns (bool) { return active; } /** * @dev This methods retrieves the price per match in wei. * * @return The price per match in wei */ function gameMatchPrice() public view returns (uint256) { return MATCH_PRICE; } /** * @dev This method returns player's number of matches in NotPlayed status. * * @param _player The address of the player * @return The number of matches that are in NotPlayed status */ function getNumberOfAvailableMatches(address _player) public view returns (uint256) { uint256 totalAvailableMatches = 0; for (uint256 i = 0; i < playerAvailableMatches[_player].length; i++) { uint256 m = playerAvailableMatches[_player][i]; GameMatch memory matchData = matches[m]; if (matchData.status == MatchStatus.NotPlayed) { totalAvailableMatches++; } } return totalAvailableMatches; } /** * @dev This method purchases a match for a player. * It can only be called from the owner's arcade contract and returns any excess ether paid. * The paid ether is transferred to the contract that mamanges the rewards. * * @param _player The address of the player * @return The match ID of the match bought */ function purchaseMatch(address _player) external payable isActiveGame() paidEnough() refundExcess() onlyOwner() returns (uint256 matchId) { matchId = ++numOfMatches; matches[matchId] = GameMatch({ player: _player, status: MatchStatus.NotPlayed, score: 0 }); playerAvailableMatches[_player].push(matchId); address(rewardShare).transfer(MATCH_PRICE); } /** * @dev This methods deactivates the game, disabling most of its functionality. * The game can be deactivated without being destroyed, in case an issue is detected. * The method can only be invoked by the owner contract. * * @return The match ID of the match bought */ function deactivateGame() external onlyOwner() { active = false; } /** * @dev This methods activates the game, enabling most of its functionality. * The game can be deactivated without being destroyed, in case an issue is detected. * The method can only be invoked by the owner contract. * * @return The match ID of the match bought */ function activateGame() external onlyOwner() { active = true; } /** * @dev This method flags a match as played, which consumes it. * The status of the match becomes Played so its score can be associated to it. * * @param _player The address of the player * @return The match ID of the match played */ function playMatch(address _player) external isActiveGame() onlyOwner() returns (uint256) { uint256 matchId = 0; for (uint256 i = 0; i < playerAvailableMatches[_player].length; i++) { uint256 m = playerAvailableMatches[_player][i]; GameMatch storage matchData = matches[m]; if (matchData.status == MatchStatus.NotPlayed) { matchData.status = MatchStatus.Played; matchId = m; return matchId; } } return matchId; } /** * @dev This method stores the score of a match played, calculates whether it falls in * the top 10 in which case it also calculates and awards a number of shares to the player. * How many depends on the position achieved. * * The method emits a match played event. * @param _player The address of the player * @param _score The score attained * @return The number of shares produced by the score (zero if the score doesn't make it to the top 10) */ function matchPlayed(address _player, uint256 _score) external isActiveGame() onlyOwner() returns (uint256 shares) { uint256 matchId = 0; for (uint256 i = 0; i < playerAvailableMatches[_player].length; i++) { uint256 m = playerAvailableMatches[_player][i]; GameMatch memory matchData = matches[m]; if (matchData.status == MatchStatus.Played) { matchId = m; break; } } require( matchId != 0, "MatchPlayed: There are no matches played to log against" ); require( matches[matchId].player == _player, "MatchPlayed: The player did not purchase the match" ); matches[matchId].status = MatchStatus.Played; matches[matchId].score = _score; uint256 pos = insertNewScore(matchId); shares = rewardShare.addPayee(_player, pos); emit LogMatchPlayed(_player, name, _score); } /** * @dev Internal method that calculates the position on the ranking for a given score. * The insertion in the list is done in order. * * @param _matchId The match with the score * @return The position in the ranking that goes from 0 to 9. If the score doesn't make it to the list, 10 is returned. */ function insertNewScore(uint256 _matchId) internal returns (uint256) { uint256 newScore = matches[_matchId].score; uint256 pos = 10; for (uint256 i = 0; i < topScores.length; i++) { uint256 currentScore = matches[topScores[i]].score; if (newScore > currentScore) { pos = i; break; } } if (pos < topScores.length) { for (uint256 i = topScores.length - 1; i > pos; i--) { topScores[i] = topScores[i - 1]; } topScores[pos] = _matchId; } return pos; } /** * @dev Method that retrieves the top 10 ranking one piece of data at a time, * to avoid complex operations on-chain. * * @return The address of the entry in the top 10 'pos' position */ function getRecordEntryAddress(uint256 _pos) public view returns (address) { require(_pos < 10 && _pos >= 0, "The position must be between 0 and 9"); return matches[topScores[_pos]].player; } /** * @dev Method that retrieves the top 10 ranking one piece of data at a time, * to avoid complex operations on-chain. * * @return The score of the entry in the top 10 'pos' position */ function getRecordEntryScore(uint256 _pos) public view returns (uint256) { require(_pos < 10 && _pos >= 0, "The position must be between 0 and 9"); return matches[topScores[_pos]].score; } /** * @dev Method that returns the number of shares of a given player in the common game reward pot. * * @param _player The address of the player * @return The number of shares for the given player in the reward pot */ function playerBalance(address payable _player) external view returns (uint256) { return rewardShare.getAccountShares(_player); } /** * @dev Method that pays to the player the ether corresponding to the number of shares as a % representation on the total. * * @param _player The address of the player * @return The amount of ether in wei paid to the player */ function releaseReward(address payable _player) external returns (uint256 amount) { amount = rewardShare.release(_player); } /** * @dev The amount of Ether already released to a payee. * * @param _player The address of the player */ function getReleasedAmount(address _player) public view returns (uint256) { return rewardShare.getReleasedAmount(_player); } }
This methods deactivates the game, disabling most of its functionality. The game can be deactivated without being destroyed, in case an issue is detected. The method can only be invoked by the owner contract. return The match ID of the match bought/
function deactivateGame() external onlyOwner() { active = false; }
1,001,464
./partial_match/1/0x1E7407b5f0c3ec55cFEEb0B19Dfb006e32F8EBB0/sources/TOW3.sol
Internal function to invoke {IERC721Receiver-onERC721Received} on a target address. The call is not executed if the target address is not a contract. from address representing the previous owner of the given token ID to target address that will receive the tokens tokenId uint256 ID of the token to be transferred data bytes optional data to send along with the call return bool whether the call correctly returned the expected magic value/ @solidity memory-safe-assembly
function _checkOnERC721Received( address from, address to, uint256 tokenId, bytes memory data ) private returns (bool) { if (to.isContract()) { try IERC721Receiver(to).onERC721Received(msg.sender, from, tokenId, data) returns (bytes4 retval) { return retval == IERC721Receiver.onERC721Received.selector; if (reason.length == 0) { revert("ERC721: transfer to non ERC721Receiver implementer"); assembly { revert(add(32, reason), mload(reason)) } } } return true; } }
2,838,420
./full_match/80001/0x8B89359a48C153994d2A6BF878b148f151d2A0c4/sources/contracts/market/MarketMatching.sol
match offers with taker offer, and execute token transactions Init offer history There is at least one offer stored for token pair If "buy" is executed within the while loop, the sender becomes taker This can happen with both market and limit order best[address][address] gets the best maker ID Ugly hack to work around rounding errors. Based on the idea that the furthest the amounts can stray from their "true" values is 1. Ergo the worst case has tPayAmt and mPayAmt at +1 away from their "correct" values and mBuyAmt and tBuyAmt at -1. Since (c - 1) (d - 1) > (a + 1) (b + 1) is equivalent to c d > a b + a + b + c + d, we write... offerType = 0 -> Limit Order Market order never puts a new offer Market order acts as Immediate-or-Cancel order, and fills as much as possible, the remaining amount is cancelled if there is any Limit orders are given with an ID Below makes the sender a maker as it sets a new offernew offer should be createdinsert offer into the sorted list
function _matcho( uint8 offerType ) internal returns (uint256 id) { uint256 tPayAmtInit = tPayAmt; OfferInfoHistory memory infoHistory; infoHistory.payAmt = tPayAmt; infoHistory.payGem = tPayGem; infoHistory.buyAmt = tBuyAmt; infoHistory.buyGem = tBuyGem; infoHistory.owner = msg.sender; infoHistory.id = uint256(0); infoHistory.cancelled = false; infoHistory.filled = false; infoHistory.filledPayAmt = uint256(0); infoHistory.filledBuyAmt = uint256(0); infoHistory.offerType = offerType; while (best[address(tBuyGem)][address(tPayGem)] > 0) { mBuyAmt = offers[best[address(tBuyGem)][address(tPayGem)]].buyAmt; mPayAmt = offers[best[address(tBuyGem)][address(tPayGem)]].payAmt; if ( mul(mBuyAmt, tBuyAmt) > mul(tPayAmt, mPayAmt) + (rounding ? mBuyAmt + tBuyAmt + tPayAmt + mPayAmt : 0) ) { break; } tBuyAmtOld = tBuyAmt; tBuyAmt = sub(tBuyAmt, min(mPayAmt, tBuyAmt)); tPayAmt = mul(tBuyAmt, tPayAmt) / tBuyAmtOld; infoHistory.filledPayAmt = sub(tPayAmtInit, tPayAmt); infoHistory.filledBuyAmt = add(infoHistory.filledBuyAmt, min(mPayAmt, tBuyAmt)); if (tPayAmt == 0 || tBuyAmt == 0) { infoHistory.filled = true; break; } } if (offerType == uint8(0)) { if (tBuyAmt > 0 && tPayAmt > 0 && tPayAmt >= dust[address(tPayGem)]) { id = _offer(tPayAmt, tPayGem, tBuyAmt, tBuyGem, uint8(0)); _sort(id, pos); offersHistoryIndices[msg.sender][id] = _nextIndex(); infoHistory.id = id; offersHistory[msg.sender].push(infoHistory); } offersHistory[msg.sender].push(infoHistory); } }
9,473,676
/* file: ERC20.sol ver: 0.4.4-o0ragman0o updated:26-July-2017 author: Darryl Morris email: o0ragman0o AT gmail.com An ERC20 compliant token with reentry protection and safe math. This software 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 MIT Licence for further details. <https://opensource.org/licenses/MIT>. Release Notes ------------- 0.4.4-o0ragman0o * removed state from interface * added abstract functions of public state to interface. * included state into contract implimentation */ pragma solidity ^0.4.10; import "https://github.com/o0ragman0o/ReentryProtected/ReentryProtected.sol"; // ERC20 Standard Token Interface with safe maths and reentry protection contract ERC20Interface { /* Structs */ /* State Valiables */ /* Events */ // Triggered when tokens are transferred. event Transfer( address indexed _from, address indexed _to, uint256 _value); // Triggered whenever approve(address _spender, uint256 _value) is called. event Approval( address indexed _owner, address indexed _spender, uint256 _value); /* Modifiers */ /* Function Abstracts */ /// @return The total supply of tokens function totalSupply() public constant returns (uint); // /// @return The trading symbol; function symbol() public constant returns (string); /// @param _addr The address of a token holder /// @return The amount of tokens held by `_addr` function balanceOf(address _addr) public constant returns (uint); /// @param _owner The address of a token holder /// @param _spender the address of a third-party /// @return The amount of tokens the `_spender` is allowed to transfer function allowance(address _owner, address _spender) public constant returns (uint); /// @notice Send `_amount` of tokens from `msg.sender` to `_to` /// @param _to The address of the recipient /// @param _amount The amount of tokens to transfer function transfer(address _to, uint256 _amount) public returns (bool); /// @notice Send `_amount` of tokens from `_from` to `_to` on the condition /// it is approved by `_from` /// @param _from The address of the sender /// @param _to The address of the recipient /// @param _amount The amount of tokens to transfer function transferFrom(address _from, address _to, uint256 _amount) public returns (bool); /// @notice `msg.sender` approves `_spender` to spend `_amount` tokens on /// its behalf /// @param _spender The address of the approved spender /// @param _amount The amount of tokens to transfer function approve(address _spender, uint256 _amount) public returns (bool); } contract ERC20Token is ReentryProtected, ERC20Interface { /* Constants */ bytes32 constant public VERSION = "ERC20 0.4.4-o0ragman0o"; /* State */ // The Total supply of tokens uint totSupply; /// @return Token symbol string sym; // Token ownership mapping mapping (address => uint) balance; // Allowances mapping mapping (address => mapping (address => uint)) allowed; /* Funtions Public */ function ERC20Token(uint _supply, string _symbol) { // Supply limited to 2^128 rather than 2^256 to prevent potential // multiplication overflow require(_supply < 2**128); totSupply = _supply; sym = _symbol; balance[msg.sender] = totSupply; } function symbol() public constant returns (string) { return sym; } // Using an explicit getter allows for function overloading function totalSupply() public constant returns (uint) { return totSupply; } // Using an explicit getter allows for function overloading function balanceOf(address _addr) public constant returns (uint) { return balance[_addr]; } // Using an explicit getter allows for function overloading function allowance(address _owner, address _spender) public constant returns (uint remaining_) { return allowed[_owner][_spender]; } // Send _value amount of tokens to address _to // Reentry protection prevents attacks upon the state function transfer(address _to, uint256 _value) public noReentry returns (bool) { return xfer(msg.sender, _to, _value); } // Send _value amount of tokens from address _from to address _to // Reentry protection prevents attacks upon the state function transferFrom(address _from, address _to, uint256 _value) public noReentry returns (bool) { require(_value <= allowed[_from][msg.sender]); allowed[_from][msg.sender] -= _value; return xfer(_from, _to, _value); } // Process a transfer internally. function xfer(address _from, address _to, uint _value) internal returns (bool) { require(_value > 0 && _value <= balance[_from]); balance[_from] -= _value; balance[_to] += _value; Transfer(_from, _to, _value); return true; } // Approves a third-party spender // Reentry protection prevents attacks upon the state function approve(address _spender, uint256 _value) public noReentry returns (bool) { require(balance[msg.sender] != 0); allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); return true; } }
Using an explicit getter allows for function overloading
function allowance(address _owner, address _spender) public constant returns (uint remaining_) { return allowed[_owner][_spender]; }
6,472,261
pragma solidity ^0.4.24; import "./Asset.sol"; import "./Events.sol"; contract StakeInterface { function calculateStakeTokens(uint _itemCost) public returns (uint _stakeToken); } contract TokenInterface { function transferFrom(address _from, address _to, uint _value) public returns (bool); function balanceOf(address _wallet) public returns (uint); } contract ArbitratorInterface { function createArbitration(string _reason, address _requesdedBy) public returns (address); } contract SplytTracker is Events { uint public version; string public ownedBy; address public satToken; address public arbitrator; address public stake; mapping (address => bytes12) assetIdByAddress; mapping (bytes32 => address) addressByassetId; // Events to notify other market places of something // Success events gets triggered when a listing is created or a listing is fully funded // _code: 1 = listing created, 2 = contributions came in // _assetAddress: the asset address for which the code happened // event Success(uint _code, address _assetAddress); // event Error(uint _code, string _message); constructor(uint _version, string _ownedBy, address _satToken, address _arbitratorAddr, address _stake) public { version = _version; ownedBy = _ownedBy; satToken = _satToken; arbitrator = _arbitratorAddr; stake = _stake; } // Setter functions. creates new asset contract given the parameters function createAsset( bytes12 _assetId, uint _term, address _seller, string _title, uint _totalCost, uint _exiprationDate, address _mpAddress, uint _mpAmount) public { StakeInterface stakeContract = StakeInterface(stake); uint sellersBal = getBalance(_seller); uint stakeTokens = stakeContract.calculateStakeTokens(_totalCost); if(stakeTokens > sellersBal) { revert(); } address newAsset = new Asset(_assetId, _term, _seller, _title, _totalCost, _exiprationDate, _mpAddress, _mpAmount, stakeTokens); assetIdByAddress[newAsset] = _assetId; addressByassetId[_assetId] = newAsset; internalContribute(_seller, newAsset, stakeTokens); emit Success(1, newAsset); } // Getter function. returns asset contract address given asset UUID function getAddressById(bytes12 _listingId) public view returns (address) { return addressByassetId[_listingId]; } // Getter function. returns asset's UUID given asset's contract address function getIdByAddress(address _contractAddr) public view returns (bytes12) { return assetIdByAddress[_contractAddr]; } // User for single buy to transfer tokens from buyer address to seller address function internalContribute(address _from, address _to, uint _amount) public returns (bool) { if(assetIdByAddress[msg.sender] == "0x0") return false; TokenInterface tokenContract = TokenInterface(satToken); bool result = tokenContract.transferFrom(_from, _to, _amount); if(result == true) emit Success(2, msg.sender); else emit Error(2, msg.sender, "Could not make transfer happen"); return result; } // Used for fractional ownership to transfer tokens from user address to listing address function internalRedeemFunds(address _listingAddress, address _seller, uint _amount) public returns (bool) { if(assetIdByAddress[msg.sender] == "0x0") { emit Error(1, msg.sender, "Asset contract not in splyt tracker"); return false; } TokenInterface tokenContract = TokenInterface(satToken); bool result = tokenContract.transferFrom(_listingAddress, _seller, _amount); if(result == true) emit Success(2, msg.sender); else emit Error(2, msg.sender, "Could not make transfer happen"); return result; } function internalArbitrate(string _reason, address _requestedBy) public returns (address) { ArbitratorInterface arbitratorContract = ArbitratorInterface(arbitrator); address arbCont = arbitratorContract.createArbitration(_reason, _requestedBy); emit Success(3, _requestedBy); return arbCont; } // Getter function. returns token contract address function getBalance(address _wallet) public returns (uint) { TokenInterface tokenContract = TokenInterface(satToken); return tokenContract.balanceOf(_wallet); } }
Getter function. returns asset contract address given asset UUID
function getAddressById(bytes12 _listingId) public view returns (address) { return addressByassetId[_listingId]; }
2,565,410
./full_match/56/0xD803719B1a6Aac1dcB2c815d987f0CB5E8f4cCAf/sources/happy.sol
disable limits (can't be enabled again)
function disableLimits() external onlyAdmin { require(vars.limitsEnabled); vars.limitsEnabled = false; emit LimitsDisabled(); }
3,238,596
pragma solidity 0.4.24; contract IMigrationContract { function migrate(address _addr, uint256 _tokens, uint256 _totaltokens) public returns (bool success); } /* taking ideas from FirstBlood token */ contract SafeMath { function safeAdd(uint256 x, uint256 y) internal pure returns(uint256) { uint256 z = x + y; assert((z >= x) && (z >= y)); return z; } function safeSubtract(uint256 x, uint256 y) internal pure returns(uint256) { assert(x >= y); uint256 z = x - y; return z; } function safeMult(uint256 x, uint256 y) internal pure returns(uint256) { uint256 z = x * y; assert((x == 0)||(z/x == y)); return z; } function safeDiv(uint256 x, uint256 y) internal pure returns(uint256) { uint256 z = x / y; return z; } } /** * @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 ethFundDeposit; event OwnershipTransferred(address indexed ethFundDeposit, address indexed _newFundDeposit); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ constructor() public { ethFundDeposit = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == ethFundDeposit); _; } /** * @dev Allows the current owner to transfer control of the contract to a _newFundDeposit. * @param _newFundDeposit The address to transfer ownership to. */ function transferOwnership(address _newFundDeposit) public onlyOwner { require(_newFundDeposit != address(0)); emit OwnershipTransferred(ethFundDeposit, _newFundDeposit); ethFundDeposit = _newFundDeposit; } } /** * @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 allow actions only when the contract IS paused */ modifier whenNotPaused() { require(!paused); _; } /** * @dev modifier to allow actions only when the contract IS NOT paused */ modifier whenPaused { require(paused); _; } /** * @dev called by the owner to pause, triggers stopped state */ function pause() public onlyOwner whenNotPaused { paused = true; emit Pause(); } /** * @dev called by the owner to unpause, returns to normal state */ function unpause() public onlyOwner whenPaused { paused = false; emit Unpause(); } } /** * @title Controllable * @dev Base contract which allows children to control the address */ contract controllable is Ownable { event AddToBlacklist(address _addr); event DeleteFromBlacklist(address _addr); // controllable variable mapping (address => bool) internal blacklist; // black list /** * @dev called by the owner to AddToBlacklist */ function addtoblacklist(address _addr) public onlyOwner { blacklist[_addr] = true; emit AddToBlacklist(_addr); } /** * @dev called by the owner to unpDeleteFromBlacklistause */ function deletefromblacklist(address _addr) public onlyOwner { blacklist[_addr] = false; emit DeleteFromBlacklist(_addr); } /** * @dev called by the owner to check the blacklist address */ function isBlacklist(address _addr) public view returns(bool) { return blacklist[_addr]; } } /** * @title Lockable * @dev Base contract which allows children to control the token release mechanism */ contract Lockable is Ownable, SafeMath { // parameters mapping (address => uint256) balances; mapping (address => uint256) totalbalances; uint256 public totalreleaseblances; mapping (address => mapping (uint256 => uint256)) userbalances; // address , order ,balances amount mapping (address => mapping (uint256 => uint256)) userRelease; // address , order ,release amount mapping (address => mapping (uint256 => uint256)) isRelease; // already release period mapping (address => mapping (uint256 => uint256)) userChargeTime; // address , order ,charge time mapping (address => uint256) userChargeCount; // user total charge times mapping (address => mapping (uint256 => uint256)) lastCliff; // address , order ,last cliff time // userbalances each time segmentation mapping (address => mapping (uint256 => mapping (uint256 => uint256))) userbalancesSegmentation; // address , order ,balances amount uint256 internal duration = 30*15 days; uint256 internal cliff = 90 days; // event event userlockmechanism(address _addr,uint256 _amount,uint256 _timestamp); event userrelease(address _addr, uint256 _times, uint256 _amount); modifier onlySelfOrOwner(address _addr) { require(msg.sender == _addr || msg.sender == ethFundDeposit); _; } function LockMechanism ( address _addr, uint256 _value ) internal { require(_addr != address(0)); require(_value != 0); // count userChargeCount[_addr] = safeAdd(userChargeCount[_addr],1); uint256 _times = userChargeCount[_addr]; // time userChargeTime[_addr][_times] = ShowTime(); // balances userbalances[_addr][_times] = _value; initsegmentation(_addr,userChargeCount[_addr],_value); totalbalances[_addr] = safeAdd(totalbalances[_addr],_value); isRelease[_addr][_times] = 0; emit userlockmechanism(_addr,_value,ShowTime()); } // init segmentation function initsegmentation(address _addr,uint256 _times,uint256 _value) internal { for (uint8 i = 1 ; i <= 5 ; i++ ) { userbalancesSegmentation[_addr][_times][i] = safeDiv(_value,5); } } // calculate period function CalcPeriod(address _addr, uint256 _times) public view returns (uint256) { uint256 userstart = userChargeTime[_addr][_times]; if (ShowTime() >= safeAdd(userstart,duration)) { return 5; } uint256 timedifference = safeSubtract(ShowTime(),userstart); uint256 period = 0; for (uint8 i = 1 ; i <= 5 ; i++ ) { if (timedifference >= cliff) { timedifference = safeSubtract(timedifference,cliff); period += 1; } } return period; } // ReleasableAmount() looking for the current releasable amount function ReleasableAmount(address _addr, uint256 _times) public view returns (uint256) { require(_addr != address(0)); uint256 period = CalcPeriod(_addr,_times); if (safeSubtract(period,isRelease[_addr][_times]) > 0){ uint256 amount = 0; for (uint256 i = safeAdd(isRelease[_addr][_times],1) ; i <= period ; i++ ) { amount = safeAdd(amount,userbalancesSegmentation[_addr][_times][i]); } return amount; } else { return 0; } } // release() release the current releasable amount function release(address _addr, uint256 _times) external onlySelfOrOwner(_addr) { uint256 amount = ReleasableAmount(_addr,_times); require(amount > 0); userRelease[_addr][_times] = safeAdd(userRelease[_addr][_times],amount); balances[_addr] = safeAdd(balances[_addr],amount); lastCliff[_addr][_times] = ShowTime(); isRelease[_addr][_times] = CalcPeriod(_addr,_times); totalreleaseblances = safeAdd(totalreleaseblances,amount); emit userrelease(_addr, _times, amount); } // ShowTime function ShowTime() internal view returns (uint256) { return block.timestamp; } // totalBalance() function totalBalanceOf(address _addr) public view returns (uint256) { return totalbalances[_addr]; } // ShowRelease() looking for the already release amount of the address at some time function ShowRelease(address _addr, uint256 _times) public view returns (uint256) { return userRelease[_addr][_times]; } // ShowUnrelease() looking for the not yet release amount of the address at some time function ShowUnrelease(address _addr, uint256 _times) public view returns (uint256) { return safeSubtract(userbalances[_addr][_times],ShowRelease(_addr,_times)); } // ShowChargeTime() looking for the charge time function ShowChargeTime(address _addr, uint256 _times) public view returns (uint256) { return userChargeTime[_addr][_times]; } // ShowChargeCount() looking for the user total charge times function ShowChargeCount(address _addr) public view returns (uint256) { return userChargeCount[_addr]; } // ShowNextCliff() looking for the nex cliff time function ShowNextCliff(address _addr, uint256 _times) public view returns (uint256) { return safeAdd(lastCliff[_addr][_times],cliff); } // ShowSegmentation() looking for the user balances Segmentation function ShowSegmentation(address _addr, uint256 _times,uint256 _period) public view returns (uint256) { return userbalancesSegmentation[_addr][_times][_period]; } } contract Token { uint256 public totalSupply; function balanceOf(address _owner) public view returns (uint256 balance); function transfer(address _to, uint256 _value) public returns (bool success); function transferFrom(address _from, address _to, uint256 _value) public returns (bool success); function approve(address _spender, uint256 _value) public returns (bool success); function allowance(address _owner, address _spender) public view returns (uint256 remaining); event Transfer(address indexed _from, address indexed _to, uint256 _value); event Approval(address indexed _owner, address indexed _spender, uint256 _value); } /* ERC 20 token */ contract StandardToken is controllable, Pausable, Token, Lockable { function transfer(address _to, uint256 _value) public whenNotPaused() returns (bool success) { if (balances[msg.sender] >= _value && balances[_to] + _value > balances[_to] && !isBlacklist(msg.sender)) { // sender balances[msg.sender] = safeSubtract(balances[msg.sender],_value); totalbalances[msg.sender] = safeSubtract(totalbalances[msg.sender],_value); // _to balances[_to] = safeAdd(balances[_to],_value); totalbalances[_to] = safeAdd(totalbalances[_to],_value); emit Transfer(msg.sender, _to, _value); return true; } else { return false; } } function transferFrom(address _from, address _to, uint256 _value) public whenNotPaused() returns (bool success) { if (balances[_from] >= _value && allowed[_from][msg.sender] >= _value && balances[_to] + _value > balances[_to] && !isBlacklist(msg.sender)) { // _to balances[_to] = safeAdd(balances[_to],_value); totalbalances[_to] = safeAdd(totalbalances[_to],_value); // _from balances[_from] = safeSubtract(balances[_from],_value); totalbalances[_from] = safeSubtract(totalbalances[_from],_value); // allowed allowed[_from][msg.sender] = safeSubtract(allowed[_from][msg.sender],_value); emit Transfer(_from, _to, _value); return true; } else { return false; } } function balanceOf(address _owner) public view returns (uint256 balance) { return balances[_owner]; } function approve(address _spender, uint256 _value) public returns (bool success) { allowed[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } function allowance(address _owner, address _spender) public view returns (uint256 remaining) { return allowed[_owner][_spender]; } // mapping (address => uint256) balances; mapping (address => mapping (address => uint256)) allowed; } contract BugXToken is StandardToken { /** * base parameters */ // metadata string public constant name = "BUGX2.0"; string public constant symbol = "BUGX"; uint256 public constant decimals = 18; string public version = "2.0"; // contracts address public newContractAddr; // the new contract for BUGX token updates; // crowdsale parameters bool public isFunding; // switched to true in operational state uint256 public fundingStartBlock; uint256 public fundingStopBlock; uint256 public currentSupply; // current supply tokens for sell uint256 public tokenRaised = 0; // the number of total sold token uint256 public tokenIssued = 0; // the number of total issued token uint256 public tokenMigrated = 0; // the number of total Migrated token uint256 internal tokenExchangeRate = 9000; // 9000 BUGX tokens per 1 ETH uint256 internal tokenExchangeRateTwo = 9900; // 9000 * 1.1 BUGX tokens per 1 ETH uint256 internal tokenExchangeRateThree = 11250; // 9000 * 1.25 BUGX tokens per 1 ETH // events event AllocateToken(address indexed _to, uint256 _value); // issue token to buyer; event TakebackToken(address indexed _from, uint256 _value); // record token take back info; event RaiseToken(address indexed _to, uint256 _value); // record token raise info; event IssueToken(address indexed _to, uint256 _value); event IncreaseSupply(uint256 _value); event DecreaseSupply(uint256 _value); event Migrate(address indexed _addr, uint256 _tokens, uint256 _totaltokens); // format decimals. function formatDecimals(uint256 _value) internal pure returns (uint256 ) { return _value * 10 ** decimals; } /** * constructor function */ // constructor constructor( address _ethFundDeposit, uint256 _currentSupply ) public { require(_ethFundDeposit != address(0x0)); ethFundDeposit = _ethFundDeposit; isFunding = false; //controls pre through crowdsale state fundingStartBlock = 0; fundingStopBlock = 0; currentSupply = formatDecimals(_currentSupply); totalSupply = formatDecimals(1500000000); //1,500,000,000 total supply require(currentSupply <= totalSupply); balances[ethFundDeposit] = currentSupply; totalbalances[ethFundDeposit] = currentSupply; } /** * Modify currentSupply functions */ /// @dev increase the token's supply function increaseSupply (uint256 _tokens) onlyOwner external { uint256 _value = formatDecimals(_tokens); require (_value + currentSupply <= totalSupply); currentSupply = safeAdd(currentSupply, _value); tokenadd(ethFundDeposit,_value); emit IncreaseSupply(_value); } /// @dev decrease the token's supply function decreaseSupply (uint256 _tokens) onlyOwner external { uint256 _value = formatDecimals(_tokens); uint256 tokenCirculation = safeAdd(tokenRaised,tokenIssued); require (safeAdd(_value,tokenCirculation) <= currentSupply); currentSupply = safeSubtract(currentSupply, _value); tokensub(ethFundDeposit,_value); emit DecreaseSupply(_value); } /** * Funding functions */ modifier whenFunding() { require (isFunding); require (block.number >= fundingStartBlock); require (block.number <= fundingStopBlock); _; } /// @dev turn on the funding state function startFunding (uint256 _fundingStartBlock, uint256 _fundingStopBlock) onlyOwner external { require (!isFunding); require (_fundingStartBlock < _fundingStopBlock); require (block.number < _fundingStartBlock); fundingStartBlock = _fundingStartBlock; fundingStopBlock = _fundingStopBlock; isFunding = true; } /// @dev turn off the funding state function stopFunding() onlyOwner external { require (isFunding); isFunding = false; } /** * migrate functions */ /// @dev set a new contract for recieve the tokens (for update contract) function setMigrateContract(address _newContractAddr) onlyOwner external { require (_newContractAddr != newContractAddr); newContractAddr = _newContractAddr; } /// sends the tokens to new contract by owner function migrate(address _addr) onlySelfOrOwner(_addr) external { require(!isFunding); require(newContractAddr != address(0x0)); uint256 tokens_value = balances[_addr]; uint256 totaltokens_value = totalbalances[_addr]; require (tokens_value != 0 || totaltokens_value != 0); balances[_addr] = 0; totalbalances[_addr] = 0; IMigrationContract newContract = IMigrationContract(newContractAddr); require (newContract.migrate(_addr, tokens_value, totaltokens_value)); tokenMigrated = safeAdd(tokenMigrated, totaltokens_value); emit Migrate(_addr, tokens_value, totaltokens_value); } /** * tokenRaised and tokenIssued control functions * base functions */ /// token raised function tokenRaise (address _addr,uint256 _value) internal { uint256 tokenCirculation = safeAdd(tokenRaised,tokenIssued); require (safeAdd(_value,tokenCirculation) <= currentSupply); tokenRaised = safeAdd(tokenRaised, _value); emit RaiseToken(_addr, _value); } /// issue token 1 : token issued function tokenIssue (address _addr,uint256 _value) internal { uint256 tokenCirculation = safeAdd(tokenRaised,tokenIssued); require (safeAdd(_value,tokenCirculation) <= currentSupply); tokenIssued = safeAdd(tokenIssued, _value); emit IssueToken(_addr, _value); } /// issue token 2 : issue token take back function tokenTakeback (address _addr,uint256 _value) internal { require (tokenIssued >= _value); tokenIssued = safeSubtract(tokenIssued, _value); emit TakebackToken(_addr, _value); } /// issue token take from ethFundDeposit to user function tokenadd (address _addr,uint256 _value) internal { require(_value != 0); require (_addr != address(0x0)); balances[_addr] = safeAdd(balances[_addr], _value); totalbalances[_addr] = safeAdd(totalbalances[_addr], _value); } /// issue token take from user to ethFundDeposit function tokensub (address _addr,uint256 _value) internal { require(_value != 0); require (_addr != address(0x0)); balances[_addr] = safeSubtract(balances[_addr], _value); totalbalances[_addr] = safeSubtract(totalbalances[_addr], _value); } /** * tokenRaised and tokenIssued control functions * main functions */ /// Issues tokens to buyers. function allocateToken(address _addr, uint256 _tokens) onlyOwner external { uint256 _value = formatDecimals(_tokens); tokenadd(_addr,_value); tokensub(ethFundDeposit,_value); tokenIssue(_addr,_value); emit Transfer(ethFundDeposit, _addr, _value); } /// Issues tokens deduction. function deductionToken (address _addr, uint256 _tokens) onlyOwner external { uint256 _value = formatDecimals(_tokens); tokensub(_addr,_value); tokenadd(ethFundDeposit,_value); tokenTakeback(_addr,_value); emit Transfer(_addr, ethFundDeposit, _value); } /// add the segmentation function addSegmentation(address _addr, uint256 _times,uint256 _period,uint256 _tokens) onlyOwner external returns (bool) { uint256 amount = userbalancesSegmentation[_addr][_times][_period]; if (amount != 0 && _tokens != 0){ uint256 _value = formatDecimals(_tokens); userbalancesSegmentation[_addr][_times][_period] = safeAdd(amount,_value); userbalances[_addr][_times] = safeAdd(userbalances[_addr][_times], _value); totalbalances[_addr] = safeAdd(totalbalances[_addr], _value); tokensub(ethFundDeposit,_value); tokenIssue(_addr,_value); return true; } else { return false; } } /// sub the segmentation function subSegmentation(address _addr, uint256 _times,uint256 _period,uint256 _tokens) onlyOwner external returns (bool) { uint256 amount = userbalancesSegmentation[_addr][_times][_period]; if (amount != 0 && _tokens != 0){ uint256 _value = formatDecimals(_tokens); userbalancesSegmentation[_addr][_times][_period] = safeSubtract(amount,_value); userbalances[_addr][_times] = safeSubtract(userbalances[_addr][_times], _value); totalbalances[_addr] = safeSubtract(totalbalances[_addr], _value); tokenadd(ethFundDeposit,_value); tokenTakeback(_addr,_value); return true; } else { return false; } } /** * tokenExchangeRate functions */ /// @dev set the token's tokenExchangeRate, function setTokenExchangeRate(uint256 _RateOne,uint256 _RateTwo,uint256 _RateThree) onlyOwner external { require (_RateOne != 0 && _RateTwo != 0 && _RateThree != 0); require (_RateOne != tokenExchangeRate && _RateTwo != tokenExchangeRateTwo && _RateThree != tokenExchangeRateThree); tokenExchangeRate = _RateOne; tokenExchangeRateTwo = _RateTwo; tokenExchangeRateThree = _RateThree; } /// calculate the tokenExchangeRate function computeTokenAmount(uint256 _eth) internal view returns (uint256 tokens) { if(_eth > 0 && _eth < 100 ether){ tokens = safeMult(_eth, tokenExchangeRate); } if (_eth >= 100 ether && _eth < 500 ether){ tokens = safeMult(_eth, tokenExchangeRateTwo); } if (_eth >= 500 ether ){ tokens = safeMult(_eth, tokenExchangeRateThree); } } /** * Append : the LockMechanism functions by owner */ function LockMechanismByOwner ( address _addr, uint256 _tokens ) external onlyOwner whenFunding { require (_tokens != 0); uint256 _value = formatDecimals(_tokens); tokenRaise(_addr,_value); tokensub(ethFundDeposit,_value); LockMechanism(_addr,_value); emit Transfer(ethFundDeposit,_addr,_value); } /** * ETH control functions */ /// @dev sends ETH to BUGX team function transferETH() onlyOwner external { require (address(this).balance != 0); ethFundDeposit.transfer(address(this).balance); } function () public payable whenFunding { // fallback function require (msg.value != 0); uint256 _value = computeTokenAmount(msg.value); tokenRaise(msg.sender,_value); tokensub(ethFundDeposit,_value); LockMechanism(msg.sender,_value); emit Transfer(ethFundDeposit,msg.sender,_value); } }
ShowSegmentation() looking for the user balances Segmentation
function ShowSegmentation(address _addr, uint256 _times,uint256 _period) public view returns (uint256) { return userbalancesSegmentation[_addr][_times][_period]; }
5,466,068
./partial_match/1/0x8E3a532F2212D71074fD27BcF570c878D14458Fb/sources/contracts/HYFI_Lottery.sol
add new reward information rewardManager the address of reward manager responsible for rewards revealing logic totalAmount the total available amount of such type of rewards/
function addReward( address rewardManager, uint256 totalAmount ) external onlyRole(DEFAULT_ADMIN_ROLE) { RewardsData memory reward; reward.rewardManager = IHYFI_RewardsManager(rewardManager); reward.totalAmount = totalAmount; reward.freeAmount = totalAmount; _rewards.push(reward); }
2,694,166
pragma solidity 0.4.24; /* script to setup contracts after full redeploy on Rinkeby. called via StabilityBoardProxy (MultiSig) but deployer account is the only signer yet because these working on the new contracts only. Stability Board and pretoken signers will be added and deployer will be removed when setup is successful. */ contract Main0001_initFirstDeploy { address constant DEPLOYER_ACCOUNT = 0x7b534c2D0F9Ee973e0b6FE8D4000cA711A20f22e; address constant RATES_FEEDER_ACCOUNT = 0x8C58187a978979947b88824DCdA5Cb5fD4410387; // new contracts address constant preTokenProxyAddress = 0x1411b3B189B01f6e6d1eA883bFFcbD3a5224934C; address constant stabilityBoardProxyAddress = 0x4686f017D456331ed2C1de66e134D8d05B24413D; PreToken constant preToken = PreToken(0xeCb782B19Be6E657ae2D88831dD98145A00D32D5); Rates constant rates = Rates(0x4babbe57453e2b6AF125B4e304256fCBDf744480); FeeAccount constant feeAccount = FeeAccount(0xF6B541E1B5e001DCc11827C1A16232759aeA730a); AugmintReserves constant augmintReserves = AugmintReserves(0x633cb544b2EF1bd9269B2111fD2B66fC05cd3477); InterestEarnedAccount constant interestEarnedAccount = InterestEarnedAccount(0x5C1a44E07541203474D92BDD03f803ea74f6947c); TokenAEur constant tokenAEur = TokenAEur(0x86A635EccEFFfA70Ff8A6DB29DA9C8DB288E40D0); MonetarySupervisor constant monetarySupervisor = MonetarySupervisor(0x1Ca4F9d261707aF8A856020a4909B777da218868); LoanManager constant loanManager = LoanManager(0xCBeFaF199b800DEeB9EAd61f358EE46E06c54070); Locker constant locker = Locker(0x095c0F071Fd75875a6b5a1dEf3f3a993F591080c); Exchange constant exchange = Exchange(0x8b52b019d237d0bbe8Baedf219132D5254e0690b); function execute(Main0001_initFirstDeploy /* self, not used */) external { // called via StabilityBoardProxy require(address(this) == stabilityBoardProxyAddress, "only deploy via stabilityboardsigner"); /****************************************************************************** * Set up permissions ******************************************************************************/ // preToken Permissions bytes32[] memory preTokenPermissions = new bytes32[](2); // dynamic array needed for grantMultiplePermissions() preTokenPermissions[0] = "PreTokenSigner"; preTokenPermissions[1] = "PermissionGranter"; preToken.grantMultiplePermissions(preTokenProxyAddress, preTokenPermissions); // StabilityBoard rates.grantPermission(stabilityBoardProxyAddress, "StabilityBoard"); feeAccount.grantPermission(stabilityBoardProxyAddress, "StabilityBoard"); interestEarnedAccount.grantPermission(stabilityBoardProxyAddress, "StabilityBoard"); tokenAEur.grantPermission(stabilityBoardProxyAddress, "StabilityBoard"); augmintReserves.grantPermission(stabilityBoardProxyAddress, "StabilityBoard"); monetarySupervisor.grantPermission(stabilityBoardProxyAddress, "StabilityBoard"); loanManager.grantPermission(stabilityBoardProxyAddress, "StabilityBoard"); locker.grantPermission(stabilityBoardProxyAddress, "StabilityBoard"); exchange.grantPermission(stabilityBoardProxyAddress, "StabilityBoard"); // RatesFeeder permissions to allow calling setRate() rates.grantPermission(RATES_FEEDER_ACCOUNT, "RatesFeeder"); // set NoTransferFee permissions feeAccount.grantPermission(feeAccount, "NoTransferFee"); feeAccount.grantPermission(augmintReserves, "NoTransferFee"); feeAccount.grantPermission(interestEarnedAccount, "NoTransferFee"); feeAccount.grantPermission(monetarySupervisor, "NoTransferFee"); feeAccount.grantPermission(loanManager, "NoTransferFee"); feeAccount.grantPermission(locker, "NoTransferFee"); feeAccount.grantPermission(exchange, "NoTransferFee"); // set MonetarySupervisor permissions interestEarnedAccount.grantPermission(monetarySupervisor, "MonetarySupervisor"); tokenAEur.grantPermission(monetarySupervisor, "MonetarySupervisor"); augmintReserves.grantPermission(monetarySupervisor, "MonetarySupervisor"); // set LoanManager permissions monetarySupervisor.grantPermission(loanManager, "LoanManager"); // set Locker permissions monetarySupervisor.grantPermission(locker, "Locker"); /****************************************************************************** * Add loan products ******************************************************************************/ // term (in sec), discountRate, loanCoverageRatio, minDisbursedAmount (w/ 4 decimals), defaultingFeePt, isActive loanManager.addLoanProduct(30 days, 990641, 600000, 1000, 50000, true); // 12% p.a. loanManager.addLoanProduct(14 days, 996337, 600000, 1000, 50000, true); // 10% p.a. loanManager.addLoanProduct(7 days, 998170, 600000, 1000, 50000, true); // 10% p.a. /****************************************************************************** * Add lock products ******************************************************************************/ // (perTermInterest, durationInSecs, minimumLockAmount, isActive) locker.addLockProduct(4019, 30 days, 1000, true); // 5% p.a. locker.addLockProduct(1506, 14 days, 1000, true); // 4% p.a. locker.addLockProduct(568, 7 days, 1000, true); // 3% p.a. /****************************************************************************** * Revoke PermissionGranter from deployer account * NB: migration scripts mistekanly granted it to deployer account (account[0]) * instead of StabilityBoardProxy in constructors ******************************************************************************/ preToken.revokePermission(DEPLOYER_ACCOUNT, "PermissionGranter"); rates.revokePermission(DEPLOYER_ACCOUNT, "PermissionGranter"); feeAccount.revokePermission(DEPLOYER_ACCOUNT, "PermissionGranter"); augmintReserves.revokePermission(DEPLOYER_ACCOUNT, "PermissionGranter"); interestEarnedAccount.revokePermission(DEPLOYER_ACCOUNT, "PermissionGranter"); tokenAEur.revokePermission(DEPLOYER_ACCOUNT, "PermissionGranter"); monetarySupervisor.revokePermission(DEPLOYER_ACCOUNT, "PermissionGranter"); loanManager.revokePermission(DEPLOYER_ACCOUNT, "PermissionGranter"); locker.revokePermission(DEPLOYER_ACCOUNT, "PermissionGranter"); exchange.revokePermission(DEPLOYER_ACCOUNT, "PermissionGranter"); /****************************************************************************** * Revoke PermissionGranter from this contract on preToken * NB: deploy script temporarly granted PermissionGranter to this script * now we can remove it as we granted it to preTokenProxy above ******************************************************************************/ preToken.revokePermission(stabilityBoardProxyAddress, "PermissionGranter"); } } /** * @title SafeMath * @dev Math operations with safety checks that throw on error TODO: check against ds-math: https://blog.dapphub.com/ds-math/ TODO: move roundedDiv to a sep lib? (eg. Math.sol) */ library SafeMath { function mul(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a * b; require(a == 0 || c / a == b, "mul overflow"); return c; } function div(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "div by 0"); // Solidity automatically throws for div by 0 but require to emit reason uint256 c = a / b; // require(a == b * c + a % b); // There is no case in which this doesn&#39;t hold return c; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a, "sub underflow"); return a - b; } function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "add overflow"); return c; } function roundedDiv(uint a, uint b) internal pure returns (uint256) { require(b > 0, "div by 0"); // Solidity automatically throws for div by 0 but require to emit reason uint256 z = a / b; if (a % b >= b / 2) { z++; // no need for safe add b/c it can happen only if we divided the input } return z; } } /* Generic contract to authorise calls to certain functions only from a given address. The address authorised must be a contract (multisig or not, depending on the permission), except for local test deployment works as: 1. contract deployer account deploys contracts 2. constructor grants "PermissionGranter" permission to deployer account 3. deployer account executes initial setup (no multiSig) 4. deployer account grants PermissionGranter permission for the MultiSig contract (e.g. StabilityBoardProxy or PreTokenProxy) 5. deployer account revokes its own PermissionGranter permission */ contract Restricted { // NB: using bytes32 rather than the string type because it&#39;s cheaper gas-wise: mapping (address => mapping (bytes32 => bool)) public permissions; event PermissionGranted(address indexed agent, bytes32 grantedPermission); event PermissionRevoked(address indexed agent, bytes32 revokedPermission); modifier restrict(bytes32 requiredPermission) { require(permissions[msg.sender][requiredPermission], "msg.sender must have permission"); _; } constructor(address permissionGranterContract) public { require(permissionGranterContract != address(0), "permissionGranterContract must be set"); permissions[permissionGranterContract]["PermissionGranter"] = true; emit PermissionGranted(permissionGranterContract, "PermissionGranter"); } function grantPermission(address agent, bytes32 requiredPermission) public { require(permissions[msg.sender]["PermissionGranter"], "msg.sender must have PermissionGranter permission"); permissions[agent][requiredPermission] = true; emit PermissionGranted(agent, requiredPermission); } function grantMultiplePermissions(address agent, bytes32[] requiredPermissions) public { require(permissions[msg.sender]["PermissionGranter"], "msg.sender must have PermissionGranter permission"); uint256 length = requiredPermissions.length; for (uint256 i = 0; i < length; i++) { grantPermission(agent, requiredPermissions[i]); } } function revokePermission(address agent, bytes32 requiredPermission) public { require(permissions[msg.sender]["PermissionGranter"], "msg.sender must have PermissionGranter permission"); permissions[agent][requiredPermission] = false; emit PermissionRevoked(agent, requiredPermission); } function revokeMultiplePermissions(address agent, bytes32[] requiredPermissions) public { uint256 length = requiredPermissions.length; for (uint256 i = 0; i < length; i++) { revokePermission(agent, requiredPermissions[i]); } } } /* Abstract multisig contract to allow multi approval execution of atomic contracts scripts e.g. migrations or settings. * Script added by signing a script address by a signer (NEW state) * Script goes to ALLOWED state once a quorom of signers sign it (quorom fx is defined in each derived contracts) * Script can be signed even in APPROVED state * APPROVED scripts can be executed only once. - if script succeeds then state set to DONE - If script runs out of gas or reverts then script state set to FAILEd and not allowed to run again (To avoid leaving "behind" scripts which fail in a given state but eventually execute in the future) * Scripts can be cancelled by an other multisig script approved and calling cancelScript() * Adding/removing signers is only via multisig approved scripts using addSigners / removeSigners fxs */ contract MultiSig { using SafeMath for uint256; uint public constant CHUNK_SIZE = 100; mapping(address => bool) public isSigner; address[] public allSigners; // all signers, even the disabled ones // NB: it can contain duplicates when a signer is added, removed then readded again // the purpose of this array is to being able to iterate on signers in isSigner uint public activeSignersCount; enum ScriptState {New, Approved, Done, Cancelled, Failed} struct Script { ScriptState state; uint signCount; mapping(address => bool) signedBy; address[] allSigners; } mapping(address => Script) public scripts; address[] public scriptAddresses; event SignerAdded(address signer); event SignerRemoved(address signer); event ScriptSigned(address scriptAddress, address signer); event ScriptApproved(address scriptAddress); event ScriptCancelled(address scriptAddress); event ScriptExecuted(address scriptAddress, bool result); constructor() public { // deployer address is the first signer. Deployer can configure new contracts by itself being the only "signer" // The first script which sets the new contracts live should add signers and revoke deployer&#39;s signature right isSigner[msg.sender] = true; allSigners.push(msg.sender); activeSignersCount = 1; emit SignerAdded(msg.sender); } function sign(address scriptAddress) public { require(isSigner[msg.sender], "sender must be signer"); Script storage script = scripts[scriptAddress]; require(script.state == ScriptState.Approved || script.state == ScriptState.New, "script state must be New or Approved"); require(!script.signedBy[msg.sender], "script must not be signed by signer yet"); if(script.allSigners.length == 0) { // first sign of a new script scriptAddresses.push(scriptAddress); } script.allSigners.push(msg.sender); script.signedBy[msg.sender] = true; script.signCount = script.signCount.add(1); emit ScriptSigned(scriptAddress, msg.sender); if(checkQuorum(script.signCount)){ script.state = ScriptState.Approved; emit ScriptApproved(scriptAddress); } } function execute(address scriptAddress) public returns (bool result) { // only allow execute to signers to avoid someone set an approved script failed by calling it with low gaslimit require(isSigner[msg.sender], "sender must be signer"); Script storage script = scripts[scriptAddress]; require(script.state == ScriptState.Approved, "script state must be Approved"); /* init to failed because if delegatecall rans out of gas we won&#39;t have enough left to set it. NB: delegatecall leaves 63/64 part of gasLimit for the caller. Therefore the execute might revert with out of gas, leaving script in Approved state when execute() is called with small gas limits. */ script.state = ScriptState.Failed; // passing scriptAddress to allow called script access its own public fx-s if needed if(scriptAddress.delegatecall(bytes4(keccak256("execute(address)")), scriptAddress)) { script.state = ScriptState.Done; result = true; } else { result = false; } emit ScriptExecuted(scriptAddress, result); } function cancelScript(address scriptAddress) public { require(msg.sender == address(this), "only callable via MultiSig"); Script storage script = scripts[scriptAddress]; require(script.state == ScriptState.Approved || script.state == ScriptState.New, "script state must be New or Approved"); script.state= ScriptState.Cancelled; emit ScriptCancelled(scriptAddress); } /* requires quorum so it&#39;s callable only via a script executed by this contract */ function addSigners(address[] signers) public { require(msg.sender == address(this), "only callable via MultiSig"); for (uint i= 0; i < signers.length; i++) { if (!isSigner[signers[i]]) { require(signers[i] != address(0), "new signer must not be 0x0"); activeSignersCount++; allSigners.push(signers[i]); isSigner[signers[i]] = true; emit SignerAdded(signers[i]); } } } /* requires quorum so it&#39;s callable only via a script executed by this contract */ function removeSigners(address[] signers) public { require(msg.sender == address(this), "only callable via MultiSig"); for (uint i= 0; i < signers.length; i++) { if (isSigner[signers[i]]) { require(activeSignersCount > 1, "must not remove last signer"); activeSignersCount--; isSigner[signers[i]] = false; emit SignerRemoved(signers[i]); } } } /* implement it in derived contract */ function checkQuorum(uint signersCount) internal view returns(bool isQuorum); function getAllSignersCount() view external returns (uint allSignersCount) { return allSigners.length; } // UI helper fx - Returns signers from offset as [signer id (index in allSigners), address as uint, isActive 0 or 1] function getAllSigners(uint offset) external view returns(uint[3][CHUNK_SIZE] signersResult) { for (uint8 i = 0; i < CHUNK_SIZE && i + offset < allSigners.length; i++) { address signerAddress = allSigners[i + offset]; signersResult[i] = [ i + offset, uint(signerAddress), isSigner[signerAddress] ? 1 : 0 ]; } } function getScriptsCount() view external returns (uint scriptsCount) { return scriptAddresses.length; } // UI helper fx - Returns scripts from offset as // [scriptId (index in scriptAddresses[]), address as uint, state, signCount] function getAllScripts(uint offset) external view returns(uint[4][CHUNK_SIZE] scriptsResult) { for (uint8 i = 0; i < CHUNK_SIZE && i + offset < scriptAddresses.length; i++) { address scriptAddress = scriptAddresses[i + offset]; scriptsResult[i] = [ i + offset, uint(scriptAddress), uint(scripts[scriptAddress].state), scripts[scriptAddress].signCount ]; } } } /* Augmint pretoken contract to record agreements and tokens allocated based on the agreement. Important: this is NOT an ERC20 token! PreTokens are non-fungible: agreements can have different conditions (valuationCap and discount) and pretokens are not tradable. Ownership can be transferred if owner wants to change wallet but the whole agreement and the total pretoken amount is moved to a new account PreTokenSigner can (via MultiSig): - add agreements and issue pretokens to an agreement - change owner of any agreement to handle if an owner lost a private keys - burn pretokens from any agreement to fix potential erroneous issuance These are known compromises on trustlessness hence all these tokens distributed based on signed agreements and preTokens are issued only to a closed group of contributors / team members. If despite these something goes wrong then as a last resort a new pretoken contract can be recreated from agreements. Some ERC20 functions are implemented so agreement owners can see their balances and use transfer in standard wallets. Restrictions: - only total balance can be transfered - effectively ERC20 transfer used to transfer agreement ownership - only agreement holders can transfer (i.e. can&#39;t transfer 0 amount if have no agreement to avoid polluting logs with Transfer events) - transfer is only allowed to accounts without an agreement yet - no approval and transferFrom ERC20 functions */ contract PreToken is Restricted { using SafeMath for uint256; uint public constant CHUNK_SIZE = 100; string constant public name = "Augmint pretokens"; // solhint-disable-line const-name-snakecase string constant public symbol = "APRE"; // solhint-disable-line const-name-snakecase uint8 constant public decimals = 0; // solhint-disable-line const-name-snakecase uint public totalSupply; struct Agreement { address owner; uint balance; uint32 discount; // discountRate in parts per million , ie. 10,000 = 1% uint32 valuationCap; // in USD (no decimals) } /* Agreement hash is the SHA-2 (SHA-256) hash of signed agreement document. To generate: OSX: shasum -a 256 agreement.pdf Windows: certUtil -hashfile agreement.pdf SHA256 */ mapping(address => bytes32) public agreementOwners; // to lookup agrement by owner mapping(bytes32 => Agreement) public agreements; bytes32[] public allAgreements; // all agreements to able to iterate over event Transfer(address indexed from, address indexed to, uint amount); event NewAgreement(address owner, bytes32 agreementHash, uint32 discount, uint32 valuationCap); constructor(address permissionGranterContract) public Restricted(permissionGranterContract) {} // solhint-disable-line no-empty-blocks function addAgreement(address owner, bytes32 agreementHash, uint32 discount, uint32 valuationCap) external restrict("PreTokenSigner") { require(owner != address(0), "owner must not be 0x0"); require(agreementOwners[owner] == 0x0, "owner must not have an aggrement yet"); require(agreementHash != 0x0, "agreementHash must not be 0x0"); require(discount > 0, "discount must be > 0"); require(agreements[agreementHash].discount == 0, "agreement must not exist yet"); agreements[agreementHash] = Agreement(owner, 0, discount, valuationCap); agreementOwners[owner] = agreementHash; allAgreements.push(agreementHash); emit NewAgreement(owner, agreementHash, discount, valuationCap); } function issueTo(bytes32 agreementHash, uint amount) external restrict("PreTokenSigner") { Agreement storage agreement = agreements[agreementHash]; require(agreement.discount > 0, "agreement must exist"); agreement.balance = agreement.balance.add(amount); totalSupply = totalSupply.add(amount); emit Transfer(0x0, agreement.owner, amount); } /* Restricted function to allow pretoken signers to fix incorrect issuance */ function burnFrom(bytes32 agreementHash, uint amount) public restrict("PreTokenSigner") returns (bool) { Agreement storage agreement = agreements[agreementHash]; require(agreement.discount > 0, "agreement must exist"); // this is redundant b/c of next requires but be explicit require(amount > 0, "burn amount must be > 0"); require(agreement.balance >= amount, "must not burn more than balance"); // .sub would revert anyways but emit reason agreement.balance = agreement.balance.sub(amount); totalSupply = totalSupply.sub(amount); emit Transfer(agreement.owner, 0x0, amount); return true; } function balanceOf(address owner) public view returns (uint) { return agreements[agreementOwners[owner]].balance; } /* function to transfer agreement ownership to other wallet by owner it&#39;s in ERC20 form so owners can use standard ERC20 wallet just need to pass full balance as value */ function transfer(address to, uint amount) public returns (bool) { // solhint-disable-line no-simple-event-func-name require(amount == agreements[agreementOwners[msg.sender]].balance, "must transfer full balance"); _transfer(msg.sender, to); return true; } /* Restricted function to allow pretoken signers to fix if pretoken owner lost keys */ function transferAgreement(bytes32 agreementHash, address to) public restrict("PreTokenSigner") returns (bool) { _transfer(agreements[agreementHash].owner, to); return true; } /* private function used by transferAgreement & transfer */ function _transfer(address from, address to) private { Agreement storage agreement = agreements[agreementOwners[from]]; require(agreementOwners[from] != 0x0, "from agreement must exists"); require(agreementOwners[to] == 0, "to must not have an agreement"); require(to != 0x0, "must not transfer to 0x0"); agreement.owner = to; agreementOwners[to] = agreementOwners[from]; agreementOwners[from] = 0x0; emit Transfer(from, to, agreement.balance); } function getAgreementsCount() external view returns (uint agreementsCount) { return allAgreements.length; } // UI helper fx - Returns all agreements from offset as // [index in allAgreements, account address as uint, balance, agreementHash as uint, // discount as uint, valuationCap as uint ] function getAllAgreements(uint offset) external view returns(uint[6][CHUNK_SIZE] agreementsResult) { for (uint8 i = 0; i < CHUNK_SIZE && i + offset < allAgreements.length; i++) { bytes32 agreementHash = allAgreements[i + offset]; Agreement storage agreement = agreements[agreementHash]; agreementsResult[i] = [ i + offset, uint(agreement.owner), agreement.balance, uint(agreementHash), uint(agreement.discount), uint(agreement.valuationCap)]; } } } /* Generic symbol / WEI rates contract. only callable by trusted price oracles. Being regularly called by a price oracle TODO: trustless/decentrilezed price Oracle TODO: shall we use blockNumber instead of now for lastUpdated? TODO: consider if we need storing rates with variable decimals instead of fixed 4 TODO: could we emit 1 RateChanged event from setMultipleRates (symbols and newrates arrays)? */ contract Rates is Restricted { using SafeMath for uint256; struct RateInfo { uint rate; // how much 1 WEI worth 1 unit , i.e. symbol/ETH rate // 0 rate means no rate info available uint lastUpdated; } // mapping currency symbol => rate. all rates are stored with 4 decimals. i.e. ETH/EUR = 989.12 then rate = 989,1200 mapping(bytes32 => RateInfo) public rates; event RateChanged(bytes32 symbol, uint newRate); constructor(address permissionGranterContract) public Restricted(permissionGranterContract) {} // solhint-disable-line no-empty-blocks function setRate(bytes32 symbol, uint newRate) external restrict("RatesFeeder") { rates[symbol] = RateInfo(newRate, now); emit RateChanged(symbol, newRate); } function setMultipleRates(bytes32[] symbols, uint[] newRates) external restrict("RatesFeeder") { require(symbols.length == newRates.length, "symobls and newRates lengths must be equal"); for (uint256 i = 0; i < symbols.length; i++) { rates[symbols[i]] = RateInfo(newRates[i], now); emit RateChanged(symbols[i], newRates[i]); } } function convertFromWei(bytes32 bSymbol, uint weiValue) external view returns(uint value) { require(rates[bSymbol].rate > 0, "rates[bSymbol] must be > 0"); return weiValue.mul(rates[bSymbol].rate).roundedDiv(1000000000000000000); } function convertToWei(bytes32 bSymbol, uint value) external view returns(uint weiValue) { // next line would revert with div by zero but require to emit reason require(rates[bSymbol].rate > 0, "rates[bSymbol] must be > 0"); /* TODO: can we make this not loosing max scale? */ return value.mul(1000000000000000000).roundedDiv(rates[bSymbol].rate); } } contract SystemAccount is Restricted { event WithdrawFromSystemAccount(address tokenAddress, address to, uint tokenAmount, uint weiAmount, string narrative); constructor(address permissionGranterContract) public Restricted(permissionGranterContract) {} // solhint-disable-line no-empty-blocks /* TODO: this is only for first pilots to avoid funds stuck in contract due to bugs. remove this function for higher volume pilots */ function withdraw(AugmintToken tokenAddress, address to, uint tokenAmount, uint weiAmount, string narrative) external restrict("StabilityBoard") { tokenAddress.transferWithNarrative(to, tokenAmount, narrative); if (weiAmount > 0) { to.transfer(weiAmount); } emit WithdrawFromSystemAccount(tokenAddress, to, tokenAmount, weiAmount, narrative); } } interface TokenReceiver { function transferNotification(address from, uint256 amount, uint data) external; } interface TransferFeeInterface { function calculateTransferFee(address from, address to, uint amount) external view returns (uint256 fee); } interface ExchangeFeeInterface { function calculateExchangeFee(uint weiAmount) external view returns (uint256 weiFee); } interface ERC20Interface { event Approval(address indexed _owner, address indexed _spender, uint _value); event Transfer(address indexed from, address indexed to, uint amount); function transfer(address to, uint value) external returns (bool); // solhint-disable-line no-simple-event-func-name function transferFrom(address from, address to, uint value) external returns (bool); function approve(address spender, uint value) external returns (bool); function balanceOf(address who) external view returns (uint); function allowance(address _owner, address _spender) external view returns (uint remaining); } /* Augmint Token interface (abstract contract) TODO: overload transfer() & transferFrom() instead of transferWithNarrative() & transferFromWithNarrative() when this fix available in web3& truffle also uses that web3: https://github.com/ethereum/web3.js/pull/1185 TODO: shall we use bytes for narrative? */ contract AugmintTokenInterface is Restricted, ERC20Interface { using SafeMath for uint256; string public name; string public symbol; bytes32 public peggedSymbol; uint8 public decimals; uint public totalSupply; mapping(address => uint256) public balances; // Balances for each account mapping(address => mapping (address => uint256)) public allowed; // allowances added with approve() address public stabilityBoardProxy; TransferFeeInterface public feeAccount; mapping(bytes32 => bool) public delegatedTxHashesUsed; // record txHashes used by delegatedTransfer event TransferFeesChanged(uint transferFeePt, uint transferFeeMin, uint transferFeeMax); event Transfer(address indexed from, address indexed to, uint amount); event AugmintTransfer(address indexed from, address indexed to, uint amount, string narrative, uint fee); event TokenIssued(uint amount); event TokenBurned(uint amount); event Approval(address indexed _owner, address indexed _spender, uint256 _value); function transfer(address to, uint value) external returns (bool); // solhint-disable-line no-simple-event-func-name function transferFrom(address from, address to, uint value) external returns (bool); function approve(address spender, uint value) external returns (bool); function delegatedTransfer(address from, address to, uint amount, string narrative, uint maxExecutorFeeInToken, /* client provided max fee for executing the tx */ bytes32 nonce, /* random nonce generated by client */ /* ^^^^ end of signed data ^^^^ */ bytes signature, uint requestedExecutorFeeInToken /* the executor can decide to request lower fee */ ) external; function delegatedTransferAndNotify(address from, TokenReceiver target, uint amount, uint data, uint maxExecutorFeeInToken, /* client provided max fee for executing the tx */ bytes32 nonce, /* random nonce generated by client */ /* ^^^^ end of signed data ^^^^ */ bytes signature, uint requestedExecutorFeeInToken /* the executor can decide to request lower fee */ ) external; function increaseApproval(address spender, uint addedValue) external returns (bool); function decreaseApproval(address spender, uint subtractedValue) external returns (bool); function issueTo(address to, uint amount) external; // restrict it to "MonetarySupervisor" in impl.; function burn(uint amount) external; function transferAndNotify(TokenReceiver target, uint amount, uint data) external; function transferWithNarrative(address to, uint256 amount, string narrative) external; function transferFromWithNarrative(address from, address to, uint256 amount, string narrative) external; function allowance(address owner, address spender) external view returns (uint256 remaining); function balanceOf(address who) external view returns (uint); } /** * @title Eliptic curve signature operations * * @dev Based on https://github.com/OpenZeppelin/openzeppelin-solidity/blob/master/contracts/ECRecovery.sol * * TODO Remove this library once solidity supports passing a signature to ecrecover. * See https://github.com/ethereum/solidity/issues/864 * */ library ECRecovery { /** * @dev Recover signer address from a message by using their signature * @param hash bytes32 message, the hash is the signed message. What is recovered is the signer address. * @param sig bytes signature, the signature is generated using web3.eth.sign() */ function recover(bytes32 hash, bytes sig) internal pure returns (address) { bytes32 r; bytes32 s; uint8 v; // Check the signature length if (sig.length != 65) { return (address(0)); } // Divide the signature in r, s and v variables // ecrecover takes the signature parameters, and the only way to get them // currently is to use assembly. // solium-disable-next-line security/no-inline-assembly assembly { r := mload(add(sig, 32)) s := mload(add(sig, 64)) v := byte(0, mload(add(sig, 96))) } // Version of signature should be 27 or 28, but 0 and 1 are also possible versions if (v < 27) { v += 27; } // If the version is correct return the signer address if (v != 27 && v != 28) { return (address(0)); } else { // solium-disable-next-line arg-overflow return ecrecover(hash, v, r, s); } } /** * toEthSignedMessageHash * @dev prefix a bytes32 value with "\x19Ethereum Signed Message:" * @dev and hash the result */ 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)); } } /* Generic Augmint Token implementation (ERC20 token) This contract manages: * Balances of Augmint holders and transactions between them * Issues/burns tokens TODO: - reconsider delegatedTransfer and how to structure it - shall we allow change of txDelegator? - consider generic bytes arg instead of uint for transferAndNotify - consider separate transfer fee params and calculation to separate contract (to feeAccount?) */ contract AugmintToken is AugmintTokenInterface { event FeeAccountChanged(TransferFeeInterface newFeeAccount); constructor(address permissionGranterContract, string _name, string _symbol, bytes32 _peggedSymbol, uint8 _decimals, TransferFeeInterface _feeAccount) public Restricted(permissionGranterContract) { require(_feeAccount != address(0), "feeAccount must be set"); require(bytes(_name).length > 0, "name must be set"); require(bytes(_symbol).length > 0, "symbol must be set"); name = _name; symbol = _symbol; peggedSymbol = _peggedSymbol; decimals = _decimals; feeAccount = _feeAccount; } function transfer(address to, uint256 amount) external returns (bool) { _transfer(msg.sender, to, amount, ""); return true; } /* Transfers based on an offline signed transfer instruction. */ function delegatedTransfer(address from, address to, uint amount, string narrative, uint maxExecutorFeeInToken, /* client provided max fee for executing the tx */ bytes32 nonce, /* random nonce generated by client */ /* ^^^^ end of signed data ^^^^ */ bytes signature, uint requestedExecutorFeeInToken /* the executor can decide to request lower fee */ ) external { bytes32 txHash = keccak256(abi.encodePacked(this, from, to, amount, narrative, maxExecutorFeeInToken, nonce)); _checkHashAndTransferExecutorFee(txHash, signature, from, maxExecutorFeeInToken, requestedExecutorFeeInToken); _transfer(from, to, amount, narrative); } function approve(address _spender, uint256 amount) external returns (bool) { require(_spender != 0x0, "spender must be set"); allowed[msg.sender][_spender] = amount; emit Approval(msg.sender, _spender, amount); return true; } /** ERC20 transferFrom attack protection: https://github.com/DecentLabs/dcm-poc/issues/57 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) Based on MonolithDAO Token.sol */ function increaseApproval(address _spender, uint _addedValue) external returns (bool) { return _increaseApproval(msg.sender, _spender, _addedValue); } function decreaseApproval(address _spender, uint _subtractedValue) external 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; } function transferFrom(address from, address to, uint256 amount) external returns (bool) { _transferFrom(from, to, amount, ""); return true; } // Issue tokens. See MonetarySupervisor but as a rule of thumb issueTo is only allowed: // - on new loan (by trusted Lender contracts) // - when converting old tokens using MonetarySupervisor // - strictly to reserve by Stability Board (via MonetarySupervisor) function issueTo(address to, uint amount) external restrict("MonetarySupervisor") { balances[to] = balances[to].add(amount); totalSupply = totalSupply.add(amount); emit Transfer(0x0, to, amount); emit AugmintTransfer(0x0, to, amount, "", 0); } // Burn tokens. Anyone can burn from its own account. YOLO. // Used by to burn from Augmint reserve or by Lender contract after loan repayment function burn(uint amount) external { require(balances[msg.sender] >= amount, "balance must be >= amount"); balances[msg.sender] = balances[msg.sender].sub(amount); totalSupply = totalSupply.sub(amount); emit Transfer(msg.sender, 0x0, amount); emit AugmintTransfer(msg.sender, 0x0, amount, "", 0); } /* to upgrade feeAccount (eg. for fee calculation changes) */ function setFeeAccount(TransferFeeInterface newFeeAccount) external restrict("StabilityBoard") { feeAccount = newFeeAccount; emit FeeAccountChanged(newFeeAccount); } /* transferAndNotify can be used by contracts which require tokens to have only 1 tx (instead of approve + call) Eg. repay loan, lock funds, token sell order on exchange Reverts on failue: - transfer fails - if transferNotification fails (callee must revert on failure) - if targetContract is an account or targetContract doesn&#39;t have neither transferNotification or fallback fx TODO: make data param generic bytes (see receiver code attempt in Locker.transferNotification) */ function transferAndNotify(TokenReceiver target, uint amount, uint data) external { _transfer(msg.sender, target, amount, ""); target.transferNotification(msg.sender, amount, data); } /* transferAndNotify based on an instruction signed offline */ function delegatedTransferAndNotify(address from, TokenReceiver target, uint amount, uint data, uint maxExecutorFeeInToken, /* client provided max fee for executing the tx */ bytes32 nonce, /* random nonce generated by client */ /* ^^^^ end of signed data ^^^^ */ bytes signature, uint requestedExecutorFeeInToken /* the executor can decide to request lower fee */ ) external { bytes32 txHash = keccak256(abi.encodePacked(this, from, target, amount, data, maxExecutorFeeInToken, nonce)); _checkHashAndTransferExecutorFee(txHash, signature, from, maxExecutorFeeInToken, requestedExecutorFeeInToken); _transfer(from, target, amount, ""); target.transferNotification(from, amount, data); } function transferWithNarrative(address to, uint256 amount, string narrative) external { _transfer(msg.sender, to, amount, narrative); } function transferFromWithNarrative(address from, address to, uint256 amount, string narrative) external { _transferFrom(from, to, amount, narrative); } function balanceOf(address _owner) external view returns (uint256 balance) { return balances[_owner]; } function allowance(address _owner, address _spender) external view returns (uint256 remaining) { return allowed[_owner][_spender]; } function _checkHashAndTransferExecutorFee(bytes32 txHash, bytes signature, address signer, uint maxExecutorFeeInToken, uint requestedExecutorFeeInToken) private { require(requestedExecutorFeeInToken <= maxExecutorFeeInToken, "requestedExecutorFee must be <= maxExecutorFee"); require(!delegatedTxHashesUsed[txHash], "txHash already used"); delegatedTxHashesUsed[txHash] = true; address recovered = ECRecovery.recover(ECRecovery.toEthSignedMessageHash(txHash), signature); require(recovered == signer, "invalid signature"); _transfer(signer, msg.sender, requestedExecutorFeeInToken, "Delegated transfer fee", 0); } function _increaseApproval(address _approver, address _spender, uint _addedValue) private returns (bool) { allowed[_approver][_spender] = allowed[_approver][_spender].add(_addedValue); emit Approval(_approver, _spender, allowed[_approver][_spender]); } function _transferFrom(address from, address to, uint256 amount, string narrative) private { require(balances[from] >= amount, "balance must >= amount"); require(allowed[from][msg.sender] >= amount, "allowance must be >= amount"); // don&#39;t allow 0 transferFrom if no approval: require(allowed[from][msg.sender] > 0, "allowance must be >= 0 even with 0 amount"); /* NB: fee is deducted from owner. It can result that transferFrom of amount x to fail when x + fee is not availale on owner balance */ _transfer(from, to, amount, narrative); allowed[from][msg.sender] = allowed[from][msg.sender].sub(amount); } function _transfer(address from, address to, uint transferAmount, string narrative) private { uint fee = feeAccount.calculateTransferFee(from, to, transferAmount); _transfer(from, to, transferAmount, narrative, fee); } function _transfer(address from, address to, uint transferAmount, string narrative, uint fee) private { require(to != 0x0, "to must be set"); uint amountWithFee = transferAmount.add(fee); // to emit proper reason instead of failing on from.sub() require(balances[from] >= amountWithFee, "balance must be >= amount + transfer fee"); if (fee > 0) { balances[feeAccount] = balances[feeAccount].add(fee); emit Transfer(from, feeAccount, fee); } balances[from] = balances[from].sub(amountWithFee); balances[to] = balances[to].add(transferAmount); emit Transfer(from, to, transferAmount); emit AugmintTransfer(from, to, transferAmount, narrative, fee); } } /* Contract to collect fees from system TODO: calculateExchangeFee + Exchange params and setters */ contract FeeAccount is SystemAccount, TransferFeeInterface { using SafeMath for uint256; struct TransferFee { uint pt; // in parts per million (ppm) , ie. 2,000 = 0.2% uint min; // with base unit of augmint token, eg. 2 decimals for token, eg. 310 = 3.1 ACE uint max; // with base unit of augmint token, eg. 2 decimals for token, eg. 310 = 3.1 ACE } TransferFee public transferFee; event TransferFeesChanged(uint transferFeePt, uint transferFeeMin, uint transferFeeMax); constructor(address permissionGranterContract, uint transferFeePt, uint transferFeeMin, uint transferFeeMax) public SystemAccount(permissionGranterContract) { transferFee = TransferFee(transferFeePt, transferFeeMin, transferFeeMax); } function () public payable { // solhint-disable-line no-empty-blocks // to accept ETH sent into feeAccount (defaulting fee in ETH ) } function setTransferFees(uint transferFeePt, uint transferFeeMin, uint transferFeeMax) external restrict("StabilityBoard") { transferFee = TransferFee(transferFeePt, transferFeeMin, transferFeeMax); emit TransferFeesChanged(transferFeePt, transferFeeMin, transferFeeMax); } function calculateTransferFee(address from, address to, uint amount) external view returns (uint256 fee) { if (!permissions[from]["NoTransferFee"] && !permissions[to]["NoTransferFee"]) { fee = amount.mul(transferFee.pt).div(1000000); if (fee > transferFee.max) { fee = transferFee.max; } else if (fee < transferFee.min) { fee = transferFee.min; } } return fee; } function calculateExchangeFee(uint weiAmount) external view returns (uint256 weiFee) { /* TODO: to be implemented and use in Exchange.sol. always revert for now */ require(weiAmount != weiAmount, "not yet implemented"); weiFee = transferFee.max; // to silence compiler warnings until it&#39;s implemented } } /* Contract to hold earned interest from loans repaid premiums for locks are being accrued (i.e. transferred) to Locker */ contract InterestEarnedAccount is SystemAccount { constructor(address permissionGranterContract) public SystemAccount(permissionGranterContract) {} // solhint-disable-line no-empty-blocks function transferInterest(AugmintTokenInterface augmintToken, address locker, uint interestAmount) external restrict("MonetarySupervisor") { augmintToken.transfer(locker, interestAmount); } } /* Contract to hold Augmint reserves (ETH & Token) - ETH as regular ETH balance of the contract - ERC20 token reserve (stored as regular Token balance under the contract address) NB: reserves are held under the contract address, therefore any transaction on the reserve is limited to the tx-s defined here (i.e. transfer is not allowed even by the contract owner or StabilityBoard or MonetarySupervisor) */ contract AugmintReserves is SystemAccount { function () public payable { // solhint-disable-line no-empty-blocks // to accept ETH sent into reserve (from defaulted loan&#39;s collateral ) } constructor(address permissionGranterContract) public SystemAccount(permissionGranterContract) {} // solhint-disable-line no-empty-blocks function burn(AugmintTokenInterface augmintToken, uint amount) external restrict("MonetarySupervisor") { augmintToken.burn(amount); } } /* MonetarySupervisor - maintains system wide KPIs (eg totalLockAmount, totalLoanAmount) - holds system wide parameters/limits - enforces system wide limits - burns and issues to AugmintReserves - Send funds from reserve to exchange when intervening (not implemented yet) - Converts older versions of AugmintTokens in 1:1 to new */ contract MonetarySupervisor is Restricted, TokenReceiver { // solhint-disable-line no-empty-blocks using SafeMath for uint256; uint public constant PERCENT_100 = 1000000; AugmintTokenInterface public augmintToken; InterestEarnedAccount public interestEarnedAccount; AugmintReserves public augmintReserves; uint public issuedByStabilityBoard; // token issued by Stability Board uint public totalLoanAmount; // total amount of all loans without interest, in token uint public totalLockedAmount; // total amount of all locks without premium, in token /********** Parameters to ensure totalLoanAmount or totalLockedAmount difference is within limits and system also works when total loan or lock amounts are low. for test calculations: https://docs.google.com/spreadsheets/d/1MeWYPYZRIm1n9lzpvbq8kLfQg1hhvk5oJY6NrR401S0 **********/ struct LtdParams { uint lockDifferenceLimit; /* only allow a new lock if Loan To Deposit ratio would stay above (1 - lockDifferenceLimit) with new lock. Stored as parts per million */ uint loanDifferenceLimit; /* only allow a new loan if Loan To Deposit ratio would stay above (1 + loanDifferenceLimit) with new loan. Stored as parts per million */ /* allowedDifferenceAmount param is to ensure the system is not "freezing" when totalLoanAmount or totalLockAmount is low. It allows a new loan or lock (up to an amount to reach this difference) even if LTD will go below / above lockDifferenceLimit / loanDifferenceLimit with the new lock/loan */ uint allowedDifferenceAmount; } LtdParams public ltdParams; /* Previously deployed AugmintTokens which are accepted for conversion (see transferNotification() ) NB: it&#39;s not iterable so old version addresses needs to be added for UI manually after each deploy */ mapping(address => bool) public acceptedLegacyAugmintTokens; event LtdParamsChanged(uint lockDifferenceLimit, uint loanDifferenceLimit, uint allowedDifferenceAmount); event AcceptedLegacyAugmintTokenChanged(address augmintTokenAddress, bool newAcceptedState); event LegacyTokenConverted(address oldTokenAddress, address account, uint amount); event KPIsAdjusted(uint totalLoanAmountAdjustment, uint totalLockedAmountAdjustment); event SystemContractsChanged(InterestEarnedAccount newInterestEarnedAccount, AugmintReserves newAugmintReserves); constructor(address permissionGranterContract, AugmintTokenInterface _augmintToken, AugmintReserves _augmintReserves, InterestEarnedAccount _interestEarnedAccount, uint lockDifferenceLimit, uint loanDifferenceLimit, uint allowedDifferenceAmount) public Restricted(permissionGranterContract) { augmintToken = _augmintToken; augmintReserves = _augmintReserves; interestEarnedAccount = _interestEarnedAccount; ltdParams = LtdParams(lockDifferenceLimit, loanDifferenceLimit, allowedDifferenceAmount); } function issueToReserve(uint amount) external restrict("StabilityBoard") { issuedByStabilityBoard = issuedByStabilityBoard.add(amount); augmintToken.issueTo(augmintReserves, amount); } function burnFromReserve(uint amount) external restrict("StabilityBoard") { issuedByStabilityBoard = issuedByStabilityBoard.sub(amount); augmintReserves.burn(augmintToken, amount); } /* Locker requesting interest when locking funds. Enforcing LTD to stay within range allowed by LTD params NB: it does not know about min loan amount, it&#39;s the loan contract&#39;s responsibility to enforce it */ function requestInterest(uint amountToLock, uint interestAmount) external { // only whitelisted Locker require(permissions[msg.sender]["Locker"], "msg.sender must have Locker permission"); require(amountToLock <= getMaxLockAmountAllowedByLtd(), "amountToLock must be <= maxLockAmountAllowedByLtd"); totalLockedAmount = totalLockedAmount.add(amountToLock); // next line would revert but require to emit reason: require(augmintToken.balanceOf(address(interestEarnedAccount)) >= interestAmount, "interestEarnedAccount balance must be >= interestAmount"); interestEarnedAccount.transferInterest(augmintToken, msg.sender, interestAmount); // transfer interest to Locker } // Locker notifying when releasing funds to update KPIs function releaseFundsNotification(uint lockedAmount) external { // only whitelisted Locker require(permissions[msg.sender]["Locker"], "msg.sender must have Locker permission"); totalLockedAmount = totalLockedAmount.sub(lockedAmount); } /* Issue loan if LTD stays within range allowed by LTD params NB: it does not know about min loan amount, it&#39;s the loan contract&#39;s responsibility to enforce it */ function issueLoan(address borrower, uint loanAmount) external { // only whitelisted LoanManager contracts require(permissions[msg.sender]["LoanManager"], "msg.sender must have LoanManager permission"); require(loanAmount <= getMaxLoanAmountAllowedByLtd(), "loanAmount must be <= maxLoanAmountAllowedByLtd"); totalLoanAmount = totalLoanAmount.add(loanAmount); augmintToken.issueTo(borrower, loanAmount); } function loanRepaymentNotification(uint loanAmount) external { // only whitelisted LoanManager contracts require(permissions[msg.sender]["LoanManager"], "msg.sender must have LoanManager permission"); totalLoanAmount = totalLoanAmount.sub(loanAmount); } // NB: this is called by Lender contract with the sum of all loans collected in batch function loanCollectionNotification(uint totalLoanAmountCollected) external { // only whitelisted LoanManager contracts require(permissions[msg.sender]["LoanManager"], "msg.sender must have LoanManager permission"); totalLoanAmount = totalLoanAmount.sub(totalLoanAmountCollected); } function setAcceptedLegacyAugmintToken(address legacyAugmintTokenAddress, bool newAcceptedState) external restrict("StabilityBoard") { acceptedLegacyAugmintTokens[legacyAugmintTokenAddress] = newAcceptedState; emit AcceptedLegacyAugmintTokenChanged(legacyAugmintTokenAddress, newAcceptedState); } function setLtdParams(uint lockDifferenceLimit, uint loanDifferenceLimit, uint allowedDifferenceAmount) external restrict("StabilityBoard") { ltdParams = LtdParams(lockDifferenceLimit, loanDifferenceLimit, allowedDifferenceAmount); emit LtdParamsChanged(lockDifferenceLimit, loanDifferenceLimit, allowedDifferenceAmount); } /* function to migrate old totalLoanAmount and totalLockedAmount from old monetarySupervisor contract when it&#39;s upgraded. Set new monetarySupervisor contract in all locker and loanManager contracts before executing this */ function adjustKPIs(uint totalLoanAmountAdjustment, uint totalLockedAmountAdjustment) external restrict("StabilityBoard") { totalLoanAmount = totalLoanAmount.add(totalLoanAmountAdjustment); totalLockedAmount = totalLockedAmount.add(totalLockedAmountAdjustment); emit KPIsAdjusted(totalLoanAmountAdjustment, totalLockedAmountAdjustment); } /* to allow upgrades of InterestEarnedAccount and AugmintReserves contracts. */ function setSystemContracts(InterestEarnedAccount newInterestEarnedAccount, AugmintReserves newAugmintReserves) external restrict("StabilityBoard") { interestEarnedAccount = newInterestEarnedAccount; augmintReserves = newAugmintReserves; emit SystemContractsChanged(newInterestEarnedAccount, newAugmintReserves); } /* User can request to convert their tokens from older AugmintToken versions in 1:1 transferNotification is called from AugmintToken&#39;s transferAndNotify Flow for converting old tokens: 1) user calls old token contract&#39;s transferAndNotify with the amount to convert, addressing the new MonetarySupervisor Contract 2) transferAndNotify transfers user&#39;s old tokens to the current MonetarySupervisor contract&#39;s address 3) transferAndNotify calls MonetarySupervisor.transferNotification 4) MonetarySupervisor checks if old AugmintToken is permitted 5) MonetarySupervisor issues new tokens to user&#39;s account in current AugmintToken 6) MonetarySupervisor burns old tokens from own balance */ function transferNotification(address from, uint amount, uint /* data, not used */ ) external { AugmintTokenInterface legacyToken = AugmintTokenInterface(msg.sender); require(acceptedLegacyAugmintTokens[legacyToken], "msg.sender must be allowed in acceptedLegacyAugmintTokens"); legacyToken.burn(amount); augmintToken.issueTo(from, amount); emit LegacyTokenConverted(msg.sender, from, amount); } function getLoanToDepositRatio() external view returns (uint loanToDepositRatio) { loanToDepositRatio = totalLockedAmount == 0 ? 0 : totalLockedAmount.mul(PERCENT_100).div(totalLoanAmount); } /* Helper function for UI. Returns max lock amount based on minLockAmount, interestPt, using LTD params & interestEarnedAccount balance */ function getMaxLockAmount(uint minLockAmount, uint interestPt) external view returns (uint maxLock) { uint allowedByEarning = augmintToken.balanceOf(address(interestEarnedAccount)).mul(PERCENT_100).div(interestPt); uint allowedByLtd = getMaxLockAmountAllowedByLtd(); maxLock = allowedByEarning < allowedByLtd ? allowedByEarning : allowedByLtd; maxLock = maxLock < minLockAmount ? 0 : maxLock; } /* Helper function for UI. Returns max loan amount based on minLoanAmont using LTD params */ function getMaxLoanAmount(uint minLoanAmount) external view returns (uint maxLoan) { uint allowedByLtd = getMaxLoanAmountAllowedByLtd(); maxLoan = allowedByLtd < minLoanAmount ? 0 : allowedByLtd; } /* returns maximum lockable token amount allowed by LTD params. */ function getMaxLockAmountAllowedByLtd() public view returns(uint maxLockByLtd) { uint allowedByLtdDifferencePt = totalLoanAmount.mul(PERCENT_100).div(PERCENT_100 .sub(ltdParams.lockDifferenceLimit)); allowedByLtdDifferencePt = totalLockedAmount >= allowedByLtdDifferencePt ? 0 : allowedByLtdDifferencePt.sub(totalLockedAmount); uint allowedByLtdDifferenceAmount = totalLockedAmount >= totalLoanAmount.add(ltdParams.allowedDifferenceAmount) ? 0 : totalLoanAmount.add(ltdParams.allowedDifferenceAmount).sub(totalLockedAmount); maxLockByLtd = allowedByLtdDifferencePt > allowedByLtdDifferenceAmount ? allowedByLtdDifferencePt : allowedByLtdDifferenceAmount; } /* returns maximum borrowable token amount allowed by LTD params */ function getMaxLoanAmountAllowedByLtd() public view returns(uint maxLoanByLtd) { uint allowedByLtdDifferencePt = totalLockedAmount.mul(ltdParams.loanDifferenceLimit.add(PERCENT_100)) .div(PERCENT_100); allowedByLtdDifferencePt = totalLoanAmount >= allowedByLtdDifferencePt ? 0 : allowedByLtdDifferencePt.sub(totalLoanAmount); uint allowedByLtdDifferenceAmount = totalLoanAmount >= totalLockedAmount.add(ltdParams.allowedDifferenceAmount) ? 0 : totalLockedAmount.add(ltdParams.allowedDifferenceAmount).sub(totalLoanAmount); maxLoanByLtd = allowedByLtdDifferencePt > allowedByLtdDifferenceAmount ? allowedByLtdDifferencePt : allowedByLtdDifferenceAmount; } } /* Augmint&#39;s Internal Exchange For flows see: https://github.com/Augmint/augmint-contracts/blob/master/docs/exchangeFlow.png TODO: - change to wihtdrawal pattern, see: https://github.com/Augmint/augmint-contracts/issues/17 - deduct fee - consider take funcs (frequent rate changes with takeBuyToken? send more and send back remainder?) - use Rates interface? */ pragma solidity 0.4.24; contract Exchange is Restricted { using SafeMath for uint256; AugmintTokenInterface public augmintToken; Rates public rates; uint public constant CHUNK_SIZE = 100; struct Order { uint64 index; address maker; // % of published current peggedSymbol/ETH rates published by Rates contract. Stored as parts per million // I.e. 1,000,000 = 100% (parity), 990,000 = 1% below parity uint32 price; // buy order: amount in wei // sell order: token amount uint amount; } uint64 public orderCount; mapping(uint64 => Order) public buyTokenOrders; mapping(uint64 => Order) public sellTokenOrders; uint64[] private activeBuyOrders; uint64[] private activeSellOrders; /* used to stop executing matchMultiple when running out of gas. actual is much less, just leaving enough matchMultipleOrders() to finish TODO: fine tune & test it*/ uint32 private constant ORDER_MATCH_WORST_GAS = 100000; event NewOrder(uint64 indexed orderId, address indexed maker, uint32 price, uint tokenAmount, uint weiAmount); event OrderFill(address indexed tokenBuyer, address indexed tokenSeller, uint64 buyTokenOrderId, uint64 sellTokenOrderId, uint publishedRate, uint32 price, uint fillRate, uint weiAmount, uint tokenAmount); event CancelledOrder(uint64 indexed orderId, address indexed maker, uint tokenAmount, uint weiAmount); event RatesContractChanged(Rates newRatesContract); constructor(address permissionGranterContract, AugmintTokenInterface _augmintToken, Rates _rates) public Restricted(permissionGranterContract) { augmintToken = _augmintToken; rates = _rates; } /* to allow upgrade of Rates contract */ function setRatesContract(Rates newRatesContract) external restrict("StabilityBoard") { rates = newRatesContract; emit RatesContractChanged(newRatesContract); } function placeBuyTokenOrder(uint32 price) external payable returns (uint64 orderId) { require(price > 0, "price must be > 0"); require(msg.value > 0, "msg.value must be > 0"); orderId = ++orderCount; buyTokenOrders[orderId] = Order(uint64(activeBuyOrders.length), msg.sender, price, msg.value); activeBuyOrders.push(orderId); emit NewOrder(orderId, msg.sender, price, 0, msg.value); } /* this function requires previous approval to transfer tokens */ function placeSellTokenOrder(uint32 price, uint tokenAmount) external returns (uint orderId) { augmintToken.transferFrom(msg.sender, this, tokenAmount); return _placeSellTokenOrder(msg.sender, price, tokenAmount); } /* place sell token order called from AugmintToken&#39;s transferAndNotify Flow: 1) user calls token contract&#39;s transferAndNotify price passed in data arg 2) transferAndNotify transfers tokens to the Exchange contract 3) transferAndNotify calls Exchange.transferNotification with lockProductId */ function transferNotification(address maker, uint tokenAmount, uint price) external { require(msg.sender == address(augmintToken), "msg.sender must be augmintToken"); _placeSellTokenOrder(maker, uint32(price), tokenAmount); } function cancelBuyTokenOrder(uint64 buyTokenId) external { Order storage order = buyTokenOrders[buyTokenId]; require(order.maker == msg.sender, "msg.sender must be order.maker"); require(order.amount > 0, "buy order already removed"); uint amount = order.amount; order.amount = 0; _removeBuyOrder(order); msg.sender.transfer(amount); emit CancelledOrder(buyTokenId, msg.sender, 0, amount); } function cancelSellTokenOrder(uint64 sellTokenId) external { Order storage order = sellTokenOrders[sellTokenId]; require(order.maker == msg.sender, "msg.sender must be order.maker"); require(order.amount > 0, "sell order already removed"); uint amount = order.amount; order.amount = 0; _removeSellOrder(order); augmintToken.transferWithNarrative(msg.sender, amount, "Sell token order cancelled"); emit CancelledOrder(sellTokenId, msg.sender, amount, 0); } /* matches any two orders if the sell price >= buy price trade price is the price of the maker (the order placed earlier) reverts if any of the orders have been removed */ function matchOrders(uint64 buyTokenId, uint64 sellTokenId) external { require(_fillOrder(buyTokenId, sellTokenId), "fill order failed"); } /* matches as many orders as possible from the passed orders Runs as long as gas is available for the call. Reverts if any match is invalid (e.g sell price > buy price) Skips match if any of the matched orders is removed / already filled (i.e. amount = 0) */ function matchMultipleOrders(uint64[] buyTokenIds, uint64[] sellTokenIds) external returns(uint matchCount) { uint len = buyTokenIds.length; require(len == sellTokenIds.length, "buyTokenIds and sellTokenIds lengths must be equal"); for (uint i = 0; i < len && gasleft() > ORDER_MATCH_WORST_GAS; i++) { if(_fillOrder(buyTokenIds[i], sellTokenIds[i])) { matchCount++; } } } function getActiveOrderCounts() external view returns(uint buyTokenOrderCount, uint sellTokenOrderCount) { return(activeBuyOrders.length, activeSellOrders.length); } // returns CHUNK_SIZE orders starting from offset // orders are encoded as [id, maker, price, amount] function getActiveBuyOrders(uint offset) external view returns (uint[4][CHUNK_SIZE] response) { for (uint8 i = 0; i < CHUNK_SIZE && i + offset < activeBuyOrders.length; i++) { uint64 orderId = activeBuyOrders[offset + i]; Order storage order = buyTokenOrders[orderId]; response[i] = [orderId, uint(order.maker), order.price, order.amount]; } } function getActiveSellOrders(uint offset) external view returns (uint[4][CHUNK_SIZE] response) { for (uint8 i = 0; i < CHUNK_SIZE && i + offset < activeSellOrders.length; i++) { uint64 orderId = activeSellOrders[offset + i]; Order storage order = sellTokenOrders[orderId]; response[i] = [orderId, uint(order.maker), order.price, order.amount]; } } function _fillOrder(uint64 buyTokenId, uint64 sellTokenId) private returns(bool success) { Order storage buy = buyTokenOrders[buyTokenId]; Order storage sell = sellTokenOrders[sellTokenId]; if( buy.amount == 0 || sell.amount == 0 ) { return false; // one order is already filled and removed. // we let matchMultiple continue, indivudal match will revert } require(buy.price >= sell.price, "buy price must be >= sell price"); // pick maker&#39;s price (whoever placed order sooner considered as maker) uint32 price = buyTokenId > sellTokenId ? sell.price : buy.price; uint publishedRate; (publishedRate, ) = rates.rates(augmintToken.peggedSymbol()); uint fillRate = publishedRate.mul(price).roundedDiv(1000000); uint sellWei = sell.amount.mul(1 ether).roundedDiv(fillRate); uint tradedWei; uint tradedTokens; if (sellWei <= buy.amount) { tradedWei = sellWei; tradedTokens = sell.amount; } else { tradedWei = buy.amount; tradedTokens = buy.amount.mul(fillRate).roundedDiv(1 ether); } buy.amount = buy.amount.sub(tradedWei); if (buy.amount == 0) { _removeBuyOrder(buy); } sell.amount = sell.amount.sub(tradedTokens); if (sell.amount == 0) { _removeSellOrder(sell); } augmintToken.transferWithNarrative(buy.maker, tradedTokens, "Buy token order fill"); sell.maker.transfer(tradedWei); emit OrderFill(buy.maker, sell.maker, buyTokenId, sellTokenId, publishedRate, price, fillRate, tradedWei, tradedTokens); return true; } function _placeSellTokenOrder(address maker, uint32 price, uint tokenAmount) private returns (uint64 orderId) { require(price > 0, "price must be > 0"); require(tokenAmount > 0, "tokenAmount must be > 0"); orderId = ++orderCount; sellTokenOrders[orderId] = Order(uint64(activeSellOrders.length), maker, price, tokenAmount); activeSellOrders.push(orderId); emit NewOrder(orderId, maker, price, tokenAmount, 0); } function _removeBuyOrder(Order storage order) private { _removeOrder(activeBuyOrders, order.index); } function _removeSellOrder(Order storage order) private { _removeOrder(activeSellOrders, order.index); } function _removeOrder(uint64[] storage orders, uint64 index) private { if (index < orders.length - 1) { orders[index] = orders[orders.length - 1]; } orders.length--; } } /* Augmint Crypto Euro token (A-EUR) implementation */ contract TokenAEur is AugmintToken { constructor(address _permissionGranterContract, TransferFeeInterface _feeAccount) public AugmintToken(_permissionGranterContract, "Augmint Crypto Euro", "AEUR", "EUR", 2, _feeAccount) {} // solhint-disable-line no-empty-blocks } /* Contract to manage Augmint token loan contracts backed by ETH For flows see: https://github.com/Augmint/augmint-contracts/blob/master/docs/loanFlow.png TODO: - create MonetarySupervisor interface and use it instead? - make data arg generic bytes? - make collect() run as long as gas provided allows */ contract LoanManager is Restricted { using SafeMath for uint256; uint16 public constant CHUNK_SIZE = 100; enum LoanState { Open, Repaid, Defaulted, Collected } // NB: Defaulted state is not stored, only getters calculate struct LoanProduct { uint minDisbursedAmount; // 0: with decimals set in AugmintToken.decimals uint32 term; // 1 uint32 discountRate; // 2: discountRate in parts per million , ie. 10,000 = 1% uint32 collateralRatio; // 3: loan token amount / colleteral pegged ccy value // in parts per million , ie. 10,000 = 1% uint32 defaultingFeePt; // 4: % of collateral in parts per million , ie. 50,000 = 5% bool isActive; // 5 } /* NB: we don&#39;t need to store loan parameters because loan products can&#39;t be altered (only disabled/enabled) */ struct LoanData { uint collateralAmount; // 0 uint repaymentAmount; // 1 address borrower; // 2 uint32 productId; // 3 LoanState state; // 4 uint40 maturity; // 5 } LoanProduct[] public products; LoanData[] public loans; mapping(address => uint[]) public accountLoans; // owner account address => array of loan Ids Rates public rates; // instance of ETH/pegged currency rate provider contract AugmintTokenInterface public augmintToken; // instance of token contract MonetarySupervisor public monetarySupervisor; event NewLoan(uint32 productId, uint loanId, address indexed borrower, uint collateralAmount, uint loanAmount, uint repaymentAmount, uint40 maturity); event LoanProductActiveStateChanged(uint32 productId, bool newState); event LoanProductAdded(uint32 productId); event LoanRepayed(uint loanId, address borrower); event LoanCollected(uint loanId, address indexed borrower, uint collectedCollateral, uint releasedCollateral, uint defaultingFee); event SystemContractsChanged(Rates newRatesContract, MonetarySupervisor newMonetarySupervisor); constructor(address permissionGranterContract, AugmintTokenInterface _augmintToken, MonetarySupervisor _monetarySupervisor, Rates _rates) public Restricted(permissionGranterContract) { augmintToken = _augmintToken; monetarySupervisor = _monetarySupervisor; rates = _rates; } function addLoanProduct(uint32 term, uint32 discountRate, uint32 collateralRatio, uint minDisbursedAmount, uint32 defaultingFeePt, bool isActive) external restrict("StabilityBoard") { uint _newProductId = products.push( LoanProduct(minDisbursedAmount, term, discountRate, collateralRatio, defaultingFeePt, isActive) ) - 1; uint32 newProductId = uint32(_newProductId); require(newProductId == _newProductId, "productId overflow"); emit LoanProductAdded(newProductId); } function setLoanProductActiveState(uint32 productId, bool newState) external restrict ("StabilityBoard") { require(productId < products.length, "invalid productId"); // next line would revert but require to emit reason products[productId].isActive = false; emit LoanProductActiveStateChanged(productId, newState); } function newEthBackedLoan(uint32 productId) external payable { require(productId < products.length, "invalid productId"); // next line would revert but require to emit reason LoanProduct storage product = products[productId]; require(product.isActive, "product must be in active state"); // valid product // calculate loan values based on ETH sent in with Tx uint tokenValue = rates.convertFromWei(augmintToken.peggedSymbol(), msg.value); uint repaymentAmount = tokenValue.mul(product.collateralRatio).div(1000000); uint loanAmount; (loanAmount, ) = calculateLoanValues(product, repaymentAmount); require(loanAmount >= product.minDisbursedAmount, "loanAmount must be >= minDisbursedAmount"); uint expiration = now.add(product.term); uint40 maturity = uint40(expiration); require(maturity == expiration, "maturity overflow"); // Create new loan uint loanId = loans.push(LoanData(msg.value, repaymentAmount, msg.sender, productId, LoanState.Open, maturity)) - 1; // Store ref to new loan accountLoans[msg.sender].push(loanId); // Issue tokens and send to borrower monetarySupervisor.issueLoan(msg.sender, loanAmount); emit NewLoan(productId, loanId, msg.sender, msg.value, loanAmount, repaymentAmount, maturity); } /* repay loan, called from AugmintToken&#39;s transferAndNotify Flow for repaying loan: 1) user calls token contract&#39;s transferAndNotify loanId passed in data arg 2) transferAndNotify transfers tokens to the Lender contract 3) transferAndNotify calls Lender.transferNotification with lockProductId */ // from arg is not used as we allow anyone to repay a loan: function transferNotification(address, uint repaymentAmount, uint loanId) external { require(msg.sender == address(augmintToken), "msg.sender must be augmintToken"); _repayLoan(loanId, repaymentAmount); } function collect(uint[] loanIds) external { /* when there are a lots of loans to be collected then the client need to call it in batches to make sure tx won&#39;t exceed block gas limit. Anyone can call it - can&#39;t cause harm as it only allows to collect loans which they are defaulted TODO: optimise defaulting fee calculations */ uint totalLoanAmountCollected; uint totalCollateralToCollect; uint totalDefaultingFee; for (uint i = 0; i < loanIds.length; i++) { require(i < loans.length, "invalid loanId"); // next line would revert but require to emit reason LoanData storage loan = loans[loanIds[i]]; require(loan.state == LoanState.Open, "loan state must be Open"); require(now >= loan.maturity, "current time must be later than maturity"); LoanProduct storage product = products[loan.productId]; uint loanAmount; (loanAmount, ) = calculateLoanValues(product, loan.repaymentAmount); totalLoanAmountCollected = totalLoanAmountCollected.add(loanAmount); loan.state = LoanState.Collected; // send ETH collateral to augmintToken reserve uint defaultingFeeInToken = loan.repaymentAmount.mul(product.defaultingFeePt).div(1000000); uint defaultingFee = rates.convertToWei(augmintToken.peggedSymbol(), defaultingFeeInToken); uint targetCollection = rates.convertToWei(augmintToken.peggedSymbol(), loan.repaymentAmount).add(defaultingFee); uint releasedCollateral; if (targetCollection < loan.collateralAmount) { releasedCollateral = loan.collateralAmount.sub(targetCollection); loan.borrower.transfer(releasedCollateral); } uint collateralToCollect = loan.collateralAmount.sub(releasedCollateral); if (defaultingFee >= collateralToCollect) { defaultingFee = collateralToCollect; collateralToCollect = 0; } else { collateralToCollect = collateralToCollect.sub(defaultingFee); } totalDefaultingFee = totalDefaultingFee.add(defaultingFee); totalCollateralToCollect = totalCollateralToCollect.add(collateralToCollect); emit LoanCollected(loanIds[i], loan.borrower, collateralToCollect.add(defaultingFee), releasedCollateral, defaultingFee); } if (totalCollateralToCollect > 0) { address(monetarySupervisor.augmintReserves()).transfer(totalCollateralToCollect); } if (totalDefaultingFee > 0){ address(augmintToken.feeAccount()).transfer(totalDefaultingFee); } monetarySupervisor.loanCollectionNotification(totalLoanAmountCollected);// update KPIs } /* to allow upgrade of Rates and MonetarySupervisor contracts */ function setSystemContracts(Rates newRatesContract, MonetarySupervisor newMonetarySupervisor) external restrict("StabilityBoard") { rates = newRatesContract; monetarySupervisor = newMonetarySupervisor; emit SystemContractsChanged(newRatesContract, newMonetarySupervisor); } function getProductCount() external view returns (uint ct) { return products.length; } // returns CHUNK_SIZE loan products starting from some offset: // [ productId, minDisbursedAmount, term, discountRate, collateralRatio, defaultingFeePt, maxLoanAmount, isActive ] function getProducts(uint offset) external view returns (uint[8][CHUNK_SIZE] response) { for (uint16 i = 0; i < CHUNK_SIZE; i++) { if (offset + i >= products.length) { break; } LoanProduct storage product = products[offset + i]; response[i] = [offset + i, product.minDisbursedAmount, product.term, product.discountRate, product.collateralRatio, product.defaultingFeePt, monetarySupervisor.getMaxLoanAmount(product.minDisbursedAmount), product.isActive ? 1 : 0 ]; } } function getLoanCount() external view returns (uint ct) { return loans.length; } /* returns CHUNK_SIZE loans starting from some offset. Loans data encoded as: [loanId, collateralAmount, repaymentAmount, borrower, productId, state, maturity, disbursementTime, loanAmount, interestAmount ] */ function getLoans(uint offset) external view returns (uint[10][CHUNK_SIZE] response) { for (uint16 i = 0; i < CHUNK_SIZE; i++) { if (offset + i >= loans.length) { break; } response[i] = getLoanTuple(offset + i); } } function getLoanCountForAddress(address borrower) external view returns (uint) { return accountLoans[borrower].length; } /* returns CHUNK_SIZE loans of a given account, starting from some offset. Loans data encoded as: [loanId, collateralAmount, repaymentAmount, borrower, productId, state, maturity, disbursementTime, loanAmount, interestAmount ] */ function getLoansForAddress(address borrower, uint offset) external view returns (uint[10][CHUNK_SIZE] response) { uint[] storage loansForAddress = accountLoans[borrower]; for (uint16 i = 0; i < CHUNK_SIZE; i++) { if (offset + i >= loansForAddress.length) { break; } response[i] = getLoanTuple(loansForAddress[offset + i]); } } function getLoanTuple(uint loanId) public view returns (uint[10] result) { require(loanId < loans.length, "invalid loanId"); // next line would revert but require to emit reason LoanData storage loan = loans[loanId]; LoanProduct storage product = products[loan.productId]; uint loanAmount; uint interestAmount; (loanAmount, interestAmount) = calculateLoanValues(product, loan.repaymentAmount); uint disbursementTime = loan.maturity - product.term; LoanState loanState = loan.state == LoanState.Open && now >= loan.maturity ? LoanState.Defaulted : loan.state; result = [loanId, loan.collateralAmount, loan.repaymentAmount, uint(loan.borrower), loan.productId, uint(loanState), loan.maturity, disbursementTime, loanAmount, interestAmount]; } function calculateLoanValues(LoanProduct storage product, uint repaymentAmount) internal view returns (uint loanAmount, uint interestAmount) { // calculate loan values based on repayment amount loanAmount = repaymentAmount.mul(product.discountRate).div(1000000); interestAmount = loanAmount > repaymentAmount ? 0 : repaymentAmount.sub(loanAmount); } /* internal function, assuming repayment amount already transfered */ function _repayLoan(uint loanId, uint repaymentAmount) internal { require(loanId < loans.length, "invalid loanId"); // next line would revert but require to emit reason LoanData storage loan = loans[loanId]; require(loan.state == LoanState.Open, "loan state must be Open"); require(repaymentAmount == loan.repaymentAmount, "repaymentAmount must be equal to tokens sent"); require(now <= loan.maturity, "current time must be earlier than maturity"); LoanProduct storage product = products[loan.productId]; uint loanAmount; uint interestAmount; (loanAmount, interestAmount) = calculateLoanValues(product, loan.repaymentAmount); loans[loanId].state = LoanState.Repaid; if (interestAmount > 0) { augmintToken.transfer(monetarySupervisor.interestEarnedAccount(), interestAmount); augmintToken.burn(loanAmount); } else { // negative or zero interest (i.e. discountRate >= 0) augmintToken.burn(repaymentAmount); } monetarySupervisor.loanRepaymentNotification(loanAmount); // update KPIs loan.borrower.transfer(loan.collateralAmount); // send back ETH collateral emit LoanRepayed(loanId, loan.borrower); } } /* contract for tracking locked funds requirements -> lock funds -> unlock funds -> index locks by address For flows see: https://github.com/Augmint/augmint-contracts/blob/master/docs/lockFlow.png TODO / think about: -> self-destruct function? */ contract Locker is Restricted, TokenReceiver { using SafeMath for uint256; uint public constant CHUNK_SIZE = 100; event NewLockProduct(uint32 indexed lockProductId, uint32 perTermInterest, uint32 durationInSecs, uint32 minimumLockAmount, bool isActive); event LockProductActiveChange(uint32 indexed lockProductId, bool newActiveState); // NB: amountLocked includes the original amount, plus interest event NewLock(address indexed lockOwner, uint lockId, uint amountLocked, uint interestEarned, uint40 lockedUntil, uint32 perTermInterest, uint32 durationInSecs); event LockReleased(address indexed lockOwner, uint lockId); event MonetarySupervisorChanged(MonetarySupervisor newMonetarySupervisor); struct LockProduct { // perTermInterest is in millionths (i.e. 1,000,000 = 100%): uint32 perTermInterest; uint32 durationInSecs; uint32 minimumLockAmount; bool isActive; } /* NB: we don&#39;t need to store lock parameters because lockProducts can&#39;t be altered (only disabled/enabled) */ struct Lock { uint amountLocked; address owner; uint32 productId; uint40 lockedUntil; bool isActive; } AugmintTokenInterface public augmintToken; MonetarySupervisor public monetarySupervisor; LockProduct[] public lockProducts; Lock[] public locks; // lock ids for an account mapping(address => uint[]) public accountLocks; constructor(address permissionGranterContract, AugmintTokenInterface _augmintToken, MonetarySupervisor _monetarySupervisor) public Restricted(permissionGranterContract) { augmintToken = _augmintToken; monetarySupervisor = _monetarySupervisor; } function addLockProduct(uint32 perTermInterest, uint32 durationInSecs, uint32 minimumLockAmount, bool isActive) external restrict("StabilityBoard") { uint _newLockProductId = lockProducts.push( LockProduct(perTermInterest, durationInSecs, minimumLockAmount, isActive)) - 1; uint32 newLockProductId = uint32(_newLockProductId); require(newLockProductId == _newLockProductId, "lockProduct overflow"); emit NewLockProduct(newLockProductId, perTermInterest, durationInSecs, minimumLockAmount, isActive); } function setLockProductActiveState(uint32 lockProductId, bool isActive) external restrict("StabilityBoard") { // next line would revert but require to emit reason: require(lockProductId < lockProducts.length, "invalid lockProductId"); lockProducts[lockProductId].isActive = isActive; emit LockProductActiveChange(lockProductId, isActive); } /* lock funds, called from AugmintToken&#39;s transferAndNotify Flow for locking tokens: 1) user calls token contract&#39;s transferAndNotify lockProductId passed in data arg 2) transferAndNotify transfers tokens to the Lock contract 3) transferAndNotify calls Lock.transferNotification with lockProductId */ function transferNotification(address from, uint256 amountToLock, uint _lockProductId) external { require(msg.sender == address(augmintToken), "msg.sender must be augmintToken"); // next line would revert but require to emit reason: require(lockProductId < lockProducts.length, "invalid lockProductId"); uint32 lockProductId = uint32(_lockProductId); require(lockProductId == _lockProductId, "lockProductId overflow"); /* TODO: make data arg generic bytes uint productId; assembly { // solhint-disable-line no-inline-assembly productId := mload(data) } */ _createLock(lockProductId, from, amountToLock); } function releaseFunds(uint lockId) external { // next line would revert but require to emit reason: require(lockId < locks.length, "invalid lockId"); Lock storage lock = locks[lockId]; LockProduct storage lockProduct = lockProducts[lock.productId]; require(lock.isActive, "lock must be in active state"); require(now >= lock.lockedUntil, "current time must be later than lockedUntil"); lock.isActive = false; uint interestEarned = calculateInterest(lockProduct.perTermInterest, lock.amountLocked); monetarySupervisor.releaseFundsNotification(lock.amountLocked); // to maintain totalLockAmount augmintToken.transferWithNarrative(lock.owner, lock.amountLocked.add(interestEarned), "Funds released from lock"); emit LockReleased(lock.owner, lockId); } function setMonetarySupervisor(MonetarySupervisor newMonetarySupervisor) external restrict("StabilityBoard") { monetarySupervisor = newMonetarySupervisor; emit MonetarySupervisorChanged(newMonetarySupervisor); } function getLockProductCount() external view returns (uint) { return lockProducts.length; } // returns 20 lock products starting from some offset // lock products are encoded as [ perTermInterest, durationInSecs, minimumLockAmount, maxLockAmount, isActive ] function getLockProducts(uint offset) external view returns (uint[5][CHUNK_SIZE] response) { for (uint8 i = 0; i < CHUNK_SIZE; i++) { if (offset + i >= lockProducts.length) { break; } LockProduct storage lockProduct = lockProducts[offset + i]; response[i] = [ lockProduct.perTermInterest, lockProduct.durationInSecs, lockProduct.minimumLockAmount, monetarySupervisor.getMaxLockAmount(lockProduct.minimumLockAmount, lockProduct.perTermInterest), lockProduct.isActive ? 1 : 0 ]; } } function getLockCount() external view returns (uint) { return locks.length; } function getLockCountForAddress(address lockOwner) external view returns (uint) { return accountLocks[lockOwner].length; } // returns CHUNK_SIZE locks starting from some offset // lock products are encoded as // [lockId, owner, amountLocked, interestEarned, lockedUntil, perTermInterest, durationInSecs, isActive ] // NB: perTermInterest is in millionths (i.e. 1,000,000 = 100%): function getLocks(uint offset) external view returns (uint[8][CHUNK_SIZE] response) { for (uint16 i = 0; i < CHUNK_SIZE; i++) { if (offset + i >= locks.length) { break; } Lock storage lock = locks[offset + i]; LockProduct storage lockProduct = lockProducts[lock.productId]; uint interestEarned = calculateInterest(lockProduct.perTermInterest, lock.amountLocked); response[i] = [uint(offset + i), uint(lock.owner), lock.amountLocked, interestEarned, lock.lockedUntil, lockProduct.perTermInterest, lockProduct.durationInSecs, lock.isActive ? 1 : 0]; } } // returns CHUNK_SIZE locks of a given account, starting from some offset // lock products are encoded as // [lockId, amountLocked, interestEarned, lockedUntil, perTermInterest, durationInSecs, isActive ] function getLocksForAddress(address lockOwner, uint offset) external view returns (uint[7][CHUNK_SIZE] response) { uint[] storage locksForAddress = accountLocks[lockOwner]; for (uint16 i = 0; i < CHUNK_SIZE; i++) { if (offset + i >= locksForAddress.length) { break; } Lock storage lock = locks[locksForAddress[offset + i]]; LockProduct storage lockProduct = lockProducts[lock.productId]; uint interestEarned = calculateInterest(lockProduct.perTermInterest, lock.amountLocked); response[i] = [ locksForAddress[offset + i], lock.amountLocked, interestEarned, lock.lockedUntil, lockProduct.perTermInterest, lockProduct.durationInSecs, lock.isActive ? 1 : 0 ]; } } function calculateInterest(uint32 perTermInterest, uint amountToLock) public pure returns (uint interestEarned) { interestEarned = amountToLock.mul(perTermInterest).div(1000000); } // Internal function. assumes amountToLock is already transferred to this Lock contract function _createLock(uint32 lockProductId, address lockOwner, uint amountToLock) internal returns(uint lockId) { LockProduct storage lockProduct = lockProducts[lockProductId]; require(lockProduct.isActive, "lockProduct must be in active state"); require(amountToLock >= lockProduct.minimumLockAmount, "amountToLock must be >= minimumLockAmount"); uint interestEarned = calculateInterest(lockProduct.perTermInterest, amountToLock); uint expiration = now.add(lockProduct.durationInSecs); uint40 lockedUntil = uint40(expiration); require(lockedUntil == expiration, "lockedUntil overflow"); lockId = locks.push(Lock(amountToLock, lockOwner, lockProductId, lockedUntil, true)) - 1; accountLocks[lockOwner].push(lockId); monetarySupervisor.requestInterest(amountToLock, interestEarned); // update KPIs & transfer interest here emit NewLock(lockOwner, lockId, amountToLock, interestEarned, lockedUntil, lockProduct.perTermInterest, lockProduct.durationInSecs); } }
returns CHUNK_SIZE loan products starting from some offset: [ productId, minDisbursedAmount, term, discountRate, collateralRatio, defaultingFeePt, maxLoanAmount, isActive ]
function getProducts(uint offset) external view returns (uint[8][CHUNK_SIZE] response) { for (uint16 i = 0; i < CHUNK_SIZE; i++) { LoanProduct storage product = products[offset + i]; response[i] = [offset + i, product.minDisbursedAmount, product.term, product.discountRate, product.collateralRatio, product.defaultingFeePt, monetarySupervisor.getMaxLoanAmount(product.minDisbursedAmount), product.isActive ? 1 : 0 ]; } }
7,655,389
// Copyright (C) 2021 Argent Labs Ltd. <https://argent.xyz> // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. // SPDX-License-Identifier: GPL-3.0-only pragma solidity ^0.8.3; import "./IFilter.sol"; abstract contract BaseFilter is IFilter { function getMethod(bytes memory _data) internal pure returns (bytes4 method) { // solhint-disable-next-line no-inline-assembly assembly { method := mload(add(_data, 0x20)) } } } // Copyright (C) 2021 Argent Labs Ltd. <https://argent.xyz> // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. // SPDX-License-Identifier: GPL-3.0-only pragma solidity ^0.8.3; interface IFilter { function isValid(address _wallet, address _spender, address _to, bytes calldata _data) external view returns (bool valid); } // Copyright (C) 2021 Argent Labs Ltd. <https://argent.xyz> // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. // SPDX-License-Identifier: GPL-3.0-only pragma solidity ^0.8.3; import "./BaseFilter.sol"; contract UniswapV2UniZapFilter is BaseFilter { bytes4 private constant ERC20_APPROVE = bytes4(keccak256("approve(address,uint256)")); bytes4 constant internal ADD_LIQUIDITY_WITH_ETH = bytes4(keccak256("swapExactETHAndAddLiquidity(address,uint256,address,uint256)")); bytes4 constant internal REMOVE_LIQUIDITY_TO_ETH = bytes4(keccak256("removeLiquidityAndSwapToETH(address,uint256,uint256,address,uint256)")); bytes4 constant internal ADD_LIQUIDITY_WITH_TOKEN = bytes4( keccak256( "swapExactTokensAndAddLiquidity(address,address,uint256,uint256,address,uint256)" ) ); bytes4 constant internal REMOVE_LIQUIDITY_TO_TOKEN = bytes4( keccak256( "removeLiquidityAndSwapToToken(address,address,uint256,uint256,address,uint256)" ) ); // Token registry address public immutable tokenRegistry; // Uniswap V2 factory address public immutable uniFactory; // Uniswap v2 pair init code bytes32 public immutable uniInitCode; // WETH address address public immutable weth; constructor (address _tokenRegistry, address _uniFactory, bytes32 _uniInitCode, address _weth) { tokenRegistry = _tokenRegistry; uniFactory = _uniFactory; uniInitCode = _uniInitCode; weth = _weth; } function isValid(address _wallet, address _spender, address _to, bytes calldata _data) external view override returns (bool valid) { // not needed but detects failure early if (_data.length < 4) { return false; } bytes4 method = getMethod(_data); // UniZap method: check that pair is valid and recipient is the wallet if (_spender == _to) { if (method == ADD_LIQUIDITY_WITH_TOKEN || method == REMOVE_LIQUIDITY_TO_TOKEN) { (address tokenA, address tokenB, , , address recipient) = abi.decode(_data[4:], (address, address, uint256, uint256, address)); return isValidPair(tokenA, tokenB) && recipient == _wallet; } if (method == ADD_LIQUIDITY_WITH_ETH) { (address token, , address recipient) = abi.decode(_data[4:], (address, uint256, address)); return isValidPair(token, weth) && recipient == _wallet; } if (method == REMOVE_LIQUIDITY_TO_ETH) { (address token, , , address recipient) = abi.decode(_data[4:], (address, uint256, uint256, address)); return isValidPair(token, weth) && recipient == _wallet; } // ERC20 methods } else { // only allow approve return (method == ERC20_APPROVE); } } function isValidPair(address _tokenA, address _tokenB) internal view returns (bool) { address pair = pairFor(_tokenA, _tokenB); (bool success, bytes memory res) = tokenRegistry.staticcall(abi.encodeWithSignature("isTokenTradable(address)", pair)); return success && abi.decode(res, (bool)); } function pairFor(address _tokenA, address _tokenB) internal view returns (address) { (address token0, address token1) = _tokenA < _tokenB ? (_tokenA, _tokenB) : (_tokenB, _tokenA); return(address(uint160(uint256(keccak256(abi.encodePacked( hex"ff", uniFactory, keccak256(abi.encodePacked(token0, token1)), uniInitCode )))))); } }
not needed but detects failure early UniZap method: check that pair is valid and recipient is the wallet
function isValid(address _wallet, address _spender, address _to, bytes calldata _data) external view override returns (bool valid) { if (_data.length < 4) { return false; } bytes4 method = getMethod(_data); if (_spender == _to) { if (method == ADD_LIQUIDITY_WITH_TOKEN || method == REMOVE_LIQUIDITY_TO_TOKEN) { (address tokenA, address tokenB, , , address recipient) = abi.decode(_data[4:], (address, address, uint256, uint256, address)); return isValidPair(tokenA, tokenB) && recipient == _wallet; } if (method == ADD_LIQUIDITY_WITH_ETH) { (address token, , address recipient) = abi.decode(_data[4:], (address, uint256, address)); return isValidPair(token, weth) && recipient == _wallet; } if (method == REMOVE_LIQUIDITY_TO_ETH) { (address token, , , address recipient) = abi.decode(_data[4:], (address, uint256, uint256, address)); return isValidPair(token, weth) && recipient == _wallet; } } }
10,058,156
pragma solidity ^0.5.2; import "../node_modules/solidity-bytes-utils/contracts/BytesUtils.sol"; library NodePtr { // Unpack first byte index function ixs(uint self) internal pure returns (uint) { return uint80(self); } // Unpack first content byte index function ixf(uint self) internal pure returns (uint) { return uint80(self>>80); } // Unpack last content byte index function ixl(uint self) internal pure returns (uint) { return uint80(self>>160); } // Pack 3 uint80s into a uint256 function getPtr(uint _ixs, uint _ixf, uint _ixl) internal pure returns (uint) { _ixs |= _ixf<<80; _ixs |= _ixl<<160; return _ixs; } } library Asn1Decode { using NodePtr for uint; using BytesUtils for bytes; /* * @dev Get the root node. First step in traversing an ASN1 structure * @param der The DER-encoded ASN1 structure * @return A pointer to the outermost node */ function root(bytes memory der) internal pure returns (uint) { return readNodeLength(der, 0); } /* * @dev Get the root node of an ASN1 structure that's within a bit string value * @param der The DER-encoded ASN1 structure * @return A pointer to the outermost node */ function rootOfBitStringAt(bytes memory der, uint ptr) internal pure returns (uint) { require(der[ptr.ixs()] == 0x03, "Not type BIT STRING"); return readNodeLength(der, ptr.ixf()+1); } /* * @dev Get the root node of an ASN1 structure that's within an octet string value * @param der The DER-encoded ASN1 structure * @return A pointer to the outermost node */ function rootOfOctetStringAt(bytes memory der, uint ptr) internal pure returns (uint) { require(der[ptr.ixs()] == 0x04, "Not type OCTET STRING"); return readNodeLength(der, ptr.ixf()); } /* * @dev Get the next sibling node * @param der The DER-encoded ASN1 structure * @param ptr Points to the indices of the current node * @return A pointer to the next sibling node */ function nextSiblingOf(bytes memory der, uint ptr) internal pure returns (uint) { return readNodeLength(der, ptr.ixl()+1); } /* * @dev Get the first child node of the current node * @param der The DER-encoded ASN1 structure * @param ptr Points to the indices of the current node * @return A pointer to the first child node */ function firstChildOf(bytes memory der, uint ptr) internal pure returns (uint) { require(der[ptr.ixs()] & 0x20 == 0x20, "Not a constructed type"); return readNodeLength(der, ptr.ixf()); } /* * @dev Use for looping through children of a node (either i or j). * @param i Pointer to an ASN1 node * @param j Pointer to another ASN1 node of the same ASN1 structure * @return True iff j is child of i or i is child of j. */ function isChildOf(uint i, uint j) internal pure returns (bool) { return ( ((i.ixf() <= j.ixs()) && (j.ixl() <= i.ixl())) || ((j.ixf() <= i.ixs()) && (i.ixl() <= j.ixl())) ); } /* * @dev Extract value of node from DER-encoded structure * @param der The der-encoded ASN1 structure * @param ptr Points to the indices of the current node * @return Value bytes of node */ function bytesAt(bytes memory der, uint ptr) internal pure returns (bytes memory) { return der.substring(ptr.ixf(), ptr.ixl()+1 - ptr.ixf()); } /* * @dev Extract entire node from DER-encoded structure * @param der The DER-encoded ASN1 structure * @param ptr Points to the indices of the current node * @return All bytes of node */ function allBytesAt(bytes memory der, uint ptr) internal pure returns (bytes memory) { return der.substring(ptr.ixs(), ptr.ixl()+1 - ptr.ixs()); } /* * @dev Extract value of node from DER-encoded structure * @param der The DER-encoded ASN1 structure * @param ptr Points to the indices of the current node * @return Value bytes of node as bytes32 */ function bytes32At(bytes memory der, uint ptr) internal pure returns (bytes32) { return der.readBytesN(ptr.ixf(), ptr.ixl()+1 - ptr.ixf()); } /* * @dev Extract value of node from DER-encoded structure * @param der The der-encoded ASN1 structure * @param ptr Points to the indices of the current node * @return Uint value of node */ function uintAt(bytes memory der, uint ptr) internal pure returns (uint) { require(der[ptr.ixs()] == 0x02, "Not type INTEGER"); require(der[ptr.ixf()] & 0x80 == 0, "Not positive"); uint len = ptr.ixl()+1 - ptr.ixf(); return uint(der.readBytesN(ptr.ixf(), len) >> (32-len)*8); } /* * @dev Extract value of a positive integer node from DER-encoded structure * @param der The DER-encoded ASN1 structure * @param ptr Points to the indices of the current node * @return Value bytes of a positive integer node */ function uintBytesAt(bytes memory der, uint ptr) internal pure returns (bytes memory) { require(der[ptr.ixs()] == 0x02, "Not type INTEGER"); require(der[ptr.ixf()] & 0x80 == 0, "Not positive"); uint valueLength = ptr.ixl()+1 - ptr.ixf(); if (der[ptr.ixf()] == 0) return der.substring(ptr.ixf()+1, valueLength-1); else return der.substring(ptr.ixf(), valueLength); } function keccakOfBytesAt(bytes memory der, uint ptr) internal pure returns (bytes32) { return der.keccak(ptr.ixf(), ptr.ixl()+1 - ptr.ixf()); } function keccakOfAllBytesAt(bytes memory der, uint ptr) internal pure returns (bytes32) { return der.keccak(ptr.ixs(), ptr.ixl()+1 - ptr.ixs()); } /* * @dev Extract value of bitstring node from DER-encoded structure * @param der The DER-encoded ASN1 structure * @param ptr Points to the indices of the current node * @return Value of bitstring converted to bytes */ function bitstringAt(bytes memory der, uint ptr) internal pure returns (bytes memory) { require(der[ptr.ixs()] == 0x03, "Not type BIT STRING"); // Only 00 padded bitstr can be converted to bytestr! require(der[ptr.ixf()] == 0x00); uint valueLength = ptr.ixl()+1 - ptr.ixf(); return der.substring(ptr.ixf()+1, valueLength-1); } function readNodeLength(bytes memory der, uint ix) private pure returns (uint) { uint length; uint80 ixFirstContentByte; uint80 ixLastContentByte; if ((der[ix+1] & 0x80) == 0) { length = uint8(der[ix+1]); ixFirstContentByte = uint80(ix+2); ixLastContentByte = uint80(ixFirstContentByte + length -1); } else { uint8 lengthbytesLength = uint8(der[ix+1] & 0x7F); if (lengthbytesLength == 1) length = der.readUint8(ix+2); else if (lengthbytesLength == 2) length = der.readUint16(ix+2); else length = uint(der.readBytesN(ix+2, lengthbytesLength) >> (32-lengthbytesLength)*8); ixFirstContentByte = uint80(ix+2+lengthbytesLength); ixLastContentByte = uint80(ixFirstContentByte + length -1); } return NodePtr.getPtr(ix, ixFirstContentByte, ixLastContentByte); } }
Extract entire node from DER-encoded structure der The DER-encoded ASN1 structure ptr Points to the indices of the current node return All bytes of node/
function allBytesAt(bytes memory der, uint ptr) internal pure returns (bytes memory) { return der.substring(ptr.ixs(), ptr.ixl()+1 - ptr.ixs()); }
1,805,041
// SPDX-License-Identifier: AGPL-3.0 // MgvOfferTaking.sol // Copyright (C) 2021 Giry SAS. // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU Affero General Public License as published // by the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU Affero General Public License for more details. // // You should have received a copy of the GNU Affero General Public License // along with this program. If not, see <https://www.gnu.org/licenses/>. pragma solidity ^0.8.10; pragma abicoder v2; import {IERC20, HasMgvEvents, IMaker, IMgvMonitor, MgvLib as ML, P} from "./MgvLib.sol"; import {MgvHasOffers} from "./MgvHasOffers.sol"; abstract contract MgvOfferTaking is MgvHasOffers { using P.Offer for P.Offer.t; using P.OfferDetail for P.OfferDetail.t; using P.Global for P.Global.t; using P.Local for P.Local.t; /* # MultiOrder struct */ /* The `MultiOrder` struct is used by market orders and snipes. Some of its fields are only used by market orders (`initialWants, initialGives`). We need a common data structure for both since low-level calls are shared between market orders and snipes. The struct is helpful in decreasing stack use. */ struct MultiOrder { uint initialWants; // used globally by market order, not used by snipes uint initialGives; // used globally by market order, not used by snipes uint totalGot; // used globally by market order, per-offer by snipes uint totalGave; // used globally by market order, per-offer by snipes uint totalPenalty; // used globally address taker; // used globally bool fillWants; // used globally } /* # Market Orders */ /* ## Market Order */ //+clear+ /* A market order specifies a (`outbound_tkn`,`inbound_tkn`) pair, a desired total amount of `outbound_tkn` (`takerWants`), and an available total amount of `inbound_tkn` (`takerGives`). It returns two `uint`s: the total amount of `outbound_tkn` received and the total amount of `inbound_tkn` spent. The `takerGives/takerWants` ratio induces a maximum average price that the taker is ready to pay across all offers that will be executed during the market order. It is thus possible to execute an offer with a price worse than the initial (`takerGives`/`takerWants`) ratio given as argument to `marketOrder` if some cheaper offers were executed earlier in the market order. The market order stops when the price has become too high, or when the end of the book has been reached, or: * If `fillWants` is true, the market order stops when `takerWants` units of `outbound_tkn` have been obtained. With `fillWants` set to true, to buy a specific volume of `outbound_tkn` at any price, set `takerWants` to the amount desired and `takerGives` to $2^{160}-1$. * If `fillWants` is false, the taker is filling `gives` instead: the market order stops when `takerGives` units of `inbound_tkn` have been sold. With `fillWants` set to false, to sell a specific volume of `inbound_tkn` at any price, set `takerGives` to the amount desired and `takerWants` to $0$. */ function marketOrder( address outbound_tkn, address inbound_tkn, uint takerWants, uint takerGives, bool fillWants ) external returns ( uint, uint, uint ) { unchecked { return generalMarketOrder( outbound_tkn, inbound_tkn, takerWants, takerGives, fillWants, msg.sender ); }} /* # General Market Order */ //+clear+ /* General market orders set up the market order with a given `taker` (`msg.sender` in the most common case). Returns `(totalGot, totalGave)`. Note that the `taker` can be anyone. This is safe when `taker == msg.sender`, but `generalMarketOrder` must not be called with `taker != msg.sender` unless a security check is done after (see [`MgvOfferTakingWithPermit`](#mgvoffertakingwithpermit.sol)`. */ function generalMarketOrder( address outbound_tkn, address inbound_tkn, uint takerWants, uint takerGives, bool fillWants, address taker ) internal returns ( uint, uint, uint ) { unchecked { /* Since amounts stored in offers are 96 bits wide, checking that `takerWants` and `takerGives` fit in 160 bits prevents overflow during the main market order loop. */ require(uint160(takerWants) == takerWants, "mgv/mOrder/takerWants/160bits"); require(uint160(takerGives) == takerGives, "mgv/mOrder/takerGives/160bits"); /* `SingleOrder` is defined in `MgvLib.sol` and holds information for ordering the execution of one offer. */ ML.SingleOrder memory sor; sor.outbound_tkn = outbound_tkn; sor.inbound_tkn = inbound_tkn; (sor.global, sor.local) = config(outbound_tkn, inbound_tkn); /* Throughout the execution of the market order, the `sor`'s offer id and other parameters will change. We start with the current best offer id (0 if the book is empty). */ sor.offerId = sor.local.best(); sor.offer = offers[outbound_tkn][inbound_tkn][sor.offerId]; /* `sor.wants` and `sor.gives` may evolve, but they are initially however much remains in the market order. */ sor.wants = takerWants; sor.gives = takerGives; /* `MultiOrder` (defined above) maintains information related to the entire market order. During the order, initial `wants`/`gives` values minus the accumulated amounts traded so far give the amounts that remain to be traded. */ MultiOrder memory mor; mor.initialWants = takerWants; mor.initialGives = takerGives; mor.taker = taker; mor.fillWants = fillWants; /* For the market order to even start, the market needs to be both active, and not currently protected from reentrancy. */ activeMarketOnly(sor.global, sor.local); unlockedMarketOnly(sor.local); /* ### Initialization */ /* The market order will operate as follows : it will go through offers from best to worse, starting from `offerId`, and: */ /* * will maintain remaining `takerWants` and `takerGives` values. The initial `takerGives/takerWants` ratio is the average price the taker will accept. Better prices may be found early in the book, and worse ones later. * will not set `prev`/`next` pointers to their correct locations at each offer taken (this is an optimization enabled by forbidding reentrancy). * after consuming a segment of offers, will update the current `best` offer to be the best remaining offer on the book. */ /* We start be enabling the reentrancy lock for this (`outbound_tkn`,`inbound_tkn`) pair. */ sor.local = sor.local.lock(true); locals[outbound_tkn][inbound_tkn] = sor.local; emit OrderStart(); /* Call recursive `internalMarketOrder` function.*/ internalMarketOrder(mor, sor, true); /* Over the course of the market order, a penalty reserved for `msg.sender` has accumulated in `mor.totalPenalty`. No actual transfers have occured yet -- all the ethers given by the makers as provision are owned by the Mangrove. `sendPenalty` finally gives the accumulated penalty to `msg.sender`. */ sendPenalty(mor.totalPenalty); emit OrderComplete( outbound_tkn, inbound_tkn, taker, mor.totalGot, mor.totalGave, mor.totalPenalty ); //+clear+ return (mor.totalGot, mor.totalGave, mor.totalPenalty); }} /* ## Internal market order */ //+clear+ /* `internalMarketOrder` works recursively. Going downward, each successive offer is executed until the market order stops (due to: volume exhausted, bad price, or empty book). Then the [reentrancy lock is lifted](#internalMarketOrder/liftReentrancy). Going upward, each offer's `maker` contract is called again with its remaining gas and given the chance to update its offers on the book. The last argument is a boolean named `proceed`. If an offer was not executed, it means the price has become too high. In that case, we notify the next recursive call that the market order should end. In this initial call, no offer has been executed yet so `proceed` is true. */ function internalMarketOrder( MultiOrder memory mor, ML.SingleOrder memory sor, bool proceed ) internal { unchecked { /* #### Case 1 : End of order */ /* We execute the offer currently stored in `sor`. */ if ( proceed && (mor.fillWants ? sor.wants > 0 : sor.gives > 0) && sor.offerId > 0 ) { uint gasused; // gas used by `makerExecute` bytes32 makerData; // data returned by maker /* <a id="MgvOfferTaking/statusCodes"></a> `mgvData` is an internal Mangrove status code. It may appear in an [`OrderResult`](#MgvLib/OrderResult). Its possible values are: * `"mgv/notExecuted"`: offer was not executed. * `"mgv/tradeSuccess"`: offer execution succeeded. Will appear in `OrderResult`. * `"mgv/notEnoughGasForMakerTrade"`: cannot give maker close enough to `gasreq`. Triggers a revert of the entire order. * `"mgv/makerRevert"`: execution of `makerExecute` reverted. Will appear in `OrderResult`. * `"mgv/makerAbort"`: execution of `makerExecute` returned normally, but returndata did not start with 32 bytes of 0s. Will appear in `OrderResult`. * `"mgv/makerTransferFail"`: maker could not send outbound_tkn tokens. Will appear in `OrderResult`. * `"mgv/makerReceiveFail"`: maker could not receive inbound_tkn tokens. Will appear in `OrderResult`. * `"mgv/takerTransferFail"`: taker could not send inbound_tkn tokens. Triggers a revert of the entire order. `mgvData` should not be exploitable by the maker! */ bytes32 mgvData; /* Load additional information about the offer. We don't do it earlier to save one storage read in case `proceed` was false. */ sor.offerDetail = offerDetails[sor.outbound_tkn][sor.inbound_tkn][ sor.offerId ]; /* `execute` will adjust `sor.wants`,`sor.gives`, and may attempt to execute the offer if its price is low enough. It is crucial that an error due to `taker` triggers a revert. That way, [`mgvData`](#MgvOfferTaking/statusCodes) not in `["mgv/notExecuted","mgv/tradeSuccess"]` means the failure is the maker's fault. */ /* Post-execution, `sor.wants`/`sor.gives` reflect how much was sent/taken by the offer. We will need it after the recursive call, so we save it in local variables. Same goes for `offerId`, `sor.offer` and `sor.offerDetail`. */ (gasused, makerData, mgvData) = execute(mor, sor); /* Keep cached copy of current `sor` values. */ uint takerWants = sor.wants; uint takerGives = sor.gives; uint offerId = sor.offerId; P.Offer.t offer = sor.offer; P.OfferDetail.t offerDetail = sor.offerDetail; /* If an execution was attempted, we move `sor` to the next offer. Note that the current state is inconsistent, since we have not yet updated `sor.offerDetails`. */ if (mgvData != "mgv/notExecuted") { sor.wants = mor.initialWants > mor.totalGot ? mor.initialWants - mor.totalGot : 0; /* It is known statically that `mor.initialGives - mor.totalGave` does not underflow since 1. `mor.totalGave` was increased by `sor.gives` during `execute`, 2. `sor.gives` was at most `mor.initialGives - mor.totalGave` from earlier step, 3. `sor.gives` may have been clamped _down_ during `execute` (to "`offer.wants`" if the offer is entirely consumed, or to `makerWouldWant`, cf. code of `execute`). */ sor.gives = mor.initialGives - mor.totalGave; sor.offerId = sor.offer.next(); sor.offer = offers[sor.outbound_tkn][sor.inbound_tkn][sor.offerId]; } /* note that internalMarketOrder may be called twice with same offerId, but in that case `proceed` will be false! */ internalMarketOrder( mor, sor, /* `proceed` value for next call. Currently, when an offer did not execute, it's because the offer's price was too high. In that case we interrupt the loop and let the taker leave with less than they asked for (but at a correct price). We could also revert instead of breaking; this could be a configurable flag for the taker to pick. */ mgvData != "mgv/notExecuted" ); /* Restore `sor` values from to before recursive call */ sor.offerId = offerId; sor.wants = takerWants; sor.gives = takerGives; sor.offer = offer; sor.offerDetail = offerDetail; /* After an offer execution, we may run callbacks and increase the total penalty. As that part is common to market orders and snipes, it lives in its own `postExecute` function. */ if (mgvData != "mgv/notExecuted") { postExecute(mor, sor, gasused, makerData, mgvData); } /* #### Case 2 : End of market order */ /* If `proceed` is false, the taker has gotten its requested volume, or we have reached the end of the book, we conclude the market order. */ } else { /* During the market order, all executed offers have been removed from the book. We end by stitching together the `best` offer pointer and the new best offer. */ sor.local = stitchOffers( sor.outbound_tkn, sor.inbound_tkn, 0, sor.offerId, sor.local ); /* <a id="internalMarketOrder/liftReentrancy"></a>Now that the market order is over, we can lift the lock on the book. In the same operation we * lift the reentrancy lock, and * update the storage so we are free from out of order storage writes. */ sor.local = sor.local.lock(false); locals[sor.outbound_tkn][sor.inbound_tkn] = sor.local; /* `payTakerMinusFees` sends the fee to the vault, proportional to the amount purchased, and gives the rest to the taker */ payTakerMinusFees(mor, sor); /* In an inverted Mangrove, amounts have been lent by each offer's maker to the taker. We now call the taker. This is a noop in a normal Mangrove. */ executeEnd(mor, sor); } }} /* # Sniping */ /* ## Snipes */ //+clear+ /* `snipes` executes multiple offers. It takes a `uint[4][]` as penultimate argument, with each array element of the form `[offerId,takerWants,takerGives,offerGasreq]`. The return parameters are of the form `(successes,snipesGot,snipesGave,bounty)`. Note that we do not distinguish further between mismatched arguments/offer fields on the one hand, and an execution failure on the other. Still, a failed offer has to pay a penalty, and ultimately transaction logs explicitly mention execution failures (see `MgvLib.sol`). */ function snipes( address outbound_tkn, address inbound_tkn, uint[4][] calldata targets, bool fillWants ) external returns ( uint, uint, uint, uint ) { unchecked { return generalSnipes(outbound_tkn, inbound_tkn, targets, fillWants, msg.sender); }} /* From an array of _n_ `[offerId, takerWants,takerGives,gasreq]` elements, execute each snipe in sequence. Returns `(successes, takerGot, takerGave, bounty)`. Note that if this function is not internal, anyone can make anyone use Mangrove. Note that unlike general market order, the returned total values are _not_ `mor.totalGot` and `mor.totalGave`, since those are reset at every iteration of the `targets` array. Instead, accumulators `snipesGot` and `snipesGave` are used. */ function generalSnipes( address outbound_tkn, address inbound_tkn, uint[4][] calldata targets, bool fillWants, address taker ) internal returns ( uint, uint, uint, uint ) { unchecked { ML.SingleOrder memory sor; sor.outbound_tkn = outbound_tkn; sor.inbound_tkn = inbound_tkn; (sor.global, sor.local) = config(outbound_tkn, inbound_tkn); MultiOrder memory mor; mor.taker = taker; mor.fillWants = fillWants; /* For the snipes to even start, the market needs to be both active and not currently protected from reentrancy. */ activeMarketOnly(sor.global, sor.local); unlockedMarketOnly(sor.local); emit OrderStart(); /* ### Main loop */ //+clear+ /* Call `internalSnipes` function. */ (uint successCount, uint snipesGot, uint snipesGave) = internalSnipes(mor, sor, targets); /* Over the course of the snipes order, a penalty reserved for `msg.sender` has accumulated in `mor.totalPenalty`. No actual transfers have occured yet -- all the ethers given by the makers as provision are owned by the Mangrove. `sendPenalty` finally gives the accumulated penalty to `msg.sender`. */ sendPenalty(mor.totalPenalty); //+clear+ emit OrderComplete( sor.outbound_tkn, sor.inbound_tkn, taker, snipesGot, snipesGave, mor.totalPenalty ); return (successCount, snipesGot, snipesGave, mor.totalPenalty); }} /* ## Internal snipes */ //+clear+ /* `internalSnipes` works by looping over targets. Each successive offer is executed under a [reentrancy lock](#internalSnipes/liftReentrancy), then its posthook is called. Going upward, each offer's `maker` contract is called again with its remaining gas and given the chance to update its offers on the book. */ function internalSnipes( MultiOrder memory mor, ML.SingleOrder memory sor, uint[4][] calldata targets ) internal returns (uint successCount, uint snipesGot, uint snipesGave) { unchecked { for (uint i = 0; i < targets.length; i++) { /* Reset these amounts since every snipe is treated individually. Only the total penalty is sent at the end of all snipes. */ mor.totalGot = 0; mor.totalGave = 0; /* Initialize single order struct. */ sor.offerId = targets[i][0]; sor.offer = offers[sor.outbound_tkn][sor.inbound_tkn][sor.offerId]; sor.offerDetail = offerDetails[sor.outbound_tkn][sor.inbound_tkn][ sor.offerId ]; /* If we removed the `isLive` conditional, a single expired or nonexistent offer in `targets` would revert the entire transaction (by the division by `offer.gives` below since `offer.gives` would be 0). We also check that `gasreq` is not worse than specified. A taker who does not care about `gasreq` can specify any amount larger than $2^{24}-1$. A mismatched price will be detected by `execute`. */ if ( !isLive(sor.offer) || sor.offerDetail.gasreq() > targets[i][3] ) { /* We move on to the next offer in the array. */ continue; } else { require( uint96(targets[i][1]) == targets[i][1], "mgv/snipes/takerWants/96bits" ); require( uint96(targets[i][2]) == targets[i][2], "mgv/snipes/takerGives/96bits" ); sor.wants = targets[i][1]; sor.gives = targets[i][2]; /* We start be enabling the reentrancy lock for this (`outbound_tkn`,`inbound_tkn`) pair. */ sor.local = sor.local.lock(true); locals[sor.outbound_tkn][sor.inbound_tkn] = sor.local; /* `execute` will adjust `sor.wants`,`sor.gives`, and may attempt to execute the offer if its price is low enough. It is crucial that an error due to `taker` triggers a revert. That way [`mgvData`](#MgvOfferTaking/statusCodes) not in `["mgv/tradeSuccess","mgv/notExecuted"]` means the failure is the maker's fault. */ /* Post-execution, `sor.wants`/`sor.gives` reflect how much was sent/taken by the offer. */ (uint gasused, bytes32 makerData, bytes32 mgvData) = execute(mor, sor); if (mgvData == "mgv/tradeSuccess") { successCount += 1; } /* In the market order, we were able to avoid stitching back offers after every `execute` since we knew a continuous segment starting at best would be consumed. Here, we cannot do this optimisation since offers in the `targets` array may be anywhere in the book. So we stitch together offers immediately after each `execute`. */ if (mgvData != "mgv/notExecuted") { sor.local = stitchOffers( sor.outbound_tkn, sor.inbound_tkn, sor.offer.prev(), sor.offer.next(), sor.local ); } /* <a id="internalSnipes/liftReentrancy"></a> Now that the current snipe is over, we can lift the lock on the book. In the same operation we * lift the reentrancy lock, and * update the storage so we are free from out of order storage writes. */ sor.local = sor.local.lock(false); locals[sor.outbound_tkn][sor.inbound_tkn] = sor.local; /* `payTakerMinusFees` sends the fee to the vault, proportional to the amount purchased, and gives the rest to the taker */ payTakerMinusFees(mor, sor); /* In an inverted Mangrove, amounts have been lent by each offer's maker to the taker. We now call the taker. This is a noop in a normal Mangrove. */ executeEnd(mor, sor); /* After an offer execution, we may run callbacks and increase the total penalty. As that part is common to market orders and snipes, it lives in its own `postExecute` function. */ if (mgvData != "mgv/notExecuted") { postExecute(mor, sor, gasused, makerData, mgvData); } snipesGot += mor.totalGot; snipesGave += mor.totalGave; } } }} /* # General execution */ /* During a market order or a snipes, offers get executed. The following code takes care of executing a single offer with parameters given by a `SingleOrder` within a larger context given by a `MultiOrder`. */ /* ## Execute */ /* This function will compare `sor.wants` `sor.gives` with `sor.offer.wants` and `sor.offer.gives`. If the price of the offer is low enough, an execution will be attempted (with volume limited by the offer's advertised volume). Summary of the meaning of the return values: * `gasused` is the gas consumed by the execution * `makerData` is the data returned after executing the offer * `mgvData` is an [internal Mangrove status code](#MgvOfferTaking/statusCodes). */ function execute(MultiOrder memory mor, ML.SingleOrder memory sor) internal returns ( uint gasused, bytes32 makerData, bytes32 mgvData ) { unchecked { /* #### `Price comparison` */ //+clear+ /* The current offer has a price `p = offerWants ÷ offerGives` and the taker is ready to accept a price up to `p' = takerGives ÷ takerWants`. Comparing `offerWants * takerWants` and `offerGives * takerGives` tels us whether `p < p'`. */ { uint offerWants = sor.offer.wants(); uint offerGives = sor.offer.gives(); uint takerWants = sor.wants; uint takerGives = sor.gives; /* <a id="MgvOfferTaking/checkPrice"></a>If the price is too high, we return early. Otherwise we now know we'll execute the offer. */ if (offerWants * takerWants > offerGives * takerGives) { return (0, bytes32(0), "mgv/notExecuted"); } /* ### Specification of value transfers: Let $o_w$ be `offerWants`, $o_g$ be `offerGives`, $t_w$ be `takerWants`, $t_g$ be `takerGives`, and `f ∈ {w,g}` be $w$ if `fillWants` is true, $g$ otherwise. Let $\textrm{got}$ be the amount that the taker will receive, and $\textrm{gave}$ be the amount that the taker will pay. #### Case $f = w$ If $f = w$, let $\textrm{got} = \min(o_g,t_w)$, and let $\textrm{gave} = \left\lceil\dfrac{o_w \textrm{got}}{o_g}\right\rceil$. This is well-defined since, for live offers, $o_g > 0$. In plain english, we only give to the taker up to what they wanted (or what the offer has to give), and follow the offer price to determine what the taker will give. Since $\textrm{gave}$ is rounded up, the price might be overevaluated. Still, we cannot spend more than what the taker specified as `takerGives`. At this point [we know](#MgvOfferTaking/checkPrice) that $o_w t_w \leq o_g t_g$, so since $t_g$ is an integer we have $t_g \geq \left\lceil\dfrac{o_w t_w}{o_g}\right\rceil \geq \left\lceil\dfrac{o_w \textrm{got}}{o_g}\right\rceil = \textrm{gave}$. #### Case $f = g$ If $f = g$, let $\textrm{gave} = \min(o_w,t_g)$, and $\textrm{got} = o_g$ if $o_w = 0$, $\textrm{got} = \left\lfloor\dfrac{o_g \textrm{gave}}{o_w}\right\rfloor$ otherwise. In plain english, we spend up to what the taker agreed to pay (or what the offer wants), and follow the offer price to determine what the taker will get. This may exceed $t_w$. #### Price adjustment Prices are rounded up to ensure maker is not drained on small amounts. It's economically unlikely, but `density` protects the taker from being drained anyway so it is better to default towards protecting the maker here. */ /* ### Implementation First we check the cases $(f=w \wedge o_g < t_w)\vee(f_g \wedge o_w < t_g)$, in which case the above spec simplifies to $\textrm{got} = o_g, \textrm{gave} = o_w$. Otherwise the offer may be partially consumed. In the case $f=w$ we don't touch $\textrm{got}$ (which was initialized to $t_w$) and compute $\textrm{gave} = \left\lceil\dfrac{o_w t_w}{o_g}\right\rceil$. As shown above we have $\textrm{gave} \leq t_g$. In the case $f=g$ we don't touch $\textrm{gave}$ (which was initialized to $t_g$) and compute $\textrm{got} = o_g$ if $o_w = 0$, and $\textrm{got} = \left\lfloor\dfrac{o_g t_g}{o_w}\right\rfloor$ otherwise. */ if ( (mor.fillWants && offerGives < takerWants) || (!mor.fillWants && offerWants < takerGives) ) { sor.wants = offerGives; sor.gives = offerWants; } else { if (mor.fillWants) { uint product = offerWants * takerWants; sor.gives = product / offerGives + (product % offerGives == 0 ? 0 : 1); } else { if (offerWants == 0) { sor.wants = offerGives; } else { sor.wants = (offerGives * takerGives) / offerWants; } } } } /* The flashloan is executed by call to `flashloan`. If the call reverts, it means the maker failed to send back `sor.wants` `outbound_tkn` to the taker. Notes : * `msg.sender` is the Mangrove itself in those calls -- all operations related to the actual caller should be done outside of this call. * any spurious exception due to an error in Mangrove code will be falsely blamed on the Maker, and its provision for the offer will be unfairly taken away. */ (bool success, bytes memory retdata) = address(this).call( abi.encodeWithSelector(this.flashloan.selector, sor, mor.taker) ); /* `success` is true: trade is complete */ if (success) { /* In case of success, `retdata` encodes the gas used by the offer. */ gasused = abi.decode(retdata, (uint)); /* `mgvData` indicates trade success */ mgvData = bytes32("mgv/tradeSuccess"); emit OfferSuccess( sor.outbound_tkn, sor.inbound_tkn, sor.offerId, mor.taker, sor.wants, sor.gives ); /* If configured to do so, the Mangrove notifies an external contract that a successful trade has taken place. */ if (sor.global.notify()) { IMgvMonitor(sor.global.monitor()).notifySuccess( sor, mor.taker ); } /* We update the totals in the multiorder based on the adjusted `sor.wants`/`sor.gives`. */ /* overflow: sor.{wants,gives} are on 96bits, sor.total{Got,Gave} are on 256 bits. */ mor.totalGot += sor.wants; mor.totalGave += sor.gives; } else { /* In case of failure, `retdata` encodes a short [status code](#MgvOfferTaking/statusCodes), the gas used by the offer, and an arbitrary 256 bits word sent by the maker. */ (mgvData, gasused, makerData) = innerDecode(retdata); /* Note that in the `if`s, the literals are bytes32 (stack values), while as revert arguments, they are strings (memory pointers). */ if ( mgvData == "mgv/makerRevert" || mgvData == "mgv/makerAbort" || mgvData == "mgv/makerTransferFail" || mgvData == "mgv/makerReceiveFail" ) { emit OfferFail( sor.outbound_tkn, sor.inbound_tkn, sor.offerId, mor.taker, sor.wants, sor.gives, mgvData ); /* If configured to do so, the Mangrove notifies an external contract that a failed trade has taken place. */ if (sor.global.notify()) { IMgvMonitor(sor.global.monitor()).notifyFail( sor, mor.taker ); } /* It is crucial that any error code which indicates an error caused by the taker triggers a revert, because functions that call `execute` consider that `mgvData` not in `["mgv/notExecuted","mgv/tradeSuccess"]` should be blamed on the maker. */ } else if (mgvData == "mgv/notEnoughGasForMakerTrade") { revert("mgv/notEnoughGasForMakerTrade"); } else if (mgvData == "mgv/takerTransferFail") { revert("mgv/takerTransferFail"); } else { /* This code must be unreachable. **Danger**: if a well-crafted offer/maker pair can force a revert of `flashloan`, the Mangrove will be stuck. */ revert("mgv/swapError"); } } /* Delete the offer. The last argument indicates whether the offer should be stripped of its provision (yes if execution failed, no otherwise). We delete offers whether the amount remaining on offer is > density or not for the sake of uniformity (code is much simpler). We also expect prices to move often enough that the maker will want to update their price anyway. To simulate leaving the remaining volume in the offer, the maker can program their `makerPosthook` to `updateOffer` and put the remaining volume back in. */ dirtyDeleteOffer( sor.outbound_tkn, sor.inbound_tkn, sor.offerId, sor.offer, sor.offerDetail, mgvData != "mgv/tradeSuccess" ); }} /* ## flashloan (abstract) */ /* Externally called by `execute`, flashloan lends money (from the taker to the maker, or from the maker to the taker, depending on the implementation) then calls `makerExecute` to run the maker liquidity fetching code. If `makerExecute` is unsuccessful, `flashloan` reverts (but the larger orderbook traversal will continue). All `flashloan` implementations must `require(msg.sender) == address(this))`. */ function flashloan(ML.SingleOrder calldata sor, address taker) external virtual returns (uint gasused); /* ## Maker Execute */ /* Called by `flashloan`, `makerExecute` runs the maker code and checks that it can safely send the desired assets to the taker. */ function makerExecute(ML.SingleOrder calldata sor) internal returns (uint gasused) { unchecked { bytes memory cd = abi.encodeWithSelector(IMaker.makerExecute.selector, sor); uint gasreq = sor.offerDetail.gasreq(); address maker = sor.offerDetail.maker(); uint oldGas = gasleft(); /* We let the maker pay for the overhead of checking remaining gas and making the call, as well as handling the return data (constant gas since only the first 32 bytes of return data are read). So the `require` below is just an approximation: if the overhead of (`require` + cost of `CALL`) is $h$, the maker will receive at worst $\textrm{gasreq} - \frac{63h}{64}$ gas. */ /* Note : as a possible future feature, we could stop an order when there's not enough gas left to continue processing offers. This could be done safely by checking, as soon as we start processing an offer, whether `63/64(gasleft-offer_gasbase) > gasreq`. If no, we could stop and know by induction that there is enough gas left to apply fees, stitch offers, etc for the offers already executed. */ if (!(oldGas - oldGas / 64 >= gasreq)) { innerRevert([bytes32("mgv/notEnoughGasForMakerTrade"), "", ""]); } (bool callSuccess, bytes32 makerData) = controlledCall(maker, gasreq, cd); gasused = oldGas - gasleft(); if (!callSuccess) { innerRevert([bytes32("mgv/makerRevert"), bytes32(gasused), makerData]); } /* Successful execution must have a returndata that begins with `bytes32("")`. */ if (makerData != "") { innerRevert([bytes32("mgv/makerAbort"), bytes32(gasused), makerData]); } bool transferSuccess = transferTokenFrom( sor.outbound_tkn, maker, address(this), sor.wants ); if (!transferSuccess) { innerRevert( [bytes32("mgv/makerTransferFail"), bytes32(gasused), makerData] ); } }} /* ## executeEnd (abstract) */ /* Called by `internalSnipes` and `internalMarketOrder`, `executeEnd` may run implementation-specific code after all makers have been called once. In [`InvertedMangrove`](#InvertedMangrove), the function calls the taker once so they can act on their flashloan. In [`Mangrove`], it does nothing. */ function executeEnd(MultiOrder memory mor, ML.SingleOrder memory sor) internal virtual; /* ## Post execute */ /* At this point, we know `mgvData != "mgv/notExecuted"`. After executing an offer (whether in a market order or in snipes), we 1. Call the maker's posthook and sum the total gas used. 2. If offer failed: sum total penalty due to taker and give remainder to maker. */ function postExecute( MultiOrder memory mor, ML.SingleOrder memory sor, uint gasused, bytes32 makerData, bytes32 mgvData ) internal { unchecked { if (mgvData == "mgv/tradeSuccess") { beforePosthook(sor); } uint gasreq = sor.offerDetail.gasreq(); /* We are about to call back the maker, giving it its unused gas (`gasreq - gasused`). Since the gas used so far may exceed `gasreq`, we prevent underflow in the subtraction below by bounding `gasused` above with `gasreq`. We could have decided not to call back the maker at all when there is no gas left, but we do it for uniformity. */ if (gasused > gasreq) { gasused = gasreq; } gasused = gasused + makerPosthook(sor, gasreq - gasused, makerData, mgvData); if (mgvData != "mgv/tradeSuccess") { mor.totalPenalty += applyPenalty(sor, gasused); } }} /* ## beforePosthook (abstract) */ /* Called by `makerPosthook`, this function can run implementation-specific code before calling the maker has been called a second time. In [`InvertedMangrove`](#InvertedMangrove), all makers are called once so the taker gets all of its money in one shot. Then makers are traversed again and the money is sent back to each taker using `beforePosthook`. In [`Mangrove`](#Mangrove), `beforePosthook` does nothing. */ function beforePosthook(ML.SingleOrder memory sor) internal virtual; /* ## Maker Posthook */ function makerPosthook( ML.SingleOrder memory sor, uint gasLeft, bytes32 makerData, bytes32 mgvData ) internal returns (uint gasused) { unchecked { /* At this point, mgvData can only be `"mgv/tradeSuccess"`, `"mgv/makerAbort"`, `"mgv/makerRevert"`, `"mgv/makerTransferFail"` or `"mgv/makerReceiveFail"` */ bytes memory cd = abi.encodeWithSelector( IMaker.makerPosthook.selector, sor, ML.OrderResult({makerData: makerData, mgvData: mgvData}) ); address maker = sor.offerDetail.maker(); uint oldGas = gasleft(); /* We let the maker pay for the overhead of checking remaining gas and making the call. So the `require` below is just an approximation: if the overhead of (`require` + cost of `CALL`) is $h$, the maker will receive at worst $\textrm{gasreq} - \frac{63h}{64}$ gas. */ if (!(oldGas - oldGas / 64 >= gasLeft)) { revert("mgv/notEnoughGasForMakerPosthook"); } (bool callSuccess, ) = controlledCall(maker, gasLeft, cd); gasused = oldGas - gasleft(); if (!callSuccess) { emit PosthookFail(sor.outbound_tkn, sor.inbound_tkn, sor.offerId); } }} /* ## `controlledCall` */ /* Calls an external function with controlled gas expense. A direct call of the form `(,bytes memory retdata) = maker.call{gas}(selector,...args)` enables a griefing attack: the maker uses half its gas to write in its memory, then reverts with that memory segment as argument. After a low-level call, solidity automaticaly copies `returndatasize` bytes of `returndata` into memory. So the total gas consumed to execute a failing offer could exceed `gasreq + offer_gasbase` where `n` is the number of failing offers. This yul call only retrieves the first 32 bytes of the maker's `returndata`. */ function controlledCall( address callee, uint gasreq, bytes memory cd ) internal returns (bool success, bytes32 data) { unchecked { bytes32[1] memory retdata; assembly { success := call(gasreq, callee, 0, add(cd, 32), mload(cd), retdata, 32) } data = retdata[0]; }} /* # Penalties */ /* Offers are just promises. They can fail. Penalty provisioning discourages from failing too much: we ask makers to provision more ETH than the expected gas cost of executing their offer and penalize them accoridng to wasted gas. Under normal circumstances, we should expect to see bots with a profit expectation dry-running offers locally and executing `snipe` on failing offers, collecting the penalty. The result should be a mostly clean book for actual takers (i.e. a book with only successful offers). **Incentive issue**: if the gas price increases enough after an offer has been created, there may not be an immediately profitable way to remove the fake offers. In that case, we count on 3 factors to keep the book clean: 1. Gas price eventually comes down. 2. Other market makers want to keep the Mangrove attractive and maintain their offer flow. 3. Mangrove governance (who may collect a fee) wants to keep the Mangrove attractive and maximize exchange volume. */ //+clear+ /* After an offer failed, part of its provision is given back to the maker and the rest is stored to be sent to the taker after the entire order completes. In `applyPenalty`, we _only_ credit the maker with its excess provision. So it looks like the maker is gaining something. In fact they're just getting back a fraction of what they provisioned earlier. */ /* Penalty application summary: * If the transaction was a success, we entirely refund the maker and send nothing to the taker. * Otherwise, the maker loses the cost of `gasused + offer_gasbase` gas. The gas price is estimated by `gasprice`. * To create the offer, the maker had to provision for `gasreq + offer_gasbase` gas at a price of `offerDetail.gasprice`. * We do not consider the tx.gasprice. * `offerDetail.gasbase` and `offerDetail.gasprice` are the values of the Mangrove parameters `config.offer_gasbase` and `config.gasprice` when the offer was created. Without caching those values, the provision set aside could end up insufficient to reimburse the maker (or to retribute the taker). */ function applyPenalty( ML.SingleOrder memory sor, uint gasused ) internal returns (uint) { unchecked { uint gasreq = sor.offerDetail.gasreq(); uint provision = 10**9 * sor.offerDetail.gasprice() * (gasreq + sor.offerDetail.offer_gasbase()); /* We set `gasused = min(gasused,gasreq)` since `gasreq < gasused` is possible e.g. with `gasreq = 0` (all calls consume nonzero gas). */ if (gasused > gasreq) { gasused = gasreq; } /* As an invariant, `applyPenalty` is only called when `mgvData` is not in `["mgv/notExecuted","mgv/tradeSuccess"]` */ uint penalty = 10**9 * sor.global.gasprice() * (gasused + sor.local.offer_gasbase()); if (penalty > provision) { penalty = provision; } /* Here we write to storage the new maker balance. This occurs _after_ possible reentrant calls. How do we know we're not crediting twice the same amounts? Because the `offer`'s provision was set to 0 in storage (through `dirtyDeleteOffer`) before the reentrant calls. In this function, we are working with cached copies of the offer as it was before it was consumed. */ creditWei(sor.offerDetail.maker(), provision - penalty); return penalty; }} function sendPenalty(uint amount) internal { unchecked { if (amount > 0) { (bool noRevert, ) = msg.sender.call{value: amount}(""); require(noRevert, "mgv/sendPenaltyReverted"); } }} /* Post-trade, `payTakerMinusFees` sends what's due to the taker and the rest (the fees) to the vault. Routing through the Mangrove like that also deals with blacklisting issues (separates the maker-blacklisted and the taker-blacklisted cases). */ function payTakerMinusFees(MultiOrder memory mor, ML.SingleOrder memory sor) internal { unchecked { /* Should be statically provable that the 2 transfers below cannot return false under well-behaved ERC20s and a non-blacklisted, non-0 target. */ uint concreteFee = (mor.totalGot * sor.local.fee()) / 10_000; if (concreteFee > 0) { mor.totalGot -= concreteFee; require( transferToken(sor.outbound_tkn, vault, concreteFee), "mgv/feeTransferFail" ); } if (mor.totalGot > 0) { require( transferToken(sor.outbound_tkn, mor.taker, mor.totalGot), "mgv/MgvFailToPayTaker" ); } }} /* # Misc. functions */ /* Regular solidity reverts prepend the string argument with a [function signature](https://docs.soliditylang.org/en/v0.7.6/control-structures.html#revert). Since we wish to transfer data through a revert, the `innerRevert` function does a low-level revert with only the required data. `innerCode` decodes this data. */ function innerDecode(bytes memory data) internal pure returns ( bytes32 mgvData, uint gasused, bytes32 makerData ) { unchecked { /* The `data` pointer is of the form `[mgvData,gasused,makerData]` where each array element is contiguous and has size 256 bits. */ assembly { mgvData := mload(add(data, 32)) gasused := mload(add(data, 64)) makerData := mload(add(data, 96)) } }} /* <a id="MgvOfferTaking/innerRevert"></a>`innerRevert` reverts a raw triple of values to be interpreted by `innerDecode`. */ function innerRevert(bytes32[3] memory data) internal pure { unchecked { assembly { revert(data, 96) } }} /* `transferTokenFrom` is adapted from [existing code](https://soliditydeveloper.com/safe-erc20) and in particular avoids the "no return value" bug. It never throws and returns true iff the transfer was successful according to `tokenAddress`. Note that any spurious exception due to an error in Mangrove code will be falsely blamed on `from`. */ function transferTokenFrom( address tokenAddress, address from, address to, uint value ) internal returns (bool) { unchecked { bytes memory cd = abi.encodeWithSelector( IERC20.transferFrom.selector, from, to, value ); (bool noRevert, bytes memory data) = tokenAddress.call(cd); return (noRevert && (data.length == 0 || abi.decode(data, (bool)))); }} function transferToken( address tokenAddress, address to, uint value ) internal returns (bool) { unchecked { bytes memory cd = abi.encodeWithSelector( IERC20.transfer.selector, to, value ); (bool noRevert, bytes memory data) = tokenAddress.call(cd); return (noRevert && (data.length == 0 || abi.decode(data, (bool)))); }} }
Internal snipes /+clear+ `internalSnipes` works by looping over targets. Each successive offer is executed under a [reentrancy lock](internalSnipes/liftReentrancy), then its posthook is called. Going upward, each offer's `maker` contract is called again with its remaining gas and given the chance to update its offers on the book. / Reset these amounts since every snipe is treated individually. Only the total penalty is sent at the end of all snipes. / Initialize single order struct. / If we removed the `isLive` conditional, a single expired or nonexistent offer in `targets` would revert the entire transaction (by the division by `offer.gives` below since `offer.gives` would be 0). We also check that `gasreq` is not worse than specified. A taker who does not care about `gasreq` can specify any amount larger than $2^{24}-1$. A mismatched price will be detected by `execute`. / We start be enabling the reentrancy lock for this (`outbound_tkn`,`inbound_tkn`) pair. / `execute` will adjust `sor.wants`,`sor.gives`, and may attempt to execute the offer if its price is low enough. It is crucial that an error due to `taker` triggers a revert. That way [`mgvData`](MgvOfferTaking/statusCodes) not in `["mgv/tradeSuccess","mgv/notExecuted"]` means the failure is the maker's fault. / Post-execution, `sor.wants`/`sor.gives` reflect how much was sent/taken by the offer. / In the market order, we were able to avoid stitching back offers after every `execute` since we knew a continuous segment starting at best would be consumed. Here, we cannot do this optimisation since offers in the `targets` array may be anywhere in the book. So we stitch together offers immediately after each `execute`. / After an offer execution, we may run callbacks and increase the total penalty. As that part is common to market orders and snipes, it lives in its own `postExecute` function. /
function internalSnipes( MultiOrder memory mor, ML.SingleOrder memory sor, uint[4][] calldata targets ) internal returns (uint successCount, uint snipesGot, uint snipesGave) { unchecked { for (uint i = 0; i < targets.length; i++) { mor.totalGot = 0; mor.totalGave = 0; sor.offerId = targets[i][0]; sor.offer = offers[sor.outbound_tkn][sor.inbound_tkn][sor.offerId]; sor.offerDetail = offerDetails[sor.outbound_tkn][sor.inbound_tkn][ sor.offerId ]; if ( !isLive(sor.offer) || sor.offerDetail.gasreq() > targets[i][3] ) { continue; require( uint96(targets[i][1]) == targets[i][1], "mgv/snipes/takerWants/96bits" ); require( uint96(targets[i][2]) == targets[i][2], "mgv/snipes/takerGives/96bits" ); sor.wants = targets[i][1]; sor.gives = targets[i][2]; sor.local = sor.local.lock(true); locals[sor.outbound_tkn][sor.inbound_tkn] = sor.local; (uint gasused, bytes32 makerData, bytes32 mgvData) = execute(mor, sor); if (mgvData == "mgv/tradeSuccess") { successCount += 1; } if (mgvData != "mgv/notExecuted") { sor.local = stitchOffers( sor.outbound_tkn, sor.inbound_tkn, sor.offer.prev(), sor.offer.next(), sor.local ); } so we are free from out of order storage writes. locals[sor.outbound_tkn][sor.inbound_tkn] = sor.local; if (mgvData != "mgv/notExecuted") { postExecute(mor, sor, gasused, makerData, mgvData); } snipesGot += mor.totalGot; snipesGave += mor.totalGave; } } }} Summary of the meaning of the return values:
12,895,739
// Sources flattened with hardhat v2.0.5 https://hardhat.org // File deps/@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol // SPDX-License-Identifier: MIT pragma solidity ^0.6.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20Upgradeable { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // File deps/@openzeppelin/contracts-upgradeable/math/SafeMathUpgradeable.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 SafeMathUpgradeable { /** * @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 deps/@openzeppelin/contracts-upgradeable/utils/AddressUpgradeable.sol pragma solidity ^0.6.2; /** * @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 in extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return _functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); return _functionCallWithValue(target, data, value, errorMessage); } function _functionCallWithValue(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) { require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: weiValue }(data); if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // File deps/@openzeppelin/contracts-upgradeable/token/ERC20/SafeERC20Upgradeable.sol pragma solidity ^0.6.0; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20Upgradeable { using SafeMathUpgradeable for uint256; 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' // 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(IERC20Upgradeable 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(IERC20Upgradeable 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(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 // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // File deps/@openzeppelin/contracts-upgradeable/utils/EnumerableSetUpgradeable.sol 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 EnumerableSetUpgradeable { // To implement this library for multiple types with as little code // repetition as possible, we write it in terms of a generic Set type with // bytes32 values. // The Set implementation uses private functions, and user-facing // implementations (such as AddressSet) are just wrappers around the // underlying Set. // This means that we can only create new EnumerableSets for types that fit // in bytes32. struct Set { // Storage of set values bytes32[] _values; // Position of the value in the `values` array, plus 1 because index 0 // means a value is not in the set. mapping (bytes32 => uint256) _indexes; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function _add(Set storage set, bytes32 value) private returns (bool) { if (!_contains(set, value)) { set._values.push(value); // The value is stored at length-1, but we add 1 to all indexes // and use 0 as a sentinel value set._indexes[value] = set._values.length; return true; } else { return false; } } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function _remove(Set storage set, bytes32 value) private returns (bool) { // We read and store the value's index to prevent multiple reads from the same storage slot uint256 valueIndex = set._indexes[value]; if (valueIndex != 0) { // Equivalent to contains(set, value) // To delete an element from the _values array in O(1), we swap the element to delete with the last one in // the array, and then remove the last element (sometimes called as 'swap and pop'). // This modifies the order of the array, as noted in {at}. uint256 toDeleteIndex = valueIndex - 1; uint256 lastIndex = set._values.length - 1; // When the value to delete is the last one, the swap operation is unnecessary. However, since this occurs // so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement. bytes32 lastvalue = set._values[lastIndex]; // Move the last value to the index where the value to delete is set._values[toDeleteIndex] = lastvalue; // Update the index for the moved value set._indexes[lastvalue] = toDeleteIndex + 1; // All indexes are 1-based // Delete the slot where the moved value was stored set._values.pop(); // Delete the index for the deleted slot delete set._indexes[value]; return true; } else { return false; } } /** * @dev Returns true if the value is in the set. O(1). */ function _contains(Set storage set, bytes32 value) private view returns (bool) { return set._indexes[value] != 0; } /** * @dev Returns the number of values on the set. O(1). */ function _length(Set storage set) private view returns (uint256) { return set._values.length; } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function _at(Set storage set, uint256 index) private view returns (bytes32) { require(set._values.length > index, "EnumerableSet: index out of bounds"); return set._values[index]; } // 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 interfaces/convex/IBooster.sol pragma solidity >=0.6.0; pragma experimental ABIEncoderV2; interface IBooster { struct PoolInfo { address lptoken; address token; address gauge; address crvRewards; address stash; bool shutdown; } function poolInfo(uint256 _pid) external view returns (PoolInfo memory); function deposit(uint256 _pid, uint256 _amount, bool _stake) external returns(bool); function depositAll(uint256 _pid, bool _stake) external returns(bool); function withdraw(uint256 _pid, uint256 _amount) external returns(bool); function withdrawAll(uint256 _pid) external returns(bool); } // File interfaces/convex/CrvDepositor.sol pragma solidity >=0.6.0; interface CrvDepositor { //deposit crv for cvxCrv //can locking immediately or defer locking to someone else by paying a fee. //while users can choose to lock or defer, this is mostly in place so that //the cvx reward contract isnt costly to claim rewards function deposit(uint256 _amount, bool _lock) external; } // File interfaces/convex/IBaseRewardsPool.sol pragma solidity ^0.6.0; interface IBaseRewardsPool { //balance function balanceOf(address _account) external view returns(uint256); //withdraw to a convex tokenized deposit function withdraw(uint256 _amount, bool _claim) external returns(bool); //withdraw directly to curve LP token function withdrawAndUnwrap(uint256 _amount, bool _claim) external returns(bool); //claim rewards function getReward() external returns(bool); //stake a convex tokenized deposit function stake(uint256 _amount) external returns(bool); //stake a convex tokenized deposit for another address(transfering ownership) function stakeFor(address _account,uint256 _amount) external returns(bool); function getReward(address _account, bool _claimExtras) external returns (bool); function rewards(address _account) external view returns (uint256); function earned(address _account) external view returns (uint256); } // File interfaces/convex/ICvxRewardsPool.sol pragma solidity ^0.6.0; interface ICvxRewardsPool { //balance function balanceOf(address _account) external view returns(uint256); //withdraw to a convex tokenized deposit function withdraw(uint256 _amount, bool _claim) external; //withdraw directly to curve LP token function withdrawAndUnwrap(uint256 _amount, bool _claim) external returns(bool); //claim rewards function getReward(bool _stake) external; //stake a convex tokenized deposit function stake(uint256 _amount) external; //stake a convex tokenized deposit for another address(transfering ownership) function stakeFor(address _account,uint256 _amount) external returns(bool); function rewards(address _account) external view returns (uint256); function earned(address _account) external view returns (uint256); } // File deps/@openzeppelin/contracts-upgradeable/proxy/Initializable.sol pragma solidity >=0.4.24 <0.7.0; /** * @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed * behind a proxy. Since a proxied contract can't have a constructor, it's common to move constructor logic to an * external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer * function so it can only be called once. The {initializer} modifier provided by this contract will have this effect. * * TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as * possible by providing the encoded function call as the `_data` argument to {UpgradeableProxy-constructor}. * * CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure * that all initializers are idempotent. This is not verified automatically as constructors are by Solidity. */ abstract contract Initializable { /** * @dev Indicates that the contract has been initialized. */ bool private _initialized; /** * @dev Indicates that the contract is in the process of being initialized. */ bool private _initializing; /** * @dev Modifier to protect an initializer function from being invoked twice. */ modifier initializer() { require(_initializing || _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) { // 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; // solhint-disable-next-line no-inline-assembly assembly { cs := extcodesize(self) } return cs == 0; } } // File deps/@openzeppelin/contracts-upgradeable/GSN/ContextUpgradeable.sol pragma solidity ^0.6.0; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract ContextUpgradeable is Initializable { function __Context_init() internal initializer { __Context_init_unchained(); } function __Context_init_unchained() internal initializer { } function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } uint256[50] private __gap; } // File deps/@openzeppelin/contracts-upgradeable/utils/PausableUpgradeable.sol pragma solidity ^0.6.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. */ contract PausableUpgradeable is Initializable, ContextUpgradeable { /** * @dev Emitted when the pause is triggered by `account`. */ event Paused(address account); /** * @dev Emitted when the pause is lifted by `account`. */ event Unpaused(address account); bool private _paused; /** * @dev Initializes the contract in unpaused state. */ function __Pausable_init() internal initializer { __Context_init_unchained(); __Pausable_init_unchained(); } function __Pausable_init_unchained() internal initializer { _paused = false; } /** * @dev Returns true if the contract is paused, and false otherwise. */ function paused() public view returns (bool) { return _paused; } /** * @dev Modifier to make a function callable only when the contract is not paused. * * Requirements: * * - The contract must not be paused. */ modifier whenNotPaused() { require(!_paused, "Pausable: paused"); _; } /** * @dev Modifier to make a function callable only when the contract is paused. * * Requirements: * * - The contract must be paused. */ modifier whenPaused() { require(_paused, "Pausable: not paused"); _; } /** * @dev Triggers stopped state. * * Requirements: * * - The contract must not be paused. */ function _pause() internal virtual whenNotPaused { _paused = true; emit Paused(_msgSender()); } /** * @dev Returns to normal state. * * Requirements: * * - The contract must be paused. */ function _unpause() internal virtual whenPaused { _paused = false; emit Unpaused(_msgSender()); } uint256[49] private __gap; } // File interfaces/curve/ICurveFi.sol pragma solidity >=0.5.0 <0.8.0; interface ICurveFi { function get_virtual_price() external returns (uint256 out); function add_liquidity( // renbtc/tbtc pool uint256[2] calldata amounts, uint256 min_mint_amount ) external; function add_liquidity( // sBTC pool uint256[3] calldata amounts, uint256 min_mint_amount ) external; function add_liquidity( // bUSD pool uint256[4] calldata amounts, uint256 min_mint_amount ) external; function get_dy( int128 i, int128 j, uint256 dx ) external returns (uint256 out); function get_dy_underlying( int128 i, int128 j, uint256 dx ) external returns (uint256 out); function exchange( int128 i, int128 j, uint256 dx, uint256 min_dy ) external; function exchange( int128 i, int128 j, uint256 dx, uint256 min_dy, uint256 deadline ) external; function exchange_underlying( int128 i, int128 j, uint256 dx, uint256 min_dy ) external; function exchange_underlying( int128 i, int128 j, uint256 dx, uint256 min_dy, uint256 deadline ) external; function remove_liquidity( uint256 _amount, uint256 deadline, uint256[2] calldata min_amounts ) external; function remove_liquidity_imbalance(uint256[2] calldata amounts, uint256 deadline) external; function remove_liquidity_imbalance(uint256[3] calldata amounts, uint256 max_burn_amount) external; function remove_liquidity(uint256 _amount, uint256[3] calldata amounts) external; function remove_liquidity_imbalance(uint256[4] calldata amounts, uint256 max_burn_amount) external; function remove_liquidity(uint256 _amount, uint256[4] calldata amounts) external; function remove_liquidity_one_coin( uint256 _token_amount, int128 i, uint256 _min_amount ) external; function commit_new_parameters( int128 amplification, int128 new_fee, int128 new_admin_fee ) external; function apply_new_parameters() external; function revert_new_parameters() external; function commit_transfer_ownership(address _owner) external; function apply_transfer_ownership() external; function revert_transfer_ownership() external; function withdraw_admin_fees() external; function coins(int128 arg0) external returns (address out); function underlying_coins(int128 arg0) external returns (address out); function balances(int128 arg0) external returns (uint256 out); function A() external returns (int128 out); function fee() external returns (int128 out); function admin_fee() external returns (int128 out); function owner() external returns (address out); function admin_actions_deadline() external returns (uint256 out); function transfer_ownership_deadline() external returns (uint256 out); function future_A() external returns (int128 out); function future_fee() external returns (int128 out); function future_admin_fee() external returns (int128 out); function future_owner() external returns (address out); function calc_withdraw_one_coin(uint256 _token_amount, int128 _i) external view returns (uint256 out); } // File contracts/badger-sett/libraries/BaseSwapper.sol pragma solidity ^0.6.11; /* Expands swapping functionality over base strategy - ETH in and ETH out Variants - Sushiswap support in addition to Uniswap */ contract BaseSwapper { using SafeERC20Upgradeable for IERC20Upgradeable; using AddressUpgradeable for address; using SafeMathUpgradeable for uint256; /// @dev Reset approval and approve exact amount function _safeApproveHelper( address token, address recipient, uint256 amount ) internal { IERC20Upgradeable(token).safeApprove(recipient, 0); IERC20Upgradeable(token).safeApprove(recipient, amount); } } // File contracts/badger-sett/libraries/CurveSwapper.sol pragma solidity ^0.6.11; /* Expands swapping functionality over base strategy - ETH in and ETH out Variants - Sushiswap support in addition to Uniswap */ contract CurveSwapper is BaseSwapper { using SafeERC20Upgradeable for IERC20Upgradeable; using AddressUpgradeable for address; using SafeMathUpgradeable for uint256; function _add_liquidity_single_coin( address swap, address pool, address inputToken, uint256 inputAmount, uint256 inputPosition, uint256 numPoolElements, uint256 min_mint_amount ) internal { _safeApproveHelper(inputToken, swap, inputAmount); if (numPoolElements == 2) { uint256[2] memory convertedAmounts; convertedAmounts[inputPosition] = inputPosition; ICurveFi(swap).add_liquidity(convertedAmounts, min_mint_amount); } else if (numPoolElements == 3) { uint256[3] memory convertedAmounts; convertedAmounts[inputPosition] = inputPosition; ICurveFi(swap).add_liquidity(convertedAmounts, min_mint_amount); } else if (numPoolElements == 4) { uint256[4] memory convertedAmounts; convertedAmounts[inputPosition] = inputPosition; ICurveFi(swap).add_liquidity(convertedAmounts, min_mint_amount); } else { revert("Invalidf number of amount elements"); } } function _add_liquidity( address pool, uint256[2] memory amounts, uint256 min_mint_amount ) internal { ICurveFi(pool).add_liquidity(amounts, min_mint_amount); } function _add_liquidity( address pool, uint256[3] memory amounts, uint256 min_mint_amount ) internal { ICurveFi(pool).add_liquidity(amounts, min_mint_amount); } function _add_liquidity( address pool, uint256[4] memory amounts, uint256 min_mint_amount ) internal { ICurveFi(pool).add_liquidity(amounts, min_mint_amount); } function _remove_liquidity_one_coin( address swap, uint256 _token_amount, int128 i, uint256 _min_amount ) internal { ICurveFi(swap).remove_liquidity_one_coin(_token_amount, i, _min_amount); } } // File deps/@openzeppelin/contracts-upgradeable/access/AccessControlUpgradeable.sol 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 AccessControlUpgradeable is Initializable, ContextUpgradeable { function __AccessControl_init() internal initializer { __Context_init_unchained(); __AccessControl_init_unchained(); } function __AccessControl_init_unchained() internal initializer { } using EnumerableSetUpgradeable for EnumerableSetUpgradeable.AddressSet; using AddressUpgradeable for address; struct RoleData { EnumerableSetUpgradeable.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()); } } uint256[49] private __gap; } // File interfaces/uniswap/IUniswapRouterV2.sol pragma solidity >=0.5.0 <0.8.0; interface IUniswapRouterV2 { function factory() external view returns (address); function addLiquidity( address tokenA, address tokenB, uint256 amountADesired, uint256 amountBDesired, uint256 amountAMin, uint256 amountBMin, address to, uint256 deadline ) external returns ( uint256 amountA, uint256 amountB, uint256 liquidity ); function addLiquidityETH( address token, uint256 amountTokenDesired, uint256 amountTokenMin, uint256 amountETHMin, address to, uint256 deadline ) external payable returns ( uint256 amountToken, uint256 amountETH, uint256 liquidity ); function removeLiquidity( address tokenA, address tokenB, uint256 liquidity, uint256 amountAMin, uint256 amountBMin, address to, uint256 deadline ) external returns (uint256 amountA, uint256 amountB); function getAmountsOut(uint256 amountIn, address[] calldata path) external view returns (uint256[] memory amounts); function getAmountsIn(uint256 amountOut, address[] calldata path) external view returns (uint256[] memory amounts); function swapETHForExactTokens( uint256 amountOut, address[] calldata path, address to, uint256 deadline ) external payable returns (uint256[] memory amounts); function swapExactETHForTokens( uint256 amountOutMin, address[] calldata path, address to, uint256 deadline ) external payable returns (uint256[] memory amounts); function swapExactTokensForETH( uint256 amountIn, uint256 amountOutMin, address[] calldata path, address to, uint256 deadline ) external returns (uint256[] memory amounts); function swapTokensForExactETH( uint256 amountOut, uint256 amountInMax, address[] calldata path, address to, uint256 deadline ) external returns (uint256[] memory amounts); function swapExactTokensForTokens( uint256 amountIn, uint256 amountOutMin, address[] calldata path, address to, uint256 deadline ) external returns (uint256[] memory amounts); function swapTokensForExactTokens( uint256 amountOut, uint256 amountInMax, address[] calldata path, address to, uint256 deadline ) external returns (uint256[] memory amounts); } // File interfaces/uniswap/IUniswapV2Factory.sol pragma solidity >=0.5.0 <0.8.0; interface IUniswapV2Factory { event PairCreated( address indexed token0, address indexed token1, address pair, uint256 ); function getPair(address tokenA, address tokenB) external view returns (address pair); function allPairs(uint256) external view returns (address pair); function allPairsLength() external view returns (uint256); function feeTo() external view returns (address); function feeToSetter() external view returns (address); function createPair(address tokenA, address tokenB) external returns (address pair); } // File contracts/badger-sett/libraries/UniswapSwapper.sol pragma solidity ^0.6.11; /* Expands swapping functionality over base strategy - ETH in and ETH out Variants - Sushiswap support in addition to Uniswap */ contract UniswapSwapper is BaseSwapper{ using SafeERC20Upgradeable for IERC20Upgradeable; using AddressUpgradeable for address; using SafeMathUpgradeable for uint256; address internal constant uniswap = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D; // Uniswap router address internal constant sushiswap = 0xd9e1cE17f2641f24aE83637ab66a2cca9C378B9F; // Sushiswap router function _swapExactTokensForTokens( address router, address startToken, uint256 balance, address[] memory path ) internal { _safeApproveHelper(startToken, router, balance); IUniswapRouterV2(router).swapExactTokensForTokens(balance, 0, path, address(this), now); } function _swapExactETHForTokens(address router, uint256 balance, address[] memory path) internal { IUniswapRouterV2(uniswap).swapExactETHForTokens{value: balance}(0, path, address(this), now); } function _swapExactTokensForETH( address router, address startToken, uint256 balance, address[] memory path ) internal { _safeApproveHelper(startToken, router, balance); IUniswapRouterV2(router).swapExactTokensForETH(balance, 0, path, address(this), now); } function _getPair(address router, address token0, address token1) internal view returns (address) { address factory = IUniswapRouterV2(router).factory(); return IUniswapV2Factory(factory).getPair(token0, token1); } /// @notice Add liquidity to uniswap for specified token pair, utilizing the maximum balance possible function _addMaxLiquidity(address router, address token0, address token1) internal { uint256 _token0Balance = IERC20Upgradeable(token0).balanceOf(address(this)); uint256 _token1Balance = IERC20Upgradeable(token1).balanceOf(address(this)); _safeApproveHelper(token0, router, _token0Balance); _safeApproveHelper(token1, router, _token1Balance); IUniswapRouterV2(router).addLiquidity(token0, token1, _token0Balance, _token1Balance, 0, 0, address(this), block.timestamp); } function _addMaxLiquidityEth(address router, address token0) internal { uint256 _token0Balance = IERC20Upgradeable(token0).balanceOf(address(this)); uint256 _ethBalance = address(this).balance; _safeApproveHelper(token0, router, _token0Balance); IUniswapRouterV2(router).addLiquidityETH{ value: address(this).balance }(token0, _token0Balance, 0, 0, address(this), block.timestamp); } } // File contracts/badger-sett/libraries/TokenSwapPathRegistry.sol pragma solidity ^0.6.11; /* Expands swapping functionality over base strategy - ETH in and ETH out Variants - Sushiswap support in addition to Uniswap */ contract TokenSwapPathRegistry { mapping(address => mapping(address => address[])) public tokenSwapPaths; event TokenSwapPathSet(address tokenIn, address tokenOut, address[] path); function getTokenSwapPath(address tokenIn, address tokenOut) public view returns (address[] memory) { return tokenSwapPaths[tokenIn][tokenOut]; } function _setTokenSwapPath( address tokenIn, address tokenOut, address[] memory path ) internal { tokenSwapPaths[tokenIn][tokenOut] = path; emit TokenSwapPathSet(tokenIn, tokenOut, path); } } // File deps/@openzeppelin/contracts-upgradeable/math/MathUpgradeable.sol pragma solidity ^0.6.0; /** * @dev Standard math utilities missing in the Solidity language. */ library MathUpgradeable { /** * @dev Returns the largest of two numbers. */ function max(uint256 a, uint256 b) internal pure returns (uint256) { return a >= b ? a : b; } /** * @dev Returns the smallest of two numbers. */ function min(uint256 a, uint256 b) internal pure returns (uint256) { return a < b ? a : b; } /** * @dev Returns the average of two numbers. The result is rounded towards * zero. */ function average(uint256 a, uint256 b) internal pure returns (uint256) { // (a + b) / 2 can overflow, so we distribute return (a / 2) + (b / 2) + ((a % 2 + b % 2) / 2); } } // File interfaces/badger/IController.sol pragma solidity >=0.5.0 <0.8.0; interface IController { function withdraw(address, uint256) external; function strategies(address) external view returns (address); function approvedStrategies(address, address) external view returns (address); function balanceOf(address) external view returns (uint256); function earn(address, uint256) external; function approveStrategy(address, address) external; function setStrategy(address, address) external; function setVault(address, address) external; function want(address) external view returns (address); function rewards() external view returns (address); function vaults(address) external view returns (address); } // File interfaces/badger/IStrategy.sol pragma solidity >=0.5.0 <0.8.0; interface IStrategy { function want() external view returns (address); function deposit() external; // NOTE: must exclude any tokens used in the yield // Controller role - withdraw should return to Controller function withdrawOther(address) external returns (uint256 balance); // Controller | Vault role - withdraw should always return to Vault function withdraw(uint256) external; // Controller | Vault role - withdraw should always return to Vault function withdrawAll() external returns (uint256); function balanceOf() external view returns (uint256); function getName() external pure returns (string memory); function setStrategist(address _strategist) external; function setWithdrawalFee(uint256 _withdrawalFee) external; function setPerformanceFeeStrategist(uint256 _performanceFeeStrategist) external; function setPerformanceFeeGovernance(uint256 _performanceFeeGovernance) external; function setGovernance(address _governance) external; function setController(address _controller) external; function tend() external; function harvest() external; } // File contracts/badger-sett/SettAccessControl.sol pragma solidity ^0.6.11; /* Common base for permissioned roles throughout Sett ecosystem */ contract SettAccessControl is Initializable { address public governance; address public strategist; address public keeper; // ===== MODIFIERS ===== function _onlyGovernance() internal view { require(msg.sender == governance, "onlyGovernance"); } function _onlyGovernanceOrStrategist() internal view { require(msg.sender == strategist || msg.sender == governance, "onlyGovernanceOrStrategist"); } function _onlyAuthorizedActors() internal view { require(msg.sender == keeper || msg.sender == governance, "onlyAuthorizedActors"); } // ===== PERMISSIONED ACTIONS ===== /// @notice Change strategist address /// @notice Can only be changed by governance itself function setStrategist(address _strategist) external { _onlyGovernance(); strategist = _strategist; } /// @notice Change keeper address /// @notice Can only be changed by governance itself function setKeeper(address _keeper) external { _onlyGovernance(); keeper = _keeper; } /// @notice Change governance address /// @notice Can only be changed by governance itself function setGovernance(address _governance) public { _onlyGovernance(); governance = _governance; } uint256[50] private __gap; } // File contracts/badger-sett/strategies/BaseStrategy.sol pragma solidity ^0.6.11; /* ===== Badger Base Strategy ===== Common base class for all Sett strategies Changelog V1.1 - Verify amount unrolled from strategy positions on withdraw() is within a threshold relative to the requested amount as a sanity check - Add version number which is displayed with baseStrategyVersion(). If a strategy does not implement this function, it can be assumed to be 1.0 V1.2 - Remove idle want handling from base withdraw() function. This should be handled as the strategy sees fit in _withdrawSome() */ abstract contract BaseStrategy is PausableUpgradeable, SettAccessControl { using SafeERC20Upgradeable for IERC20Upgradeable; using AddressUpgradeable for address; using SafeMathUpgradeable for uint256; event Withdraw(uint256 amount); event WithdrawAll(uint256 balance); event WithdrawOther(address token, uint256 amount); event SetStrategist(address strategist); event SetGovernance(address governance); event SetController(address controller); event SetWithdrawalFee(uint256 withdrawalFee); event SetPerformanceFeeStrategist(uint256 performanceFeeStrategist); event SetPerformanceFeeGovernance(uint256 performanceFeeGovernance); event Harvest(uint256 harvested, uint256 indexed blockNumber); event Tend(uint256 tended); address public want; // Want: Curve.fi renBTC/wBTC (crvRenWBTC) LP token uint256 public performanceFeeGovernance; uint256 public performanceFeeStrategist; uint256 public withdrawalFee; uint256 public constant MAX_FEE = 10000; address public controller; address public guardian; uint256 public withdrawalMaxDeviationThreshold; function __BaseStrategy_init( address _governance, address _strategist, address _controller, address _keeper, address _guardian ) public initializer whenNotPaused { __Pausable_init(); governance = _governance; strategist = _strategist; keeper = _keeper; controller = _controller; guardian = _guardian; withdrawalMaxDeviationThreshold = 50; } // ===== Modifiers ===== function _onlyController() internal view { require(msg.sender == controller, "onlyController"); } function _onlyAuthorizedActorsOrController() internal view { require(msg.sender == keeper || msg.sender == governance || msg.sender == controller, "onlyAuthorizedActorsOrController"); } function _onlyAuthorizedPausers() internal view { require(msg.sender == guardian || msg.sender == governance, "onlyPausers"); } /// ===== View Functions ===== function baseStrategyVersion() public view returns (string memory) { return "1.2"; } /// @notice Get the balance of want held idle in the Strategy function balanceOfWant() public view returns (uint256) { return IERC20Upgradeable(want).balanceOf(address(this)); } /// @notice Get the total balance of want realized in the strategy, whether idle or active in Strategy positions. function balanceOf() public virtual view returns (uint256) { return balanceOfWant().add(balanceOfPool()); } function isTendable() public virtual view returns (bool) { return false; } function isProtectedToken(address token) public view returns (bool) { address[] memory protectedTokens = getProtectedTokens(); for (uint256 i = 0; i < protectedTokens.length; i++) { if (token == protectedTokens[i]) { return true; } } return false; } /// ===== Permissioned Actions: Governance ===== function setGuardian(address _guardian) external { _onlyGovernance(); guardian = _guardian; } function setWithdrawalFee(uint256 _withdrawalFee) external { _onlyGovernance(); require(_withdrawalFee <= MAX_FEE, "base-strategy/excessive-withdrawal-fee"); withdrawalFee = _withdrawalFee; } function setPerformanceFeeStrategist(uint256 _performanceFeeStrategist) external { _onlyGovernance(); require(_performanceFeeStrategist <= MAX_FEE, "base-strategy/excessive-strategist-performance-fee"); performanceFeeStrategist = _performanceFeeStrategist; } function setPerformanceFeeGovernance(uint256 _performanceFeeGovernance) external { _onlyGovernance(); require(_performanceFeeGovernance <= MAX_FEE, "base-strategy/excessive-governance-performance-fee"); performanceFeeGovernance = _performanceFeeGovernance; } function setController(address _controller) external { _onlyGovernance(); controller = _controller; } function setWithdrawalMaxDeviationThreshold(uint256 _threshold) external { _onlyGovernance(); require(_threshold <= MAX_FEE, "base-strategy/excessive-max-deviation-threshold"); withdrawalMaxDeviationThreshold = _threshold; } function deposit() public virtual whenNotPaused { _onlyAuthorizedActorsOrController(); uint256 _want = IERC20Upgradeable(want).balanceOf(address(this)); if (_want > 0) { _deposit(_want); } _postDeposit(); } // ===== Permissioned Actions: Controller ===== /// @notice Controller-only function to Withdraw partial funds, normally used with a vault withdrawal function withdrawAll() external virtual whenNotPaused returns (uint256 balance) { _onlyController(); _withdrawAll(); _transferToVault(IERC20Upgradeable(want).balanceOf(address(this))); } /// @notice Withdraw partial funds from the strategy, unrolling from strategy positions as necessary /// @notice Processes withdrawal fee if present /// @dev If it fails to recover sufficient funds (defined by withdrawalMaxDeviationThreshold), the withdrawal should fail so that this unexpected behavior can be investigated function withdraw(uint256 _amount) external virtual whenNotPaused { _onlyController(); // Withdraw from strategy positions, typically taking from any idle want first. _withdrawSome(_amount); uint256 _postWithdraw = IERC20Upgradeable(want).balanceOf(address(this)); // Sanity check: Ensure we were able to retrieve sufficent want from strategy positions // If we end up with less than the amount requested, make sure it does not deviate beyond a maximum threshold if (_postWithdraw < _amount) { uint256 diff = _diff(_amount, _postWithdraw); // Require that difference between expected and actual values is less than the deviation threshold percentage require(diff <= _amount.mul(withdrawalMaxDeviationThreshold).div(MAX_FEE), "base-strategy/withdraw-exceed-max-deviation-threshold"); } // Return the amount actually withdrawn if less than amount requested uint256 _toWithdraw = MathUpgradeable.min(_postWithdraw, _amount); // Process withdrawal fee uint256 _fee = _processWithdrawalFee(_toWithdraw); // Transfer remaining to Vault to handle withdrawal _transferToVault(_toWithdraw.sub(_fee)); } // NOTE: must exclude any tokens used in the yield // Controller role - withdraw should return to Controller function withdrawOther(address _asset) external virtual whenNotPaused returns (uint256 balance) { _onlyController(); _onlyNotProtectedTokens(_asset); balance = IERC20Upgradeable(_asset).balanceOf(address(this)); IERC20Upgradeable(_asset).safeTransfer(controller, balance); } /// ===== Permissioned Actions: Authoized Contract Pausers ===== function pause() external { _onlyAuthorizedPausers(); _pause(); } function unpause() external { _onlyGovernance(); _unpause(); } /// ===== Internal Helper Functions ===== /// @notice If withdrawal fee is active, take the appropriate amount from the given value and transfer to rewards recipient /// @return The withdrawal fee that was taken function _processWithdrawalFee(uint256 _amount) internal returns (uint256) { if (withdrawalFee == 0) { return 0; } uint256 fee = _amount.mul(withdrawalFee).div(MAX_FEE); IERC20Upgradeable(want).safeTransfer(IController(controller).rewards(), fee); return fee; } /// @dev Helper function to process an arbitrary fee /// @dev If the fee is active, transfers a given portion in basis points of the specified value to the recipient /// @return The fee that was taken function _processFee( address token, uint256 amount, uint256 feeBps, address recipient ) internal returns (uint256) { if (feeBps == 0) { return 0; } uint256 fee = amount.mul(feeBps).div(MAX_FEE); IERC20Upgradeable(token).safeTransfer(recipient, fee); return fee; } function _transferToVault(uint256 _amount) internal { address _vault = IController(controller).vaults(address(want)); require(_vault != address(0), "!vault"); // additional protection so we don't burn the funds IERC20Upgradeable(want).safeTransfer(_vault, _amount); } /// @notice Utility function to diff two numbers, expects higher value in first position function _diff(uint256 a, uint256 b) internal pure returns (uint256) { require(a >= b, "diff/expected-higher-number-in-first-position"); return a.sub(b); } // ===== Abstract Functions: To be implemented by specific Strategies ===== /// @dev Internal deposit logic to be implemented by Stratgies function _deposit(uint256 _want) internal virtual; function _postDeposit() internal virtual { //no-op by default } /// @notice Specify tokens used in yield process, should not be available to withdraw via withdrawOther() function _onlyNotProtectedTokens(address _asset) internal virtual; function getProtectedTokens() public virtual view returns (address[] memory) { return new address[](0); } /// @dev Internal logic for strategy migration. Should exit positions as efficiently as possible function _withdrawAll() internal virtual; /// @dev Internal logic for partial withdrawals. Should exit positions as efficiently as possible. /// @dev The withdraw() function shell automatically uses idle want in the strategy before attempting to withdraw more using this function _withdrawSome(uint256 _amount) internal virtual returns (uint256); /// @dev Realize returns from positions /// @dev Returns can be reinvested into positions, or distributed in another fashion /// @dev Performance fees should also be implemented in this function /// @dev Override function stub is removed as each strategy can have it's own return signature for STATICCALL // function harvest() external virtual; /// @dev User-friendly name for this strategy for purposes of convenient reading function getName() external virtual pure returns (string memory); /// @dev Balance of want currently held in strategy positions function balanceOfPool() public virtual view returns (uint256); uint256[49] private __gap; } // File contracts/badger-sett/strategies/convex/StrategyCvxHelper.sol pragma solidity ^0.6.11; /* 1. Stake cvxCrv 2. Sell earned rewards into cvxCrv position and restake */ contract StrategyCvxHelper is BaseStrategy, CurveSwapper, UniswapSwapper, TokenSwapPathRegistry { using SafeERC20Upgradeable for IERC20Upgradeable; using AddressUpgradeable for address; using SafeMathUpgradeable for uint256; using EnumerableSetUpgradeable for EnumerableSetUpgradeable.AddressSet; // ===== Token Registry ===== address public constant wbtc = 0x2260FAC5E5542a773Aa44fBCfeDf7C193bc2C599; address public constant weth = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2; address public constant crv = 0xD533a949740bb3306d119CC777fa900bA034cd52; address public constant cvx = 0x4e3FBD56CD56c3e72c1403e103b45Db9da5B9D2B; address public constant cvxCrv = 0x62B9c7356A2Dc64a1969e19C23e4f579F9810Aa7; address public constant usdc = 0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48; address public constant threeCrv = 0x6c3F90f043a72FA612cbac8115EE7e52BDe6E490; IERC20Upgradeable public constant crvToken = IERC20Upgradeable(0xD533a949740bb3306d119CC777fa900bA034cd52); IERC20Upgradeable public constant cvxToken = IERC20Upgradeable(0x4e3FBD56CD56c3e72c1403e103b45Db9da5B9D2B); IERC20Upgradeable public constant cvxCrvToken = IERC20Upgradeable(0x62B9c7356A2Dc64a1969e19C23e4f579F9810Aa7); IERC20Upgradeable public constant usdcToken = IERC20Upgradeable(0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48); IERC20Upgradeable public constant threeCrvToken = IERC20Upgradeable(0x6c3F90f043a72FA612cbac8115EE7e52BDe6E490); // ===== Convex Registry ===== CrvDepositor public constant crvDepositor = CrvDepositor(0x8014595F2AB54cD7c604B00E9fb932176fDc86Ae); // Convert CRV -> cvxCRV/ETH SLP IBooster public constant booster = IBooster(0xF403C135812408BFbE8713b5A23a04b3D48AAE31); ICvxRewardsPool public constant cvxRewardsPool = ICvxRewardsPool(0xCF50b810E57Ac33B91dCF525C6ddd9881B139332); uint256 public constant MAX_UINT_256 = uint256(-1); event HarvestState(uint256 timestamp, uint256 blockNumber); event WithdrawState(uint256 toWithdraw, uint256 preWant, uint256 postWant, uint256 withdrawn); struct TokenSwapData { address tokenIn; uint256 totalSold; uint256 wantGained; } event TendState(uint256 crvTended, uint256 cvxTended, uint256 cvxCrvHarvested); function initialize( address _governance, address _strategist, address _controller, address _keeper, address _guardian, uint256[3] memory _feeConfig ) public initializer whenNotPaused { __BaseStrategy_init(_governance, _strategist, _controller, _keeper, _guardian); want = cvx; performanceFeeGovernance = _feeConfig[0]; performanceFeeStrategist = _feeConfig[1]; withdrawalFee = _feeConfig[2]; address[] memory path = new address[](3); path[0] = cvxCrv; path[1] = weth; path[2] = cvx; _setTokenSwapPath(cvxCrv, cvx, path); // Approvals: Staking Pool cvxToken.approve(address(cvxRewardsPool), MAX_UINT_256); } /// ===== View Functions ===== function version() external pure returns (string memory) { return "1.0"; } function getName() external pure override returns (string memory) { return "StrategyCvxHelper"; } function balanceOfPool() public view override returns (uint256) { return cvxRewardsPool.balanceOf(address(this)); } function getProtectedTokens() public view override returns (address[] memory) { address[] memory protectedTokens = new address[](2); protectedTokens[0] = want; protectedTokens[1] = cvx; return protectedTokens; } function isTendable() public view override returns (bool) { return false; } /// ===== Internal Core Implementations ===== function _onlyNotProtectedTokens(address _asset) internal override { require(!isProtectedToken(_asset)); } /// @dev Deposit Badger into the staking contract function _deposit(uint256 _want) internal override { // Deposit all want in core staking pool cvxRewardsPool.stake(_want); } /// @dev Unroll from all strategy positions, and transfer non-core tokens to controller rewards function _withdrawAll() internal override { // TODO: Functionality not required for initial migration // Note: All want is automatically withdrawn outside this "inner hook" in base strategy function } /// @dev Withdraw want from staking rewards, using earnings first function _withdrawSome(uint256 _amount) internal override returns (uint256) { // Get idle want in the strategy uint256 _preWant = IERC20Upgradeable(want).balanceOf(address(this)); // If we lack sufficient idle want, withdraw the difference from the strategy position if (_preWant < _amount) { uint256 _toWithdraw = _amount.sub(_preWant); cvxRewardsPool.withdraw(_toWithdraw, false); // Note: Withdrawl process will earn sushi, this will be deposited into SushiBar on next tend() } // Confirm how much want we actually end up with uint256 _postWant = IERC20Upgradeable(want).balanceOf(address(this)); // Return the actual amount withdrawn if less than requested uint256 _withdrawn = MathUpgradeable.min(_postWant, _amount); emit WithdrawState(_amount, _preWant, _postWant, _withdrawn); return _withdrawn; } function _tendGainsFromPositions() internal { if (cvxRewardsPool.earned(address(this)) > 0) { cvxRewardsPool.getReward(true); } } function harvest() external whenNotPaused returns (uint256 cvxHarvested) { _onlyAuthorizedActors(); // 1. Harvest gains from positions _tendGainsFromPositions(); // 2. Swap cvxCRV tokens to CVX uint256 cvxCrvBalance = cvxCrvToken.balanceOf(address(this)); if (cvxCrvBalance > 0) { _swapExactTokensForTokens(sushiswap, cvxCrv, cvxCrvBalance, getTokenSwapPath(cvxCrv, cvx)); } // Track harvested + converted coin balance of want cvxHarvested = cvxToken.balanceOf(address(this)); // 3. Stake all CVX if (cvxHarvested > 0) { cvxRewardsPool.stake(cvxHarvested); } emit Tend(cvxHarvested); return cvxHarvested; } }
===== Internal Core Implementations =====
function _onlyNotProtectedTokens(address _asset) internal override { require(!isProtectedToken(_asset)); }
1,496,419
./full_match/42220/0x02c79D1d360732e23Cf135996E91E10fC0C5e23e/sources/contracts/community/CommunityImplementation.sol
Checks a manager signature _expirationTimestamp timestamp when the signature will expire/expired _signature the signature of a manager/
function _checkManagerSignature(uint256 _expirationTimestamp, bytes calldata _signature) internal { require( msg.sender == communityAdmin.authorizedWalletAddress(), "Community: Sender must be the backend wallet" ); require(_expirationTimestamp >= block.timestamp, "Community: Signature too old"); bytes32 _messageHash = keccak256( abi.encodePacked(msg.sender, address(this), _expirationTimestamp) ); address _signerAddress = _messageHash.toEthSignedMessageHash().recover(_signature); require(hasRole(MANAGER_ROLE, _signerAddress), "Community: Invalid signature"); }
16,323,886
./partial_match/42/0x6076eCda565f5325642AaEe0e9f7A4B916d2dFf1/sources/FeePool.sol
Send the rewards to claiming address - will be locked in rewardEscrow. account The address to send the fees to. snxAmount The amount of PERI./ Record vesting entry for claiming address and amount PERI already minted to rewardEscrow balance
function _payRewards(address account, uint snxAmount) internal notFeeAddress(account) { uint escrowDuration = 52 weeks; uint periAmount; uint usdcAmount; FeePoolState _feePoolState = feePoolState(); (periAmount, usdcAmount) = _feePoolState.getAccountsKindsEntry(account, 0); periAmount = snxAmount.multiplyDecimal(periAmount.multiplyDecimalRoundPrecise(80)); usdcAmount = snxAmount.multiplyDecimal(usdcAmount.multiplyDecimalRoundPrecise(20)); console.log("periamount :" , periAmount); console.log("usdcAmount :" , usdcAmount); console.log("snxAmount :" , snxAmount); rewardEscrowV2().appendVestingEntry(account, snxAmount, escrowDuration); }
9,020,154
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, "Only allowed by owner"); _; } function transferOwnership(address payable _newOwner) public onlyOwner { owner = _newOwner; emit OwnershipTransferred(msg.sender, _newOwner); } } // ---------------------------------------------------------------------------- // 'SCROOGE' token contract // Symbol : SCRG // Name : SCROOGE // Total supply: 3000 // Decimals : 18 // ---------------------------------------------------------------------------- // ERC20 Token, with the addition of symbol, name and decimals and assisted // token transfers // ---------------------------------------------------------------------------- contract SCROOGE is IERC20, Owned { using SafeMath for uint256; string public symbol = "SCRG"; string public name = "SCROOGE"; uint256 public decimals = 18; uint256 _totalSupply = 3000 * 10 ** (18); // 3000 mapping(address => uint256) balances; mapping(address => mapping(address => uint256)) allowed; uint256 saleStart; uint256 public ethsReceived; uint256 ethCap = 100 ether; mapping(address => bool) whitelisted; // ------------------------------------------------------------------------ // Constructor // ------------------------------------------------------------------------ constructor() public { owner = 0x677DdD722f07f5B4925762Be5cE98b50D24a347e; balances[address(this)] = 3000 * 10 ** (18); // 3000 emit Transfer(address(0), address(this), 3000 * 10 ** (18)); saleStart = 1606071600; // 22 Nov, 2020 7pm GMT } /*****************Pre sale functions***********************/ modifier saleOpen{ if(block.timestamp <= saleStart.add(1 hours)) // within the first hour require(whitelisted[msg.sender], "Only whitelisted addresses allowed during 1st hour"); require(ethsReceived < ethCap, "100 ether cap is reached"); _; } receive() external payable saleOpen{ uint256 investment = msg.value; if(ethsReceived.add(investment) > ethCap){ investment = ethCap.sub(ethsReceived); // return the extra investment msg.sender.transfer(msg.value.sub(investment)); } uint256 tokens = getTokenAmount(investment); require(_transfer(msg.sender, tokens), "Sale is over"); // send received funds to the owner owner.transfer(investment); ethsReceived = ethsReceived.add(investment); } function getTokenAmount(uint256 amount) private pure returns(uint256){ return (amount.mul(10)); // 10 tokens per ether } function burnUnSoldTokens() external onlyOwner{ require(ethsReceived >= ethCap, "sale is not close"); burnTokens(balances[address(this)]); } function _transfer(address to, uint256 tokens) private returns(bool){ // prevent transfer to 0x0, use burn instead require(address(to) != address(0)); require(balances[address(this)] >= tokens, "Insufficient tokens in contract"); balances[address(this)] = balances[address(this)].sub(tokens); balances[to] = balances[to].add(tokens); emit Transfer(address(this),to,tokens); return true; } // ------------------------------------------------------------------------ // Whitelist the batch of users // @param `users` the array of addresses of the users to be whitelisted // only allowed by owner // ------------------------------------------------------------------------ function addToWhitelist(address[] calldata users) external onlyOwner{ require(users.length <= 20, "Max batch allowed is 20"); for(uint256 i = 0; i< users.length; i++) { whitelisted[users[i]] = true; } } /** 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); balances[to] = balances[to].add(tokens); emit Transfer(msg.sender, to, tokens); return true; } // ------------------------------------------------------------------------ // Transfer `tokens` from the `from` account to the `to` account // // The calling account must already have sufficient tokens approve(...)-d // for spending from the `from` account and // - From account must have sufficient balance to transfer // - Spender must have sufficient allowance to transfer // - 0 value transfers are allowed // ------------------------------------------------------------------------ function transferFrom(address from, address to, 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); balances[to] = balances[to].add(tokens); emit Transfer(from, to, tokens.sub(tokens)); return true; } // ------------------------------------------------------------------------ // Burn the `value` amount of tokens from the `account` // ------------------------------------------------------------------------ function burnTokens(uint256 value) private{ require(_totalSupply >= value); // burn only unsold tokens _totalSupply = _totalSupply.sub(value); balances[address(this)] = balances[address(this)].sub(value); emit Transfer(address(this), address(0), value); } }
------------------------------------------------------------------------ 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 ------------------------------------------------------------------------ prevent transfer to 0x0, use burn instead
function transfer(address to, uint256 tokens) public override returns (bool success) { require(address(to) != address(0)); require(balances[msg.sender] >= tokens ); require(balances[to] + tokens >= balances[to]); balances[msg.sender] = balances[msg.sender].sub(tokens); balances[to] = balances[to].add(tokens); emit Transfer(msg.sender, to, tokens); return true; }
1,544,955
// SPDX-License-Identifier: MIT // Reference: copied from https://github.com/sushiswap/sushiswap/blob/canary/contracts/MasterChefV2.sol // Reference: https://github.com/sushiswap/sushiswap/blob/canary/contracts/MiniChefV2.sol pragma solidity >=0.8.4; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; import "@openzeppelin/contracts/utils/Multicall.sol"; import "./interfaces/IRewarder.sol"; import "./libraries/SafeMath.sol"; import "./libraries/SignedSafeMath.sol"; // @notice Staking contract to reward Tokens for stakers contract Staking is Ownable, Multicall { using SafeMath for uint256; using SafeMath128 for uint128; using SafeERC20 for IERC20; using SignedSafeMath for int256; /// @notice Info of each stakers. /// `amount` LP token amount the user has provided. /// `rewardDebt` The amount of Token entitled to the user. struct UserInfo { uint256 amount; int256 rewardDebt; } // The amount of RewardToken entitled to a user but is pending to be distributed is: // // pending reward = (user.amount * pool.accRewardPerShare) - user.rewardDebt // // Whenever a user deposits or withdraws LP tokens to a pool. Here's what happens: // 1. The pool's `accRewardPerShare` (and `lastRewardBlock`) gets updated. // 2. User receives the pending reward sent to his/her address. // 3. User's `amount` gets updated. // 4. User's `rewardDebt` gets updated. /// @notice Info of each Staking pool. /// `allocPoint` The amount of allocation points assigned to the pool. /// Also known as the amount of Token to distribute per block. struct PoolInfo { uint128 accRewardPerShare; uint64 lastRewardBlock; uint64 allocPoint; } /// @notice Address of Reward Token contract. IERC20 public immutable rewardToken; /// @notice Info of each Staking pool. PoolInfo[] public poolInfo; /// @notice Address of the LP token for each Staking pool. IERC20[] public lpToken; /// @notice Address of each `IRewarder` contract in Staking. IRewarder[] public rewarder; /// @notice Info of each user that stakes LP tokens. mapping(uint256 => mapping(address => UserInfo)) public userInfo; /// @dev Total allocation points. Must be the sum of all allocation points in all pools. uint256 public totalAllocPoint; uint256 public blockReward; uint256 private constant ACC_PRECISION = 1e12; event Deposit(address indexed user, uint256 indexed pid, uint256 amount, address indexed to); event Withdraw(address indexed user, uint256 indexed pid, uint256 amount, address indexed to); event EmergencyWithdraw(address indexed user, uint256 indexed pid, uint256 amount, address indexed to); event Harvest(address indexed user, uint256 indexed pid, uint256 amount); event LogPoolAddition(uint256 indexed pid, uint256 allocPoint, IERC20 indexed lpToken, IRewarder indexed rewarder); event LogSetPool(uint256 indexed pid, uint256 allocPoint, IRewarder indexed rewarder, bool overwrite); event LogUpdatePool(uint256 indexed pid, uint64 lastRewardBlock, uint256 lpSupply, uint256 accRewardPerShare); event LogInit(); event LogBlockReward(uint256 blockReward); /// @param _rewardToken The reward token contract address. /// @param _blockReward Initial Token Reward per block. constructor(IERC20 _rewardToken, uint256 _blockReward) public { rewardToken = _rewardToken; blockReward = _blockReward; } /// @notice set block reward. function setBlockReward(uint256 _blockReward) public onlyOwner { massUpdatePools(); blockReward = _blockReward; emit LogBlockReward(_blockReward); } /// @notice Returns the number of Staking pools. function poolLength() public view returns (uint256 pools) { pools = poolInfo.length; } function checkPoolDuplicate(IERC20 _lpToken) public { uint256 length = lpToken.length; for (uint256 pid = 0; pid < length; ++pid) { require(lpToken[pid] != _lpToken, "Staking: existing pool"); } } /// @notice Add a new LP to the pool. Can only be called by the owner. /// DO NOT add the same LP token more than once. Rewards will be messed up if you do. /// @param allocPoint AP of the new pool. /// @param _lpToken Address of the LP ERC-20 token. /// @param _rewarder Address of the rewarder delegate. function add( uint256 allocPoint, IERC20 _lpToken, IRewarder _rewarder ) public onlyOwner { checkPoolDuplicate(_lpToken); uint256 lastRewardBlock = block.number; totalAllocPoint = totalAllocPoint.add(allocPoint); lpToken.push(_lpToken); rewarder.push(_rewarder); poolInfo.push( PoolInfo({ allocPoint: allocPoint.to64(), lastRewardBlock: lastRewardBlock.to64(), accRewardPerShare: 0 }) ); emit LogPoolAddition(lpToken.length.sub(1), allocPoint, _lpToken, _rewarder); } /// @notice Update the given pool's Reward token allocation point and `IRewarder` contract. Can only be called by the owner. /// @param _pid The index of the pool. See `poolInfo`. /// @param _allocPoint New AP of the pool. /// @param _rewarder Address of the rewarder delegate. /// @param overwrite True if _rewarder should be `set`. Otherwise `_rewarder` is ignored. function set( uint256 _pid, uint256 _allocPoint, IRewarder _rewarder, bool overwrite ) public onlyOwner { massUpdatePools(); totalAllocPoint = totalAllocPoint.sub(poolInfo[_pid].allocPoint).add(_allocPoint); poolInfo[_pid].allocPoint = _allocPoint.to64(); if (overwrite) { rewarder[_pid] = _rewarder; } emit LogSetPool(_pid, _allocPoint, overwrite ? _rewarder : rewarder[_pid], overwrite); } /// @notice View function to see pending Rewards on frontend. /// @param _pid The index of the pool. See `poolInfo`. /// @param _user Address of user. /// @return pending Token reward for a given user. function pendingRewards(uint256 _pid, address _user) external view returns (uint256 pending) { PoolInfo memory pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][_user]; uint256 accRewardPerShare = pool.accRewardPerShare; uint256 lpSupply = lpToken[_pid].balanceOf(address(this)); if (block.number > pool.lastRewardBlock && lpSupply != 0) { uint256 blocks = block.number.sub(pool.lastRewardBlock); uint256 rewards = blocks.mul(blockReward).mul(pool.allocPoint) / totalAllocPoint; accRewardPerShare = accRewardPerShare.add(rewards.mul(ACC_PRECISION) / lpSupply); } pending = int256(user.amount.mul(accRewardPerShare) / ACC_PRECISION).sub(user.rewardDebt).toUInt256(); } /// @notice Update reward variables for all pools. Be careful of gas spending! function massUpdatePools() public { uint256 length = poolInfo.length; for (uint256 pid = 0; pid < length; ++pid) { updatePool(pid); } } /// @notice Update reward variables of the given pool. /// @param pid The index of the pool. See `poolInfo`. /// @return pool Returns the pool that was updated. function updatePool(uint256 pid) public returns (PoolInfo memory pool) { pool = poolInfo[pid]; if (block.number > pool.lastRewardBlock) { uint256 lpSupply = lpToken[pid].balanceOf(address(this)); if (lpSupply > 0) { uint256 blocks = block.number.sub(pool.lastRewardBlock); uint256 rewards = blocks.mul(blockReward).mul(pool.allocPoint) / totalAllocPoint; pool.accRewardPerShare = pool.accRewardPerShare.add((rewards.mul(ACC_PRECISION) / lpSupply).to128()); } pool.lastRewardBlock = block.number.to64(); poolInfo[pid] = pool; emit LogUpdatePool(pid, pool.lastRewardBlock, lpSupply, pool.accRewardPerShare); } } /// @notice Deposit LP tokens to Staking contract for Reward token allocation. /// @param pid The index of the pool. See `poolInfo`. /// @param amount LP token amount to deposit. /// @param to The receiver of `amount` deposit benefit. function deposit( uint256 pid, uint256 amount, address to ) public { PoolInfo memory pool = updatePool(pid); UserInfo storage user = userInfo[pid][to]; // Effects user.amount = user.amount.add(amount); user.rewardDebt = user.rewardDebt.add(int256(amount.mul(pool.accRewardPerShare) / ACC_PRECISION)); // Interactions IRewarder _rewarder = rewarder[pid]; if (address(_rewarder) != address(0)) { _rewarder.onTokenReward(pid, to, to, 0, user.amount); } lpToken[pid].safeTransferFrom(msg.sender, address(this), amount); emit Deposit(msg.sender, pid, amount, to); } /// @notice Withdraw LP tokens from Staking contract. /// @param pid The index of the pool. See `poolInfo`. /// @param amount LP token amount to withdraw. /// @param to Receiver of the LP tokens. function withdraw( uint256 pid, uint256 amount, address to ) public { PoolInfo memory pool = updatePool(pid); UserInfo storage user = userInfo[pid][msg.sender]; // Effects user.rewardDebt = user.rewardDebt.sub(int256(amount.mul(pool.accRewardPerShare) / ACC_PRECISION)); user.amount = user.amount.sub(amount); // Interactions IRewarder _rewarder = rewarder[pid]; if (address(_rewarder) != address(0)) { _rewarder.onTokenReward(pid, msg.sender, to, 0, user.amount); } lpToken[pid].safeTransfer(to, amount); emit Withdraw(msg.sender, pid, amount, to); } /// @notice Harvest proceeds for transaction sender to `to`. /// @param pid The index of the pool. See `poolInfo`. /// @param to Receiver of Token rewards. function harvest(uint256 pid, address to) public { PoolInfo memory pool = updatePool(pid); UserInfo storage user = userInfo[pid][msg.sender]; int256 accumulatedRewards = int256(user.amount.mul(pool.accRewardPerShare) / ACC_PRECISION); uint256 _pendingRewards = accumulatedRewards.sub(user.rewardDebt).toUInt256(); // Effects user.rewardDebt = accumulatedRewards; // Interactions if (_pendingRewards != 0) { rewardToken.safeTransfer(to, _pendingRewards); } IRewarder _rewarder = rewarder[pid]; if (address(_rewarder) != address(0)) { _rewarder.onTokenReward(pid, msg.sender, to, _pendingRewards, user.amount); } emit Harvest(msg.sender, pid, _pendingRewards); } /// @notice Withdraw LP tokens from Staking contract and harvest proceeds for transaction sender to `to`. /// @param pid The index of the pool. See `poolInfo`. /// @param amount LP token amount to withdraw. /// @param to Receiver of the LP tokens and Token rewards. function withdrawAndHarvest( uint256 pid, uint256 amount, address to ) public { PoolInfo memory pool = updatePool(pid); UserInfo storage user = userInfo[pid][msg.sender]; int256 accumulatedRewards = int256(user.amount.mul(pool.accRewardPerShare) / ACC_PRECISION); uint256 _pendingRewards = accumulatedRewards.sub(user.rewardDebt).toUInt256(); // Effects user.rewardDebt = accumulatedRewards.sub(int256(amount.mul(pool.accRewardPerShare) / ACC_PRECISION)); user.amount = user.amount.sub(amount); // Interactions rewardToken.safeTransfer(to, _pendingRewards); IRewarder _rewarder = rewarder[pid]; if (address(_rewarder) != address(0)) { _rewarder.onTokenReward(pid, msg.sender, to, _pendingRewards, user.amount); } lpToken[pid].safeTransfer(to, amount); emit Withdraw(msg.sender, pid, amount, to); emit Harvest(msg.sender, pid, _pendingRewards); } /// @notice Withdraw without caring about rewards. EMERGENCY ONLY. /// @param pid The index of the pool. See `poolInfo`. /// @param to Receiver of the LP tokens. function emergencyWithdraw(uint256 pid, address to) public { UserInfo storage user = userInfo[pid][msg.sender]; uint256 amount = user.amount; user.amount = 0; user.rewardDebt = 0; IRewarder _rewarder = rewarder[pid]; if (address(_rewarder) != address(0)) { _rewarder.onTokenReward(pid, msg.sender, to, 0, 0); } // Note: transfer can fail or succeed if `amount` is zero. lpToken[pid].safeTransfer(to, amount); emit EmergencyWithdraw(msg.sender, pid, amount, to); } } // 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 "../IERC20.sol"; import "../../../utils/Address.sol"; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using Address for address; function safeTransfer( IERC20 token, address to, uint256 value ) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom( IERC20 token, address from, address to, uint256 value ) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove( IERC20 token, address spender, uint256 value ) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' require( (value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance( IERC20 token, address spender, uint256 value ) internal { uint256 newAllowance = token.allowance(address(this), spender) + value; _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance( IERC20 token, address spender, uint256 value ) internal { unchecked { uint256 oldAllowance = token.allowance(address(this), spender); require(oldAllowance >= value, "SafeERC20: decreased allowance below zero"); uint256 newAllowance = oldAllowance - value; _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./Address.sol"; /** * @dev Provides a function to batch together multiple calls in a single external call. * * _Available since v4.1._ */ abstract contract Multicall { /** * @dev Receives and executes a batch of function calls on this contract. */ function multicall(bytes[] calldata data) external returns (bytes[] memory results) { results = new bytes[](data.length); for (uint256 i = 0; i < data.length; i++) { results[i] = Address.functionDelegateCall(address(this), data[i]); } return results; } } // SPDX-License-Identifier: MIT pragma solidity >=0.8.4; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; interface IRewarder { function onTokenReward(uint256 pid, address user, address recipient, uint256 tokenAmount, uint256 newLpAmount) external; function pendingTokens(uint256 pid, address user, uint256 tokenAmount) external view returns (IERC20[] memory, uint256[] memory); } // SPDX-License-Identifier: MIT pragma solidity >=0.8.4; /// reference: https://github.com/boringcrypto/BoringSolidity/blob/master/contracts/libraries/BoringMath.sol /// changelog: renamed "BoringMath" => "SafeMath" /// @notice A library for performing overflow-/underflow-safe math, /// updated with awesomeness from of DappHub (https://github.com/dapphub/ds-math). library SafeMath { function add(uint256 a, uint256 b) internal pure returns (uint256 c) { require((c = a + b) >= b, "SafeMath: Add Overflow"); } function sub(uint256 a, uint256 b) internal pure returns (uint256 c) { require((c = a - b) <= a, "SafeMath: Underflow"); } function mul(uint256 a, uint256 b) internal pure returns (uint256 c) { require(b == 0 || (c = a * b) / b == a, "SafeMath: Mul Overflow"); } function to128(uint256 a) internal pure returns (uint128 c) { require(a <= type(uint128).max, "SafeMath: uint128 Overflow"); c = uint128(a); } function to64(uint256 a) internal pure returns (uint64 c) { require(a <= type(uint64).max, "SafeMath: uint64 Overflow"); c = uint64(a); } function to32(uint256 a) internal pure returns (uint32 c) { require(a <= type(uint32).max, "SafeMath: uint32 Overflow"); c = uint32(a); } } /// @notice A library for performing overflow-/underflow-safe addition and subtraction on uint128. library SafeMath128 { function add(uint128 a, uint128 b) internal pure returns (uint128 c) { require((c = a + b) >= b, "SafeMath: Add Overflow"); } function sub(uint128 a, uint128 b) internal pure returns (uint128 c) { require((c = a - b) <= a, "SafeMath: Underflow"); } } /// @notice A library for performing overflow-/underflow-safe addition and subtraction on uint64. library SafeMath64 { function add(uint64 a, uint64 b) internal pure returns (uint64 c) { require((c = a + b) >= b, "SafeMath: Add Overflow"); } function sub(uint64 a, uint64 b) internal pure returns (uint64 c) { require((c = a - b) <= a, "SafeMath: Underflow"); } } /// @notice A library for performing overflow-/underflow-safe addition and subtraction on uint32. library SafeMath32 { function add(uint32 a, uint32 b) internal pure returns (uint32 c) { require((c = a + b) >= b, "SafeMath: Add Overflow"); } function sub(uint32 a, uint32 b) internal pure returns (uint32 c) { require((c = a - b) <= a, "SafeMath: Underflow"); } } // SPDX-License-Identifier: MIT pragma solidity >=0.8.4; library SignedSafeMath { int256 constant private _INT256_MIN = -2**255; /** * @dev Returns the multiplication of two signed integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(int256 a, int256 b) internal pure returns (int256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } require(!(a == -1 && b == _INT256_MIN), "SignedSafeMath: multiplication overflow"); int256 c = a * b; require(c / a == b, "SignedSafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two signed integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(int256 a, int256 b) internal pure returns (int256) { require(b != 0, "SignedSafeMath: division by zero"); require(!(b == -1 && a == _INT256_MIN), "SignedSafeMath: division overflow"); int256 c = a / b; return c; } /** * @dev Returns the subtraction of two signed integers, reverting on * overflow. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(int256 a, int256 b) internal pure returns (int256) { int256 c = a - b; require((b >= 0 && c <= a) || (b < 0 && c > a), "SignedSafeMath: subtraction overflow"); return c; } /** * @dev Returns the addition of two signed integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(int256 a, int256 b) internal pure returns (int256) { int256 c = a + b; require((b >= 0 && c >= a) || (b < 0 && c < a), "SignedSafeMath: addition overflow"); return c; } function toUInt256(int256 a) internal pure returns (uint256) { require(a >= 0, "Integer < 0"); return uint256(a); } } // 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 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; /** * @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); } } } }
Harvest proceeds for transaction sender to `to`. pid The index of the pool. See `poolInfo`. to Receiver of Token rewards. Effects Interactions
function harvest(uint256 pid, address to) public { PoolInfo memory pool = updatePool(pid); UserInfo storage user = userInfo[pid][msg.sender]; int256 accumulatedRewards = int256(user.amount.mul(pool.accRewardPerShare) / ACC_PRECISION); uint256 _pendingRewards = accumulatedRewards.sub(user.rewardDebt).toUInt256(); user.rewardDebt = accumulatedRewards; if (_pendingRewards != 0) { rewardToken.safeTransfer(to, _pendingRewards); } IRewarder _rewarder = rewarder[pid]; if (address(_rewarder) != address(0)) { _rewarder.onTokenReward(pid, msg.sender, to, _pendingRewards, user.amount); } emit Harvest(msg.sender, pid, _pendingRewards); }
12,236,036
./full_match/1/0x3FE29e090394c7EF1E3d2E1637E50d9FAaEB9649/sources/contracts/NonTransferrableNFT.sol
This internal function, called by redeemNFT to physically burn the NFT and redeem their Future position which distributes the locked tokens to its owner this function does five things: 1) Checks to ensure only the owner of the NFT can call this function 2) it checks that the tokens can actually be unlocked based on the time from the expiration 3) it burns the NFT - removing it from storage entirely 4) it also deletes the futures struct from storage so that nothing can be redeemed from that storage index again 5) it withdraws the tokens that have been locked - delivering them to the current owner of the NFT _holder is the owner of the NFT calling the function _id is the unique id of the NFT and unique id of the Future struct/
function _redeemNFT(address _holder, uint256 _id) internal { require(ownerOf(_id) == _holder, 'NFT03'); Future memory future = futures[_id]; require(future.unlockDate < block.timestamp && future.amount > 0, 'NFT04'); emit NFTRedeemed(_id, _holder, future.amount, future.token, future.unlockDate); _burn(_id); delete futures[_id]; TransferHelper.withdrawTokens(future.token, _holder, future.amount);
8,365,350
pragma solidity 0.5.17; contract IFactRegistry { /* Returns true if the given fact was previously registered in the contract. */ function isValid(bytes32 fact) external view returns(bool); } contract IMerkleVerifier { uint256 constant internal MAX_N_MERKLE_VERIFIER_QUERIES = 128; function verify( uint256 channelPtr, uint256 queuePtr, bytes32 root, uint256 n) internal view returns (bytes32 hash); } contract IQueryableFactRegistry is IFactRegistry { /* Returns true if at least one fact has been registered. */ function hasRegisteredFact() external view returns(bool); } contract IStarkVerifier { function verifyProof( uint256[] memory proofParams, uint256[] memory proof, uint256[] memory publicInput ) internal; } contract MemoryMap { /* We store the state of the verifer in a contiguous chunk of memory. The offsets of the different fields are listed below. E.g. The offset of the i'th hash is [mm_hashes + i]. */ uint256 constant internal CHANNEL_STATE_SIZE = 3; uint256 constant internal MAX_N_QUERIES = 48; uint256 constant internal FRI_QUEUE_SIZE = MAX_N_QUERIES; uint256 constant internal MAX_SUPPORTED_MAX_FRI_STEP = 4; uint256 constant internal MM_EVAL_DOMAIN_SIZE = 0x0; uint256 constant internal MM_BLOW_UP_FACTOR = 0x1; uint256 constant internal MM_LOG_EVAL_DOMAIN_SIZE = 0x2; uint256 constant internal MM_PROOF_OF_WORK_BITS = 0x3; uint256 constant internal MM_EVAL_DOMAIN_GENERATOR = 0x4; uint256 constant internal MM_PUBLIC_INPUT_PTR = 0x5; uint256 constant internal MM_TRACE_COMMITMENT = 0x6; uint256 constant internal MM_OODS_COMMITMENT = 0x7; uint256 constant internal MM_N_UNIQUE_QUERIES = 0x8; uint256 constant internal MM_CHANNEL = 0x9; // uint256[3] uint256 constant internal MM_MERKLE_QUEUE = 0xc; // uint256[96] uint256 constant internal MM_FRI_QUEUE = 0x6c; // uint256[144] uint256 constant internal MM_FRI_QUERIES_DELIMITER = 0xfc; uint256 constant internal MM_FRI_CTX = 0xfd; // uint256[40] uint256 constant internal MM_FRI_STEPS_PTR = 0x125; uint256 constant internal MM_FRI_EVAL_POINTS = 0x126; // uint256[10] uint256 constant internal MM_FRI_COMMITMENTS = 0x130; // uint256[10] uint256 constant internal MM_FRI_LAST_LAYER_DEG_BOUND = 0x13a; uint256 constant internal MM_FRI_LAST_LAYER_PTR = 0x13b; uint256 constant internal MM_CONSTRAINT_POLY_ARGS_START = 0x13c; uint256 constant internal MM_PERIODIC_COLUMN__CONSTS0_A = 0x13c; uint256 constant internal MM_PERIODIC_COLUMN__CONSTS1_A = 0x13d; uint256 constant internal MM_PERIODIC_COLUMN__CONSTS2_A = 0x13e; uint256 constant internal MM_PERIODIC_COLUMN__CONSTS3_A = 0x13f; uint256 constant internal MM_PERIODIC_COLUMN__CONSTS4_A = 0x140; uint256 constant internal MM_PERIODIC_COLUMN__CONSTS5_A = 0x141; uint256 constant internal MM_PERIODIC_COLUMN__CONSTS6_A = 0x142; uint256 constant internal MM_PERIODIC_COLUMN__CONSTS7_A = 0x143; uint256 constant internal MM_PERIODIC_COLUMN__CONSTS8_A = 0x144; uint256 constant internal MM_PERIODIC_COLUMN__CONSTS9_A = 0x145; uint256 constant internal MM_PERIODIC_COLUMN__CONSTS0_B = 0x146; uint256 constant internal MM_PERIODIC_COLUMN__CONSTS1_B = 0x147; uint256 constant internal MM_PERIODIC_COLUMN__CONSTS2_B = 0x148; uint256 constant internal MM_PERIODIC_COLUMN__CONSTS3_B = 0x149; uint256 constant internal MM_PERIODIC_COLUMN__CONSTS4_B = 0x14a; uint256 constant internal MM_PERIODIC_COLUMN__CONSTS5_B = 0x14b; uint256 constant internal MM_PERIODIC_COLUMN__CONSTS6_B = 0x14c; uint256 constant internal MM_PERIODIC_COLUMN__CONSTS7_B = 0x14d; uint256 constant internal MM_PERIODIC_COLUMN__CONSTS8_B = 0x14e; uint256 constant internal MM_PERIODIC_COLUMN__CONSTS9_B = 0x14f; uint256 constant internal MM_MAT00 = 0x150; uint256 constant internal MM_MAT01 = 0x151; uint256 constant internal MM_TRACE_LENGTH = 0x152; uint256 constant internal MM_MAT10 = 0x153; uint256 constant internal MM_MAT11 = 0x154; uint256 constant internal MM_INPUT_VALUE_A = 0x155; uint256 constant internal MM_OUTPUT_VALUE_A = 0x156; uint256 constant internal MM_INPUT_VALUE_B = 0x157; uint256 constant internal MM_OUTPUT_VALUE_B = 0x158; uint256 constant internal MM_TRACE_GENERATOR = 0x159; uint256 constant internal MM_OODS_POINT = 0x15a; uint256 constant internal MM_COEFFICIENTS = 0x15b; // uint256[48] uint256 constant internal MM_OODS_VALUES = 0x18b; // uint256[22] uint256 constant internal MM_CONSTRAINT_POLY_ARGS_END = 0x1a1; uint256 constant internal MM_COMPOSITION_OODS_VALUES = 0x1a1; // uint256[2] uint256 constant internal MM_OODS_EVAL_POINTS = 0x1a3; // uint256[48] uint256 constant internal MM_OODS_COEFFICIENTS = 0x1d3; // uint256[24] uint256 constant internal MM_TRACE_QUERY_RESPONSES = 0x1eb; // uint256[960] uint256 constant internal MM_COMPOSITION_QUERY_RESPONSES = 0x5ab; // uint256[96] uint256 constant internal MM_CONTEXT_SIZE = 0x60b; } contract MerkleVerifier is IMerkleVerifier { function getHashMask() internal pure returns(uint256) { // Default implementation. return 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF000000000000000000000000; } /* Verifies a Merkle tree decommitment for n leaves in a Merkle tree with N leaves. The inputs data sits in the queue at queuePtr. Each slot in the queue contains a 32 bytes leaf index and a 32 byte leaf value. The indices need to be in the range [N..2*N-1] and strictly incrementing. Decommitments are read from the channel in the ctx. The input data is destroyed during verification. */ function verify( uint256 channelPtr, uint256 queuePtr, bytes32 root, uint256 n) internal view returns (bytes32 hash) { uint256 lhashMask = getHashMask(); require(n <= MAX_N_MERKLE_VERIFIER_QUERIES, "TOO_MANY_MERKLE_QUERIES"); assembly { // queuePtr + i * 0x40 gives the i'th index in the queue. // hashesPtr + i * 0x40 gives the i'th hash in the queue. let hashesPtr := add(queuePtr, 0x20) let queueSize := mul(n, 0x40) let slotSize := 0x40 // The items are in slots [0, n-1]. let rdIdx := 0 let wrIdx := 0 // = n % n. // Iterate the queue until we hit the root. let index := mload(add(rdIdx, queuePtr)) let proofPtr := mload(channelPtr) // while(index > 1). for { } gt(index, 1) { } { let siblingIndex := xor(index, 1) // sibblingOffset := 0x20 * lsb(siblingIndex). let sibblingOffset := mulmod(siblingIndex, 0x20, 0x40) // Store the hash corresponding to index in the correct slot. // 0 if index is even and 0x20 if index is odd. // The hash of the sibling will be written to the other slot. mstore(xor(0x20, sibblingOffset), mload(add(rdIdx, hashesPtr))) rdIdx := addmod(rdIdx, slotSize, queueSize) // Inline channel operation: // Assume we are going to read a new hash from the proof. // If this is not the case add(proofPtr, 0x20) will be reverted. let newHashPtr := proofPtr proofPtr := add(proofPtr, 0x20) // Push index/2 into the queue, before reading the next index. // The order is important, as otherwise we may try to read from an empty queue (in // the case where we are working on one item). // wrIdx will be updated after writing the relevant hash to the queue. mstore(add(wrIdx, queuePtr), div(index, 2)) // Load the next index from the queue and check if it is our sibling. index := mload(add(rdIdx, queuePtr)) if eq(index, siblingIndex) { // Take sibling from queue rather than from proof. newHashPtr := add(rdIdx, hashesPtr) // Revert reading from proof. proofPtr := sub(proofPtr, 0x20) rdIdx := addmod(rdIdx, slotSize, queueSize) // Index was consumed, read the next one. // Note that the queue can't be empty at this point. // The index of the parent of the current node was already pushed into the // queue, and the parent is never the sibling. index := mload(add(rdIdx, queuePtr)) } mstore(sibblingOffset, mload(newHashPtr)) // Push the new hash to the end of the queue. mstore(add(wrIdx, hashesPtr), and(lhashMask, keccak256(0x00, 0x40))) wrIdx := addmod(wrIdx, slotSize, queueSize) } hash := mload(add(rdIdx, hashesPtr)) // Update the proof pointer in the context. mstore(channelPtr, proofPtr) } // emit LogBool(hash == root); require(hash == root, "INVALID_MERKLE_PROOF"); } } contract MimcConstraintPoly { // The Memory map during the execution of this contract is as follows: // [0x0, 0x20) - periodic_column/consts0_a. // [0x20, 0x40) - periodic_column/consts1_a. // [0x40, 0x60) - periodic_column/consts2_a. // [0x60, 0x80) - periodic_column/consts3_a. // [0x80, 0xa0) - periodic_column/consts4_a. // [0xa0, 0xc0) - periodic_column/consts5_a. // [0xc0, 0xe0) - periodic_column/consts6_a. // [0xe0, 0x100) - periodic_column/consts7_a. // [0x100, 0x120) - periodic_column/consts8_a. // [0x120, 0x140) - periodic_column/consts9_a. // [0x140, 0x160) - periodic_column/consts0_b. // [0x160, 0x180) - periodic_column/consts1_b. // [0x180, 0x1a0) - periodic_column/consts2_b. // [0x1a0, 0x1c0) - periodic_column/consts3_b. // [0x1c0, 0x1e0) - periodic_column/consts4_b. // [0x1e0, 0x200) - periodic_column/consts5_b. // [0x200, 0x220) - periodic_column/consts6_b. // [0x220, 0x240) - periodic_column/consts7_b. // [0x240, 0x260) - periodic_column/consts8_b. // [0x260, 0x280) - periodic_column/consts9_b. // [0x280, 0x2a0) - mat00. // [0x2a0, 0x2c0) - mat01. // [0x2c0, 0x2e0) - trace_length. // [0x2e0, 0x300) - mat10. // [0x300, 0x320) - mat11. // [0x320, 0x340) - input_value_a. // [0x340, 0x360) - output_value_a. // [0x360, 0x380) - input_value_b. // [0x380, 0x3a0) - output_value_b. // [0x3a0, 0x3c0) - trace_generator. // [0x3c0, 0x3e0) - oods_point. // [0x3e0, 0x9e0) - coefficients. // [0x9e0, 0xca0) - oods_values. // ----------------------- end of input data - ------------------------- // [0xca0, 0xcc0) - composition_degree_bound. // [0xcc0, 0xce0) - intermediate_value/after_lin_transform0_a_0. // [0xce0, 0xd00) - intermediate_value/after_lin_transform0_b_0. // [0xd00, 0xd20) - intermediate_value/after_lin_transform1_a_0. // [0xd20, 0xd40) - intermediate_value/after_lin_transform1_b_0. // [0xd40, 0xd60) - intermediate_value/after_lin_transform2_a_0. // [0xd60, 0xd80) - intermediate_value/after_lin_transform2_b_0. // [0xd80, 0xda0) - intermediate_value/after_lin_transform3_a_0. // [0xda0, 0xdc0) - intermediate_value/after_lin_transform3_b_0. // [0xdc0, 0xde0) - intermediate_value/after_lin_transform4_a_0. // [0xde0, 0xe00) - intermediate_value/after_lin_transform4_b_0. // [0xe00, 0xe20) - intermediate_value/after_lin_transform5_a_0. // [0xe20, 0xe40) - intermediate_value/after_lin_transform5_b_0. // [0xe40, 0xe60) - intermediate_value/after_lin_transform6_a_0. // [0xe60, 0xe80) - intermediate_value/after_lin_transform6_b_0. // [0xe80, 0xea0) - intermediate_value/after_lin_transform7_a_0. // [0xea0, 0xec0) - intermediate_value/after_lin_transform7_b_0. // [0xec0, 0xee0) - intermediate_value/after_lin_transform8_a_0. // [0xee0, 0xf00) - intermediate_value/after_lin_transform8_b_0. // [0xf00, 0xf20) - intermediate_value/after_lin_transform9_a_0. // [0xf20, 0xf40) - intermediate_value/after_lin_transform9_b_0. // [0xf40, 0xf80) - expmods. // [0xf80, 0xfe0) - denominator_invs. // [0xfe0, 0x1040) - denominators. // [0x1040, 0x1060) - numerators. // [0x1060, 0x10c0) - adjustments. // [0x10c0, 0x1180) - expmod_context. function() external { uint256 res; assembly { let PRIME := 0x30000003000000010000000000000001 // Copy input from calldata to memory. calldatacopy(0x0, 0x0, /*Input data size*/ 0xca0) let point := /*oods_point*/ mload(0x3c0) // Initialize composition_degree_bound to 2 * trace_length. mstore(0xca0, mul(2, /*trace_length*/ mload(0x2c0))) function expmod(base, exponent, modulus) -> res { let p := /*expmod_context*/ 0x10c0 mstore(p, 0x20) // Length of Base. mstore(add(p, 0x20), 0x20) // Length of Exponent. mstore(add(p, 0x40), 0x20) // Length of Modulus. mstore(add(p, 0x60), base) // Base. mstore(add(p, 0x80), exponent) // Exponent. mstore(add(p, 0xa0), modulus) // Modulus. // Call modexp precompile. if iszero(staticcall(not(0), 0x05, p, 0xc0, p, 0x20)) { revert(0, 0) } res := mload(p) } function degreeAdjustment(compositionPolynomialDegreeBound, constraintDegree, numeratorDegree, denominatorDegree) -> res { res := sub(sub(compositionPolynomialDegreeBound, 1), sub(add(constraintDegree, numeratorDegree), denominatorDegree)) } { // Prepare expmods for denominators and numerators. // expmods[0] = point^trace_length. mstore(0xf40, expmod(point, /*trace_length*/ mload(0x2c0), PRIME)) // expmods[1] = trace_generator^(trace_length - 1). mstore(0xf60, expmod(/*trace_generator*/ mload(0x3a0), sub(/*trace_length*/ mload(0x2c0), 1), PRIME)) } { // Prepare denominators for batch inverse. // Denominator for constraints: 'step0_a', 'step0_b', 'step1_a', 'step1_b', 'step2_a', 'step2_b', 'step3_a', 'step3_b', 'step4_a', 'step4_b', 'step5_a', 'step5_b', 'step6_a', 'step6_b', 'step7_a', 'step7_b', 'step8_a', 'step8_b', 'step9_a', 'step9_b'. // denominators[0] = point^trace_length - 1. mstore(0xfe0, addmod(/*point^trace_length*/ mload(0xf40), sub(PRIME, 1), PRIME)) // Denominator for constraints: 'input_a', 'input_b'. // denominators[1] = point - 1. mstore(0x1000, addmod(point, sub(PRIME, 1), PRIME)) // Denominator for constraints: 'output_a', 'output_b'. // denominators[2] = point - trace_generator^(trace_length - 1). mstore(0x1020, addmod(point, sub(PRIME, /*trace_generator^(trace_length - 1)*/ mload(0xf60)), PRIME)) } { // Compute the inverses of the denominators into denominatorInvs using batch inverse. // Start by computing the cumulative product. // Let (d_0, d_1, d_2, ..., d_{n-1}) be the values in denominators. After this loop // denominatorInvs will be (1, d_0, d_0 * d_1, ...) and prod will contain the value of // d_0 * ... * d_{n-1}. // Compute the offset between the partialProducts array and the input values array. let productsToValuesOffset := 0x60 let prod := 1 let partialProductEndPtr := 0xfe0 for { let partialProductPtr := 0xf80 } lt(partialProductPtr, partialProductEndPtr) { partialProductPtr := add(partialProductPtr, 0x20) } { mstore(partialProductPtr, prod) // prod *= d_{i}. prod := mulmod(prod, mload(add(partialProductPtr, productsToValuesOffset)), PRIME) } let firstPartialProductPtr := 0xf80 // Compute the inverse of the product. let prodInv := expmod(prod, sub(PRIME, 2), PRIME) if eq(prodInv, 0) { // Solidity generates reverts with reason that look as follows: // 1. 4 bytes with the constant 0x08c379a0 (== Keccak256(b'Error(string)')[:4]). // 2. 32 bytes offset bytes (always 0x20 as far as i can tell). // 3. 32 bytes with the length of the revert reason. // 4. Revert reason string. mstore(0, 0x08c379a000000000000000000000000000000000000000000000000000000000) mstore(0x4, 0x20) mstore(0x24, 0x1e) mstore(0x44, "Batch inverse product is zero.") revert(0, 0x62) } // Compute the inverses. // Loop over denominator_invs in reverse order. // currentPartialProductPtr is initialized to one past the end. let currentPartialProductPtr := 0xfe0 for { } gt(currentPartialProductPtr, firstPartialProductPtr) { } { currentPartialProductPtr := sub(currentPartialProductPtr, 0x20) // Store 1/d_{i} = (d_0 * ... * d_{i-1}) * 1/(d_0 * ... * d_{i}). mstore(currentPartialProductPtr, mulmod(mload(currentPartialProductPtr), prodInv, PRIME)) // Update prodInv to be 1/(d_0 * ... * d_{i-1}) by multiplying by d_i. prodInv := mulmod(prodInv, mload(add(currentPartialProductPtr, productsToValuesOffset)), PRIME) } } { // Compute numerators and adjustment polynomials. // Numerator for constraints 'step9_a', 'step9_b'. // numerators[0] = point - trace_generator^(trace_length - 1). mstore(0x1040, addmod(point, sub(PRIME, /*trace_generator^(trace_length - 1)*/ mload(0xf60)), PRIME)) // Adjustment polynomial for constraints 'step0_a', 'step0_b', 'step1_a', 'step1_b', 'step2_a', 'step2_b', 'step3_a', 'step3_b', 'step4_a', 'step4_b', 'step5_a', 'step5_b', 'step6_a', 'step6_b', 'step7_a', 'step7_b', 'step8_a', 'step8_b'. // adjustments[0] = point^degreeAdjustment(composition_degree_bound, 3 * (trace_length - 1), 0, trace_length). mstore(0x1060, expmod(point, degreeAdjustment(/*composition_degree_bound*/ mload(0xca0), mul(3, sub(/*trace_length*/ mload(0x2c0), 1)), 0, /*trace_length*/ mload(0x2c0)), PRIME)) // Adjustment polynomial for constraints 'step9_a', 'step9_b'. // adjustments[1] = point^degreeAdjustment(composition_degree_bound, 3 * (trace_length - 1), 1, trace_length). mstore(0x1080, expmod(point, degreeAdjustment(/*composition_degree_bound*/ mload(0xca0), mul(3, sub(/*trace_length*/ mload(0x2c0), 1)), 1, /*trace_length*/ mload(0x2c0)), PRIME)) // Adjustment polynomial for constraints 'input_a', 'output_a', 'input_b', 'output_b'. // adjustments[2] = point^degreeAdjustment(composition_degree_bound, trace_length - 1, 0, 1). mstore(0x10a0, expmod(point, degreeAdjustment(/*composition_degree_bound*/ mload(0xca0), sub(/*trace_length*/ mload(0x2c0), 1), 0, 1), PRIME)) } { // Compute the result of the composition polynomial. { // after_lin_transform0_a_0 = mat00 * (column0_row0 - consts0_a) + mat01 * (column10_row0 - consts0_b). let val := addmod( mulmod( /*mat00*/ mload(0x280), addmod( /*column0_row0*/ mload(0x9e0), sub(PRIME, /*periodic_column/consts0_a*/ mload(0x0)), PRIME), PRIME), mulmod( /*mat01*/ mload(0x2a0), addmod( /*column10_row0*/ mload(0xb40), sub(PRIME, /*periodic_column/consts0_b*/ mload(0x140)), PRIME), PRIME), PRIME) mstore(0xcc0, val) } { // after_lin_transform0_b_0 = mat10 * (column0_row0 - consts0_a) + mat11 * (column10_row0 - consts0_b). let val := addmod( mulmod( /*mat10*/ mload(0x2e0), addmod( /*column0_row0*/ mload(0x9e0), sub(PRIME, /*periodic_column/consts0_a*/ mload(0x0)), PRIME), PRIME), mulmod( /*mat11*/ mload(0x300), addmod( /*column10_row0*/ mload(0xb40), sub(PRIME, /*periodic_column/consts0_b*/ mload(0x140)), PRIME), PRIME), PRIME) mstore(0xce0, val) } { // after_lin_transform1_a_0 = mat00 * (column1_row0 - consts1_a) + mat01 * (column11_row0 - consts1_b). let val := addmod( mulmod( /*mat00*/ mload(0x280), addmod( /*column1_row0*/ mload(0xa20), sub(PRIME, /*periodic_column/consts1_a*/ mload(0x20)), PRIME), PRIME), mulmod( /*mat01*/ mload(0x2a0), addmod( /*column11_row0*/ mload(0xb80), sub(PRIME, /*periodic_column/consts1_b*/ mload(0x160)), PRIME), PRIME), PRIME) mstore(0xd00, val) } { // after_lin_transform1_b_0 = mat10 * (column1_row0 - consts1_a) + mat11 * (column11_row0 - consts1_b). let val := addmod( mulmod( /*mat10*/ mload(0x2e0), addmod( /*column1_row0*/ mload(0xa20), sub(PRIME, /*periodic_column/consts1_a*/ mload(0x20)), PRIME), PRIME), mulmod( /*mat11*/ mload(0x300), addmod( /*column11_row0*/ mload(0xb80), sub(PRIME, /*periodic_column/consts1_b*/ mload(0x160)), PRIME), PRIME), PRIME) mstore(0xd20, val) } { // after_lin_transform2_a_0 = mat00 * (column2_row0 - consts2_a) + mat01 * (column12_row0 - consts2_b). let val := addmod( mulmod( /*mat00*/ mload(0x280), addmod( /*column2_row0*/ mload(0xa40), sub(PRIME, /*periodic_column/consts2_a*/ mload(0x40)), PRIME), PRIME), mulmod( /*mat01*/ mload(0x2a0), addmod( /*column12_row0*/ mload(0xba0), sub(PRIME, /*periodic_column/consts2_b*/ mload(0x180)), PRIME), PRIME), PRIME) mstore(0xd40, val) } { // after_lin_transform2_b_0 = mat10 * (column2_row0 - consts2_a) + mat11 * (column12_row0 - consts2_b). let val := addmod( mulmod( /*mat10*/ mload(0x2e0), addmod( /*column2_row0*/ mload(0xa40), sub(PRIME, /*periodic_column/consts2_a*/ mload(0x40)), PRIME), PRIME), mulmod( /*mat11*/ mload(0x300), addmod( /*column12_row0*/ mload(0xba0), sub(PRIME, /*periodic_column/consts2_b*/ mload(0x180)), PRIME), PRIME), PRIME) mstore(0xd60, val) } { // after_lin_transform3_a_0 = mat00 * (column3_row0 - consts3_a) + mat01 * (column13_row0 - consts3_b). let val := addmod( mulmod( /*mat00*/ mload(0x280), addmod( /*column3_row0*/ mload(0xa60), sub(PRIME, /*periodic_column/consts3_a*/ mload(0x60)), PRIME), PRIME), mulmod( /*mat01*/ mload(0x2a0), addmod( /*column13_row0*/ mload(0xbc0), sub(PRIME, /*periodic_column/consts3_b*/ mload(0x1a0)), PRIME), PRIME), PRIME) mstore(0xd80, val) } { // after_lin_transform3_b_0 = mat10 * (column3_row0 - consts3_a) + mat11 * (column13_row0 - consts3_b). let val := addmod( mulmod( /*mat10*/ mload(0x2e0), addmod( /*column3_row0*/ mload(0xa60), sub(PRIME, /*periodic_column/consts3_a*/ mload(0x60)), PRIME), PRIME), mulmod( /*mat11*/ mload(0x300), addmod( /*column13_row0*/ mload(0xbc0), sub(PRIME, /*periodic_column/consts3_b*/ mload(0x1a0)), PRIME), PRIME), PRIME) mstore(0xda0, val) } { // after_lin_transform4_a_0 = mat00 * (column4_row0 - consts4_a) + mat01 * (column14_row0 - consts4_b). let val := addmod( mulmod( /*mat00*/ mload(0x280), addmod( /*column4_row0*/ mload(0xa80), sub(PRIME, /*periodic_column/consts4_a*/ mload(0x80)), PRIME), PRIME), mulmod( /*mat01*/ mload(0x2a0), addmod( /*column14_row0*/ mload(0xbe0), sub(PRIME, /*periodic_column/consts4_b*/ mload(0x1c0)), PRIME), PRIME), PRIME) mstore(0xdc0, val) } { // after_lin_transform4_b_0 = mat10 * (column4_row0 - consts4_a) + mat11 * (column14_row0 - consts4_b). let val := addmod( mulmod( /*mat10*/ mload(0x2e0), addmod( /*column4_row0*/ mload(0xa80), sub(PRIME, /*periodic_column/consts4_a*/ mload(0x80)), PRIME), PRIME), mulmod( /*mat11*/ mload(0x300), addmod( /*column14_row0*/ mload(0xbe0), sub(PRIME, /*periodic_column/consts4_b*/ mload(0x1c0)), PRIME), PRIME), PRIME) mstore(0xde0, val) } { // after_lin_transform5_a_0 = mat00 * (column5_row0 - consts5_a) + mat01 * (column15_row0 - consts5_b). let val := addmod( mulmod( /*mat00*/ mload(0x280), addmod( /*column5_row0*/ mload(0xaa0), sub(PRIME, /*periodic_column/consts5_a*/ mload(0xa0)), PRIME), PRIME), mulmod( /*mat01*/ mload(0x2a0), addmod( /*column15_row0*/ mload(0xc00), sub(PRIME, /*periodic_column/consts5_b*/ mload(0x1e0)), PRIME), PRIME), PRIME) mstore(0xe00, val) } { // after_lin_transform5_b_0 = mat10 * (column5_row0 - consts5_a) + mat11 * (column15_row0 - consts5_b). let val := addmod( mulmod( /*mat10*/ mload(0x2e0), addmod( /*column5_row0*/ mload(0xaa0), sub(PRIME, /*periodic_column/consts5_a*/ mload(0xa0)), PRIME), PRIME), mulmod( /*mat11*/ mload(0x300), addmod( /*column15_row0*/ mload(0xc00), sub(PRIME, /*periodic_column/consts5_b*/ mload(0x1e0)), PRIME), PRIME), PRIME) mstore(0xe20, val) } { // after_lin_transform6_a_0 = mat00 * (column6_row0 - consts6_a) + mat01 * (column16_row0 - consts6_b). let val := addmod( mulmod( /*mat00*/ mload(0x280), addmod( /*column6_row0*/ mload(0xac0), sub(PRIME, /*periodic_column/consts6_a*/ mload(0xc0)), PRIME), PRIME), mulmod( /*mat01*/ mload(0x2a0), addmod( /*column16_row0*/ mload(0xc20), sub(PRIME, /*periodic_column/consts6_b*/ mload(0x200)), PRIME), PRIME), PRIME) mstore(0xe40, val) } { // after_lin_transform6_b_0 = mat10 * (column6_row0 - consts6_a) + mat11 * (column16_row0 - consts6_b). let val := addmod( mulmod( /*mat10*/ mload(0x2e0), addmod( /*column6_row0*/ mload(0xac0), sub(PRIME, /*periodic_column/consts6_a*/ mload(0xc0)), PRIME), PRIME), mulmod( /*mat11*/ mload(0x300), addmod( /*column16_row0*/ mload(0xc20), sub(PRIME, /*periodic_column/consts6_b*/ mload(0x200)), PRIME), PRIME), PRIME) mstore(0xe60, val) } { // after_lin_transform7_a_0 = mat00 * (column7_row0 - consts7_a) + mat01 * (column17_row0 - consts7_b). let val := addmod( mulmod( /*mat00*/ mload(0x280), addmod( /*column7_row0*/ mload(0xae0), sub(PRIME, /*periodic_column/consts7_a*/ mload(0xe0)), PRIME), PRIME), mulmod( /*mat01*/ mload(0x2a0), addmod( /*column17_row0*/ mload(0xc40), sub(PRIME, /*periodic_column/consts7_b*/ mload(0x220)), PRIME), PRIME), PRIME) mstore(0xe80, val) } { // after_lin_transform7_b_0 = mat10 * (column7_row0 - consts7_a) + mat11 * (column17_row0 - consts7_b). let val := addmod( mulmod( /*mat10*/ mload(0x2e0), addmod( /*column7_row0*/ mload(0xae0), sub(PRIME, /*periodic_column/consts7_a*/ mload(0xe0)), PRIME), PRIME), mulmod( /*mat11*/ mload(0x300), addmod( /*column17_row0*/ mload(0xc40), sub(PRIME, /*periodic_column/consts7_b*/ mload(0x220)), PRIME), PRIME), PRIME) mstore(0xea0, val) } { // after_lin_transform8_a_0 = mat00 * (column8_row0 - consts8_a) + mat01 * (column18_row0 - consts8_b). let val := addmod( mulmod( /*mat00*/ mload(0x280), addmod( /*column8_row0*/ mload(0xb00), sub(PRIME, /*periodic_column/consts8_a*/ mload(0x100)), PRIME), PRIME), mulmod( /*mat01*/ mload(0x2a0), addmod( /*column18_row0*/ mload(0xc60), sub(PRIME, /*periodic_column/consts8_b*/ mload(0x240)), PRIME), PRIME), PRIME) mstore(0xec0, val) } { // after_lin_transform8_b_0 = mat10 * (column8_row0 - consts8_a) + mat11 * (column18_row0 - consts8_b). let val := addmod( mulmod( /*mat10*/ mload(0x2e0), addmod( /*column8_row0*/ mload(0xb00), sub(PRIME, /*periodic_column/consts8_a*/ mload(0x100)), PRIME), PRIME), mulmod( /*mat11*/ mload(0x300), addmod( /*column18_row0*/ mload(0xc60), sub(PRIME, /*periodic_column/consts8_b*/ mload(0x240)), PRIME), PRIME), PRIME) mstore(0xee0, val) } { // after_lin_transform9_a_0 = mat00 * (column9_row0 - consts9_a) + mat01 * (column19_row0 - consts9_b). let val := addmod( mulmod( /*mat00*/ mload(0x280), addmod( /*column9_row0*/ mload(0xb20), sub(PRIME, /*periodic_column/consts9_a*/ mload(0x120)), PRIME), PRIME), mulmod( /*mat01*/ mload(0x2a0), addmod( /*column19_row0*/ mload(0xc80), sub(PRIME, /*periodic_column/consts9_b*/ mload(0x260)), PRIME), PRIME), PRIME) mstore(0xf00, val) } { // after_lin_transform9_b_0 = mat10 * (column9_row0 - consts9_a) + mat11 * (column19_row0 - consts9_b). let val := addmod( mulmod( /*mat10*/ mload(0x2e0), addmod( /*column9_row0*/ mload(0xb20), sub(PRIME, /*periodic_column/consts9_a*/ mload(0x120)), PRIME), PRIME), mulmod( /*mat11*/ mload(0x300), addmod( /*column19_row0*/ mload(0xc80), sub(PRIME, /*periodic_column/consts9_b*/ mload(0x260)), PRIME), PRIME), PRIME) mstore(0xf20, val) } { // Constraint expression for step0_a: column1_row0 - after_lin_transform0_a_0 * after_lin_transform0_a_0 * after_lin_transform0_a_0. let val := addmod( /*column1_row0*/ mload(0xa20), sub( PRIME, mulmod( mulmod( /*intermediate_value/after_lin_transform0_a_0*/ mload(0xcc0), /*intermediate_value/after_lin_transform0_a_0*/ mload(0xcc0), PRIME), /*intermediate_value/after_lin_transform0_a_0*/ mload(0xcc0), PRIME)), PRIME) // Numerator: 1. // val *= 1. // val := mulmod(val, 1, PRIME). // Denominator: point^trace_length - 1. // val *= denominator_invs[0]. val := mulmod(val, mload(0xf80), PRIME) // res += val * (coefficients[0] + coefficients[1] * adjustments[0]). res := addmod(res, mulmod(val, add(/*coefficients[0]*/ mload(0x3e0), mulmod(/*coefficients[1]*/ mload(0x400), /*adjustments[0]*/mload(0x1060), PRIME)), PRIME), PRIME) } { // Constraint expression for step0_b: column11_row0 - after_lin_transform0_b_0 * after_lin_transform0_b_0 * after_lin_transform0_b_0. let val := addmod( /*column11_row0*/ mload(0xb80), sub( PRIME, mulmod( mulmod( /*intermediate_value/after_lin_transform0_b_0*/ mload(0xce0), /*intermediate_value/after_lin_transform0_b_0*/ mload(0xce0), PRIME), /*intermediate_value/after_lin_transform0_b_0*/ mload(0xce0), PRIME)), PRIME) // Numerator: 1. // val *= 1. // val := mulmod(val, 1, PRIME). // Denominator: point^trace_length - 1. // val *= denominator_invs[0]. val := mulmod(val, mload(0xf80), PRIME) // res += val * (coefficients[2] + coefficients[3] * adjustments[0]). res := addmod(res, mulmod(val, add(/*coefficients[2]*/ mload(0x420), mulmod(/*coefficients[3]*/ mload(0x440), /*adjustments[0]*/mload(0x1060), PRIME)), PRIME), PRIME) } { // Constraint expression for step1_a: column2_row0 - after_lin_transform1_a_0 * after_lin_transform1_a_0 * after_lin_transform1_a_0. let val := addmod( /*column2_row0*/ mload(0xa40), sub( PRIME, mulmod( mulmod( /*intermediate_value/after_lin_transform1_a_0*/ mload(0xd00), /*intermediate_value/after_lin_transform1_a_0*/ mload(0xd00), PRIME), /*intermediate_value/after_lin_transform1_a_0*/ mload(0xd00), PRIME)), PRIME) // Numerator: 1. // val *= 1. // val := mulmod(val, 1, PRIME). // Denominator: point^trace_length - 1. // val *= denominator_invs[0]. val := mulmod(val, mload(0xf80), PRIME) // res += val * (coefficients[4] + coefficients[5] * adjustments[0]). res := addmod(res, mulmod(val, add(/*coefficients[4]*/ mload(0x460), mulmod(/*coefficients[5]*/ mload(0x480), /*adjustments[0]*/mload(0x1060), PRIME)), PRIME), PRIME) } { // Constraint expression for step1_b: column12_row0 - after_lin_transform1_b_0 * after_lin_transform1_b_0 * after_lin_transform1_b_0. let val := addmod( /*column12_row0*/ mload(0xba0), sub( PRIME, mulmod( mulmod( /*intermediate_value/after_lin_transform1_b_0*/ mload(0xd20), /*intermediate_value/after_lin_transform1_b_0*/ mload(0xd20), PRIME), /*intermediate_value/after_lin_transform1_b_0*/ mload(0xd20), PRIME)), PRIME) // Numerator: 1. // val *= 1. // val := mulmod(val, 1, PRIME). // Denominator: point^trace_length - 1. // val *= denominator_invs[0]. val := mulmod(val, mload(0xf80), PRIME) // res += val * (coefficients[6] + coefficients[7] * adjustments[0]). res := addmod(res, mulmod(val, add(/*coefficients[6]*/ mload(0x4a0), mulmod(/*coefficients[7]*/ mload(0x4c0), /*adjustments[0]*/mload(0x1060), PRIME)), PRIME), PRIME) } { // Constraint expression for step2_a: column3_row0 - after_lin_transform2_a_0 * after_lin_transform2_a_0 * after_lin_transform2_a_0. let val := addmod( /*column3_row0*/ mload(0xa60), sub( PRIME, mulmod( mulmod( /*intermediate_value/after_lin_transform2_a_0*/ mload(0xd40), /*intermediate_value/after_lin_transform2_a_0*/ mload(0xd40), PRIME), /*intermediate_value/after_lin_transform2_a_0*/ mload(0xd40), PRIME)), PRIME) // Numerator: 1. // val *= 1. // val := mulmod(val, 1, PRIME). // Denominator: point^trace_length - 1. // val *= denominator_invs[0]. val := mulmod(val, mload(0xf80), PRIME) // res += val * (coefficients[8] + coefficients[9] * adjustments[0]). res := addmod(res, mulmod(val, add(/*coefficients[8]*/ mload(0x4e0), mulmod(/*coefficients[9]*/ mload(0x500), /*adjustments[0]*/mload(0x1060), PRIME)), PRIME), PRIME) } { // Constraint expression for step2_b: column13_row0 - after_lin_transform2_b_0 * after_lin_transform2_b_0 * after_lin_transform2_b_0. let val := addmod( /*column13_row0*/ mload(0xbc0), sub( PRIME, mulmod( mulmod( /*intermediate_value/after_lin_transform2_b_0*/ mload(0xd60), /*intermediate_value/after_lin_transform2_b_0*/ mload(0xd60), PRIME), /*intermediate_value/after_lin_transform2_b_0*/ mload(0xd60), PRIME)), PRIME) // Numerator: 1. // val *= 1. // val := mulmod(val, 1, PRIME). // Denominator: point^trace_length - 1. // val *= denominator_invs[0]. val := mulmod(val, mload(0xf80), PRIME) // res += val * (coefficients[10] + coefficients[11] * adjustments[0]). res := addmod(res, mulmod(val, add(/*coefficients[10]*/ mload(0x520), mulmod(/*coefficients[11]*/ mload(0x540), /*adjustments[0]*/mload(0x1060), PRIME)), PRIME), PRIME) } { // Constraint expression for step3_a: column4_row0 - after_lin_transform3_a_0 * after_lin_transform3_a_0 * after_lin_transform3_a_0. let val := addmod( /*column4_row0*/ mload(0xa80), sub( PRIME, mulmod( mulmod( /*intermediate_value/after_lin_transform3_a_0*/ mload(0xd80), /*intermediate_value/after_lin_transform3_a_0*/ mload(0xd80), PRIME), /*intermediate_value/after_lin_transform3_a_0*/ mload(0xd80), PRIME)), PRIME) // Numerator: 1. // val *= 1. // val := mulmod(val, 1, PRIME). // Denominator: point^trace_length - 1. // val *= denominator_invs[0]. val := mulmod(val, mload(0xf80), PRIME) // res += val * (coefficients[12] + coefficients[13] * adjustments[0]). res := addmod(res, mulmod(val, add(/*coefficients[12]*/ mload(0x560), mulmod(/*coefficients[13]*/ mload(0x580), /*adjustments[0]*/mload(0x1060), PRIME)), PRIME), PRIME) } { // Constraint expression for step3_b: column14_row0 - after_lin_transform3_b_0 * after_lin_transform3_b_0 * after_lin_transform3_b_0. let val := addmod( /*column14_row0*/ mload(0xbe0), sub( PRIME, mulmod( mulmod( /*intermediate_value/after_lin_transform3_b_0*/ mload(0xda0), /*intermediate_value/after_lin_transform3_b_0*/ mload(0xda0), PRIME), /*intermediate_value/after_lin_transform3_b_0*/ mload(0xda0), PRIME)), PRIME) // Numerator: 1. // val *= 1. // val := mulmod(val, 1, PRIME). // Denominator: point^trace_length - 1. // val *= denominator_invs[0]. val := mulmod(val, mload(0xf80), PRIME) // res += val * (coefficients[14] + coefficients[15] * adjustments[0]). res := addmod(res, mulmod(val, add(/*coefficients[14]*/ mload(0x5a0), mulmod(/*coefficients[15]*/ mload(0x5c0), /*adjustments[0]*/mload(0x1060), PRIME)), PRIME), PRIME) } { // Constraint expression for step4_a: column5_row0 - after_lin_transform4_a_0 * after_lin_transform4_a_0 * after_lin_transform4_a_0. let val := addmod( /*column5_row0*/ mload(0xaa0), sub( PRIME, mulmod( mulmod( /*intermediate_value/after_lin_transform4_a_0*/ mload(0xdc0), /*intermediate_value/after_lin_transform4_a_0*/ mload(0xdc0), PRIME), /*intermediate_value/after_lin_transform4_a_0*/ mload(0xdc0), PRIME)), PRIME) // Numerator: 1. // val *= 1. // val := mulmod(val, 1, PRIME). // Denominator: point^trace_length - 1. // val *= denominator_invs[0]. val := mulmod(val, mload(0xf80), PRIME) // res += val * (coefficients[16] + coefficients[17] * adjustments[0]). res := addmod(res, mulmod(val, add(/*coefficients[16]*/ mload(0x5e0), mulmod(/*coefficients[17]*/ mload(0x600), /*adjustments[0]*/mload(0x1060), PRIME)), PRIME), PRIME) } { // Constraint expression for step4_b: column15_row0 - after_lin_transform4_b_0 * after_lin_transform4_b_0 * after_lin_transform4_b_0. let val := addmod( /*column15_row0*/ mload(0xc00), sub( PRIME, mulmod( mulmod( /*intermediate_value/after_lin_transform4_b_0*/ mload(0xde0), /*intermediate_value/after_lin_transform4_b_0*/ mload(0xde0), PRIME), /*intermediate_value/after_lin_transform4_b_0*/ mload(0xde0), PRIME)), PRIME) // Numerator: 1. // val *= 1. // val := mulmod(val, 1, PRIME). // Denominator: point^trace_length - 1. // val *= denominator_invs[0]. val := mulmod(val, mload(0xf80), PRIME) // res += val * (coefficients[18] + coefficients[19] * adjustments[0]). res := addmod(res, mulmod(val, add(/*coefficients[18]*/ mload(0x620), mulmod(/*coefficients[19]*/ mload(0x640), /*adjustments[0]*/mload(0x1060), PRIME)), PRIME), PRIME) } { // Constraint expression for step5_a: column6_row0 - after_lin_transform5_a_0 * after_lin_transform5_a_0 * after_lin_transform5_a_0. let val := addmod( /*column6_row0*/ mload(0xac0), sub( PRIME, mulmod( mulmod( /*intermediate_value/after_lin_transform5_a_0*/ mload(0xe00), /*intermediate_value/after_lin_transform5_a_0*/ mload(0xe00), PRIME), /*intermediate_value/after_lin_transform5_a_0*/ mload(0xe00), PRIME)), PRIME) // Numerator: 1. // val *= 1. // val := mulmod(val, 1, PRIME). // Denominator: point^trace_length - 1. // val *= denominator_invs[0]. val := mulmod(val, mload(0xf80), PRIME) // res += val * (coefficients[20] + coefficients[21] * adjustments[0]). res := addmod(res, mulmod(val, add(/*coefficients[20]*/ mload(0x660), mulmod(/*coefficients[21]*/ mload(0x680), /*adjustments[0]*/mload(0x1060), PRIME)), PRIME), PRIME) } { // Constraint expression for step5_b: column16_row0 - after_lin_transform5_b_0 * after_lin_transform5_b_0 * after_lin_transform5_b_0. let val := addmod( /*column16_row0*/ mload(0xc20), sub( PRIME, mulmod( mulmod( /*intermediate_value/after_lin_transform5_b_0*/ mload(0xe20), /*intermediate_value/after_lin_transform5_b_0*/ mload(0xe20), PRIME), /*intermediate_value/after_lin_transform5_b_0*/ mload(0xe20), PRIME)), PRIME) // Numerator: 1. // val *= 1. // val := mulmod(val, 1, PRIME). // Denominator: point^trace_length - 1. // val *= denominator_invs[0]. val := mulmod(val, mload(0xf80), PRIME) // res += val * (coefficients[22] + coefficients[23] * adjustments[0]). res := addmod(res, mulmod(val, add(/*coefficients[22]*/ mload(0x6a0), mulmod(/*coefficients[23]*/ mload(0x6c0), /*adjustments[0]*/mload(0x1060), PRIME)), PRIME), PRIME) } { // Constraint expression for step6_a: column7_row0 - after_lin_transform6_a_0 * after_lin_transform6_a_0 * after_lin_transform6_a_0. let val := addmod( /*column7_row0*/ mload(0xae0), sub( PRIME, mulmod( mulmod( /*intermediate_value/after_lin_transform6_a_0*/ mload(0xe40), /*intermediate_value/after_lin_transform6_a_0*/ mload(0xe40), PRIME), /*intermediate_value/after_lin_transform6_a_0*/ mload(0xe40), PRIME)), PRIME) // Numerator: 1. // val *= 1. // val := mulmod(val, 1, PRIME). // Denominator: point^trace_length - 1. // val *= denominator_invs[0]. val := mulmod(val, mload(0xf80), PRIME) // res += val * (coefficients[24] + coefficients[25] * adjustments[0]). res := addmod(res, mulmod(val, add(/*coefficients[24]*/ mload(0x6e0), mulmod(/*coefficients[25]*/ mload(0x700), /*adjustments[0]*/mload(0x1060), PRIME)), PRIME), PRIME) } { // Constraint expression for step6_b: column17_row0 - after_lin_transform6_b_0 * after_lin_transform6_b_0 * after_lin_transform6_b_0. let val := addmod( /*column17_row0*/ mload(0xc40), sub( PRIME, mulmod( mulmod( /*intermediate_value/after_lin_transform6_b_0*/ mload(0xe60), /*intermediate_value/after_lin_transform6_b_0*/ mload(0xe60), PRIME), /*intermediate_value/after_lin_transform6_b_0*/ mload(0xe60), PRIME)), PRIME) // Numerator: 1. // val *= 1. // val := mulmod(val, 1, PRIME). // Denominator: point^trace_length - 1. // val *= denominator_invs[0]. val := mulmod(val, mload(0xf80), PRIME) // res += val * (coefficients[26] + coefficients[27] * adjustments[0]). res := addmod(res, mulmod(val, add(/*coefficients[26]*/ mload(0x720), mulmod(/*coefficients[27]*/ mload(0x740), /*adjustments[0]*/mload(0x1060), PRIME)), PRIME), PRIME) } { // Constraint expression for step7_a: column8_row0 - after_lin_transform7_a_0 * after_lin_transform7_a_0 * after_lin_transform7_a_0. let val := addmod( /*column8_row0*/ mload(0xb00), sub( PRIME, mulmod( mulmod( /*intermediate_value/after_lin_transform7_a_0*/ mload(0xe80), /*intermediate_value/after_lin_transform7_a_0*/ mload(0xe80), PRIME), /*intermediate_value/after_lin_transform7_a_0*/ mload(0xe80), PRIME)), PRIME) // Numerator: 1. // val *= 1. // val := mulmod(val, 1, PRIME). // Denominator: point^trace_length - 1. // val *= denominator_invs[0]. val := mulmod(val, mload(0xf80), PRIME) // res += val * (coefficients[28] + coefficients[29] * adjustments[0]). res := addmod(res, mulmod(val, add(/*coefficients[28]*/ mload(0x760), mulmod(/*coefficients[29]*/ mload(0x780), /*adjustments[0]*/mload(0x1060), PRIME)), PRIME), PRIME) } { // Constraint expression for step7_b: column18_row0 - after_lin_transform7_b_0 * after_lin_transform7_b_0 * after_lin_transform7_b_0. let val := addmod( /*column18_row0*/ mload(0xc60), sub( PRIME, mulmod( mulmod( /*intermediate_value/after_lin_transform7_b_0*/ mload(0xea0), /*intermediate_value/after_lin_transform7_b_0*/ mload(0xea0), PRIME), /*intermediate_value/after_lin_transform7_b_0*/ mload(0xea0), PRIME)), PRIME) // Numerator: 1. // val *= 1. // val := mulmod(val, 1, PRIME). // Denominator: point^trace_length - 1. // val *= denominator_invs[0]. val := mulmod(val, mload(0xf80), PRIME) // res += val * (coefficients[30] + coefficients[31] * adjustments[0]). res := addmod(res, mulmod(val, add(/*coefficients[30]*/ mload(0x7a0), mulmod(/*coefficients[31]*/ mload(0x7c0), /*adjustments[0]*/mload(0x1060), PRIME)), PRIME), PRIME) } { // Constraint expression for step8_a: column9_row0 - after_lin_transform8_a_0 * after_lin_transform8_a_0 * after_lin_transform8_a_0. let val := addmod( /*column9_row0*/ mload(0xb20), sub( PRIME, mulmod( mulmod( /*intermediate_value/after_lin_transform8_a_0*/ mload(0xec0), /*intermediate_value/after_lin_transform8_a_0*/ mload(0xec0), PRIME), /*intermediate_value/after_lin_transform8_a_0*/ mload(0xec0), PRIME)), PRIME) // Numerator: 1. // val *= 1. // val := mulmod(val, 1, PRIME). // Denominator: point^trace_length - 1. // val *= denominator_invs[0]. val := mulmod(val, mload(0xf80), PRIME) // res += val * (coefficients[32] + coefficients[33] * adjustments[0]). res := addmod(res, mulmod(val, add(/*coefficients[32]*/ mload(0x7e0), mulmod(/*coefficients[33]*/ mload(0x800), /*adjustments[0]*/mload(0x1060), PRIME)), PRIME), PRIME) } { // Constraint expression for step8_b: column19_row0 - after_lin_transform8_b_0 * after_lin_transform8_b_0 * after_lin_transform8_b_0. let val := addmod( /*column19_row0*/ mload(0xc80), sub( PRIME, mulmod( mulmod( /*intermediate_value/after_lin_transform8_b_0*/ mload(0xee0), /*intermediate_value/after_lin_transform8_b_0*/ mload(0xee0), PRIME), /*intermediate_value/after_lin_transform8_b_0*/ mload(0xee0), PRIME)), PRIME) // Numerator: 1. // val *= 1. // val := mulmod(val, 1, PRIME). // Denominator: point^trace_length - 1. // val *= denominator_invs[0]. val := mulmod(val, mload(0xf80), PRIME) // res += val * (coefficients[34] + coefficients[35] * adjustments[0]). res := addmod(res, mulmod(val, add(/*coefficients[34]*/ mload(0x820), mulmod(/*coefficients[35]*/ mload(0x840), /*adjustments[0]*/mload(0x1060), PRIME)), PRIME), PRIME) } { // Constraint expression for step9_a: column0_row1 - after_lin_transform9_a_0 * after_lin_transform9_a_0 * after_lin_transform9_a_0. let val := addmod( /*column0_row1*/ mload(0xa00), sub( PRIME, mulmod( mulmod( /*intermediate_value/after_lin_transform9_a_0*/ mload(0xf00), /*intermediate_value/after_lin_transform9_a_0*/ mload(0xf00), PRIME), /*intermediate_value/after_lin_transform9_a_0*/ mload(0xf00), PRIME)), PRIME) // Numerator: point - trace_generator^(trace_length - 1). // val *= numerators[0]. val := mulmod(val, mload(0x1040), PRIME) // Denominator: point^trace_length - 1. // val *= denominator_invs[0]. val := mulmod(val, mload(0xf80), PRIME) // res += val * (coefficients[36] + coefficients[37] * adjustments[1]). res := addmod(res, mulmod(val, add(/*coefficients[36]*/ mload(0x860), mulmod(/*coefficients[37]*/ mload(0x880), /*adjustments[1]*/mload(0x1080), PRIME)), PRIME), PRIME) } { // Constraint expression for step9_b: column10_row1 - after_lin_transform9_b_0 * after_lin_transform9_b_0 * after_lin_transform9_b_0. let val := addmod( /*column10_row1*/ mload(0xb60), sub( PRIME, mulmod( mulmod( /*intermediate_value/after_lin_transform9_b_0*/ mload(0xf20), /*intermediate_value/after_lin_transform9_b_0*/ mload(0xf20), PRIME), /*intermediate_value/after_lin_transform9_b_0*/ mload(0xf20), PRIME)), PRIME) // Numerator: point - trace_generator^(trace_length - 1). // val *= numerators[0]. val := mulmod(val, mload(0x1040), PRIME) // Denominator: point^trace_length - 1. // val *= denominator_invs[0]. val := mulmod(val, mload(0xf80), PRIME) // res += val * (coefficients[38] + coefficients[39] * adjustments[1]). res := addmod(res, mulmod(val, add(/*coefficients[38]*/ mload(0x8a0), mulmod(/*coefficients[39]*/ mload(0x8c0), /*adjustments[1]*/mload(0x1080), PRIME)), PRIME), PRIME) } { // Constraint expression for input_a: column0_row0 - input_value_a. let val := addmod(/*column0_row0*/ mload(0x9e0), sub(PRIME, /*input_value_a*/ mload(0x320)), PRIME) // Numerator: 1. // val *= 1. // val := mulmod(val, 1, PRIME). // Denominator: point - 1. // val *= denominator_invs[1]. val := mulmod(val, mload(0xfa0), PRIME) // res += val * (coefficients[40] + coefficients[41] * adjustments[2]). res := addmod(res, mulmod(val, add(/*coefficients[40]*/ mload(0x8e0), mulmod(/*coefficients[41]*/ mload(0x900), /*adjustments[2]*/mload(0x10a0), PRIME)), PRIME), PRIME) } { // Constraint expression for output_a: column9_row0 - output_value_a. let val := addmod(/*column9_row0*/ mload(0xb20), sub(PRIME, /*output_value_a*/ mload(0x340)), PRIME) // Numerator: 1. // val *= 1. // val := mulmod(val, 1, PRIME). // Denominator: point - trace_generator^(trace_length - 1). // val *= denominator_invs[2]. val := mulmod(val, mload(0xfc0), PRIME) // res += val * (coefficients[42] + coefficients[43] * adjustments[2]). res := addmod(res, mulmod(val, add(/*coefficients[42]*/ mload(0x920), mulmod(/*coefficients[43]*/ mload(0x940), /*adjustments[2]*/mload(0x10a0), PRIME)), PRIME), PRIME) } { // Constraint expression for input_b: column10_row0 - input_value_b. let val := addmod(/*column10_row0*/ mload(0xb40), sub(PRIME, /*input_value_b*/ mload(0x360)), PRIME) // Numerator: 1. // val *= 1. // val := mulmod(val, 1, PRIME). // Denominator: point - 1. // val *= denominator_invs[1]. val := mulmod(val, mload(0xfa0), PRIME) // res += val * (coefficients[44] + coefficients[45] * adjustments[2]). res := addmod(res, mulmod(val, add(/*coefficients[44]*/ mload(0x960), mulmod(/*coefficients[45]*/ mload(0x980), /*adjustments[2]*/mload(0x10a0), PRIME)), PRIME), PRIME) } { // Constraint expression for output_b: column19_row0 - output_value_b. let val := addmod(/*column19_row0*/ mload(0xc80), sub(PRIME, /*output_value_b*/ mload(0x380)), PRIME) // Numerator: 1. // val *= 1. // val := mulmod(val, 1, PRIME). // Denominator: point - trace_generator^(trace_length - 1). // val *= denominator_invs[2]. val := mulmod(val, mload(0xfc0), PRIME) // res += val * (coefficients[46] + coefficients[47] * adjustments[2]). res := addmod(res, mulmod(val, add(/*coefficients[46]*/ mload(0x9a0), mulmod(/*coefficients[47]*/ mload(0x9c0), /*adjustments[2]*/mload(0x10a0), PRIME)), PRIME), PRIME) } mstore(0, res) return(0, 0x20) } } } } contract PeriodicColumnContract { function compute(uint256 x) external pure returns (uint256 result); } contract PrimeFieldElement6 { uint256 internal constant K_MODULUS = 0x30000003000000010000000000000001; uint256 internal constant K_MODULUS_MASK = 0x3fffffffffffffffffffffffffffffff; uint256 internal constant K_MONTGOMERY_R = 0xffffff0fffffffafffffffffffffffb; uint256 internal constant K_MONTGOMERY_R_INV = 0x9000001200000096000000600000001; uint256 internal constant GENERATOR_VAL = 3; uint256 internal constant ONE_VAL = 1; uint256 internal constant GEN1024_VAL = 0x2361be682e1cc2d366e86e194024739f; function fromMontgomery(uint256 val) internal pure returns (uint256 res) { // uint256 res = fmul(val, kMontgomeryRInv); assembly { res := mulmod( val, 0x9000001200000096000000600000001, 0x30000003000000010000000000000001 ) } return res; } function fromMontgomeryBytes(bytes32 bs) internal pure returns (uint256) { // Assuming bs is a 256bit bytes object, in Montgomery form, it is read into a field // element. uint256 res = uint256(bs); return fromMontgomery(res); } function toMontgomeryInt(uint256 val) internal pure returns (uint256 res) { //uint256 res = fmul(val, kMontgomeryR); assembly { res := mulmod( val, 0xffffff0fffffffafffffffffffffffb, 0x30000003000000010000000000000001 ) } return res; } function fmul(uint256 a, uint256 b) internal pure returns (uint256 res) { //uint256 res = mulmod(a, b, kModulus); assembly { res := mulmod(a, b, 0x30000003000000010000000000000001) } return res; } function fadd(uint256 a, uint256 b) internal pure returns (uint256 res) { // uint256 res = addmod(a, b, kModulus); assembly { res := addmod(a, b, 0x30000003000000010000000000000001) } return res; } function fsub(uint256 a, uint256 b) internal pure returns (uint256 res) { // uint256 res = addmod(a, kModulus - b, kModulus); assembly { res := addmod( a, sub(0x30000003000000010000000000000001, b), 0x30000003000000010000000000000001 ) } return res; } function fpow(uint256 val, uint256 exp) internal returns (uint256) { return expmod(val, exp, K_MODULUS); } function expmod(uint256 base, uint256 exponent, uint256 modulus) internal returns (uint256 res) { assembly { let p := mload(0x40) mstore(p, 0x20) // Length of Base. mstore(add(p, 0x20), 0x20) // Length of Exponent. mstore(add(p, 0x40), 0x20) // Length of Modulus. mstore(add(p, 0x60), base) // Base. mstore(add(p, 0x80), exponent) // Exponent. mstore(add(p, 0xa0), modulus) // Modulus. // Call modexp precompile. if iszero(call(not(0), 0x05, 0, p, 0xc0, p, 0x20)) { revert(0, 0) } res := mload(p) } } function inverse(uint256 val) internal returns (uint256) { return expmod(val, K_MODULUS - 2, K_MODULUS); } } contract Prng is PrimeFieldElement6 { function storePrng(uint256 statePtr, bytes32 digest, uint256 counter) internal pure { assembly { mstore(statePtr, digest) mstore(add(statePtr, 0x20), counter) } } function loadPrng(uint256 statePtr) internal pure returns (bytes32, uint256) { bytes32 digest; uint256 counter; assembly { digest := mload(statePtr) counter := mload(add(statePtr, 0x20)) } return (digest, counter); } function initPrng(uint256 prngPtr, bytes32 publicInputHash) internal pure { storePrng(prngPtr, /*keccak256(publicInput)*/ publicInputHash, 0); } /* Auxiliary function for getRandomBytes. */ function getRandomBytesInner(bytes32 digest, uint256 counter) internal pure returns (bytes32, uint256, bytes32) { // returns 32 bytes (for random field elements or four queries at a time). bytes32 randomBytes = keccak256(abi.encodePacked(digest, counter)); return (digest, counter + 1, randomBytes); } /* Returns 32 bytes. Used for a random field element, or for 4 query indices. */ function getRandomBytes(uint256 prngPtr) internal pure returns (bytes32 randomBytes) { bytes32 digest; uint256 counter; (digest, counter) = loadPrng(prngPtr); // returns 32 bytes (for random field elements or four queries at a time). (digest, counter, randomBytes) = getRandomBytesInner(digest, counter); storePrng(prngPtr, digest, counter); return randomBytes; } function mixSeedWithBytes(uint256 prngPtr, bytes memory dataBytes) internal pure { bytes32 digest; assembly { digest := mload(prngPtr) } initPrng(prngPtr, keccak256(abi.encodePacked(digest, dataBytes))); } function getPrngDigest(uint256 prngPtr) internal pure returns (bytes32 digest) { assembly { digest := mload(prngPtr) } } } contract PublicInputOffsets { // The following constants are offsets of data expected in the public input. uint256 internal constant OFFSET_LOG_TRACE_LENGTH = 0; uint256 internal constant OFFSET_VDF_OUTPUT_X = 1; uint256 internal constant OFFSET_VDF_OUTPUT_Y = 2; uint256 internal constant OFFSET_VDF_INPUT_X = 3; uint256 internal constant OFFSET_VDF_INPUT_Y = 4; // The Verifier derives the number of iterations from the log of the trace length. // The Vending contract uses the number of iterations. uint256 internal constant OFFSET_N_ITER = 0; } contract StarkParameters is PrimeFieldElement6 { uint256 constant internal N_COEFFICIENTS = 48; uint256 constant internal MASK_SIZE = 22; uint256 constant internal N_ROWS_IN_MASK = 2; uint256 constant internal N_COLUMNS_IN_MASK = 20; uint256 constant internal CONSTRAINTS_DEGREE_BOUND = 2; uint256 constant internal N_OODS_VALUES = MASK_SIZE + CONSTRAINTS_DEGREE_BOUND; uint256 constant internal N_OODS_COEFFICIENTS = N_OODS_VALUES; uint256 constant internal MAX_FRI_STEP = 3; } contract VerifierChannel is Prng { /* We store the state of the channel in uint256[3] as follows: [0] proof pointer. [1] prng digest. [2] prng counter. */ uint256 constant internal CHANNEL_STATE_SIZE = 3; event LogValue(bytes32 val); event SendRandomnessEvent(uint256 val); event ReadFieldElementEvent(uint256 val); event ReadHashEvent(bytes32 val); function getPrngPtr(uint256 channelPtr) internal pure returns (uint256) { return channelPtr + 0x20; } function initChannel(uint256 channelPtr, uint256 proofPtr, bytes32 publicInputHash) internal pure { assembly { // Skip 0x20 bytes length at the beginning of the proof. mstore(channelPtr, add(proofPtr, 0x20)) } initPrng(getPrngPtr(channelPtr), publicInputHash); } function sendFieldElements(uint256 channelPtr, uint256 nElements, uint256 targetPtr) internal pure { require(nElements < 0x1000000, "Overflow protection failed."); assembly { let PRIME := 0x30000003000000010000000000000001 let PRIME_MON_R_INV := 0x9000001200000096000000600000001 let PRIME_MASK := 0x3fffffffffffffffffffffffffffffff let digestPtr := add(channelPtr, 0x20) let counterPtr := add(channelPtr, 0x40) let endPtr := add(targetPtr, mul(nElements, 0x20)) for { } lt(targetPtr, endPtr) { targetPtr := add(targetPtr, 0x20) } { // *targetPtr = getRandomFieldElement(getPrngPtr(channelPtr)); let fieldElement := PRIME // while (fieldElement >= PRIME). for { } iszero(lt(fieldElement, PRIME)) { } { // keccak256(abi.encodePacked(digest, counter)); fieldElement := and(keccak256(digestPtr, 0x40), PRIME_MASK) // *counterPtr += 1; mstore(counterPtr, add(mload(counterPtr), 1)) } // *targetPtr = fromMontgomery(fieldElement); mstore(targetPtr, mulmod(fieldElement, PRIME_MON_R_INV, PRIME)) // emit ReadFieldElementEvent(fieldElement); // log1(targetPtr, 0x20, 0x4bfcc54f35095697be2d635fb0706801e13637312eff0cedcdfc254b3b8c385e); } } } /* Sends random queries and returns an array of queries sorted in ascending order. Generates count queries in the range [0, mask] and returns the number of unique queries. Note that mask is of the form 2^k-1 (for some k). Note that queriesOutPtr may be (and is) inteleaved with other arrays. The stride parameter is passed to indicate the distance between every two entries to the queries array, i.e. stride = 0x20*(number of interleaved arrays). */ function sendRandomQueries( uint256 channelPtr, uint256 count, uint256 mask, uint256 queriesOutPtr, uint256 stride) internal pure returns (uint256) { uint256 val; uint256 shift = 0; uint256 endPtr = queriesOutPtr; for (uint256 i = 0; i < count; i++) { if (shift == 0) { val = uint256(getRandomBytes(getPrngPtr(channelPtr))); shift = 0x100; } shift -= 0x40; uint256 queryIdx = (val >> shift) & mask; // emit sendRandomnessEvent(queryIdx); uint256 ptr = endPtr; uint256 curr; // Insert new queryIdx in the correct place like insertion sort. while (ptr > queriesOutPtr) { assembly { curr := mload(sub(ptr, stride)) } if (queryIdx >= curr) { break; } assembly { mstore(ptr, curr) } ptr -= stride; } if (queryIdx != curr) { assembly { mstore(ptr, queryIdx) } endPtr += stride; } else { // Revert right shuffling. while (ptr < endPtr) { assembly { mstore(ptr, mload(add(ptr, stride))) ptr := add(ptr, stride) } } } } return (endPtr - queriesOutPtr) / stride; } function readBytes(uint256 channelPtr, bool mix) internal pure returns (bytes32) { uint256 proofPtr; bytes32 val; assembly { proofPtr := mload(channelPtr) val := mload(proofPtr) mstore(channelPtr, add(proofPtr, 0x20)) } if (mix) { // inline: Prng.mixSeedWithBytes(getPrngPtr(channelPtr), abi.encodePacked(val)); assembly { let digestPtr := add(channelPtr, 0x20) let counterPtr := add(digestPtr, 0x20) mstore(counterPtr, val) // prng.digest := keccak256(digest||val), nonce was written earlier. mstore(digestPtr, keccak256(digestPtr, 0x40)) // prng.counter := 0. mstore(counterPtr, 0) } } return val; } function readHash(uint256 channelPtr, bool mix) internal pure returns (bytes32) { bytes32 val = readBytes(channelPtr, mix); // emit ReadHashEvent(val); return val; } function readFieldElement(uint256 channelPtr, bool mix) internal pure returns (uint256) { uint256 val = fromMontgomery(uint256(readBytes(channelPtr, mix))); // emit ReadFieldElementEvent(val); return val; } function verifyProofOfWork(uint256 channelPtr, uint256 proofOfWorkBits) internal pure { if (proofOfWorkBits == 0) { return; } uint256 proofOfWorkDigest; assembly { // [0:29] := 0123456789abcded || digest || workBits. mstore(0, 0x0123456789abcded000000000000000000000000000000000000000000000000) let digest := mload(add(channelPtr, 0x20)) mstore(0x8, digest) mstore8(0x28, proofOfWorkBits) mstore(0, keccak256(0, 0x29)) let proofPtr := mload(channelPtr) mstore(0x20, mload(proofPtr)) // proofOfWorkDigest:= keccak256(keccak256(0123456789abcded || digest || workBits) || nonce). proofOfWorkDigest := keccak256(0, 0x28) mstore(0, digest) // prng.digest := keccak256(digest||nonce), nonce was written earlier. mstore(add(channelPtr, 0x20), keccak256(0, 0x28)) // prng.counter := 0. mstore(add(channelPtr, 0x40), 0) mstore(channelPtr, add(proofPtr, 0x8)) } uint256 proofOfWorkThreshold = uint256(1) << (256 - proofOfWorkBits); require(proofOfWorkDigest < proofOfWorkThreshold, "Proof of work check failed."); } } contract FactRegistry is IQueryableFactRegistry { // Mapping: fact hash -> true. mapping (bytes32 => bool) private verifiedFact; // Indicates whether the Fact Registry has at least one fact registered. bool anyFactRegistered; /* Checks if a fact has been verified. */ function isValid(bytes32 fact) external view returns(bool) { return verifiedFact[fact]; } function registerFact( bytes32 factHash ) internal { // This function stores the testiment hash in the mapping. verifiedFact[factHash] = true; // Mark first time off. if (!anyFactRegistered) { anyFactRegistered = true; } } /* Indicates whether at least one fact was registered. */ function hasRegisteredFact() external view returns(bool) { return anyFactRegistered; } } contract FriLayer is MerkleVerifier, PrimeFieldElement6 { event LogGas(string name, uint256 val); uint256 constant internal FRI_MAX_FRI_STEP = 4; uint256 constant internal MAX_COSET_SIZE = 2**FRI_MAX_FRI_STEP; // Generator of the group of size MAX_COSET_SIZE: GENERATOR_VAL**((PRIME - 1)/MAX_COSET_SIZE). uint256 constant internal FRI_GROUP_GEN = 0x1388a7fd3b4b9599dc4b0691d6a5fcba; uint256 constant internal FRI_GROUP_SIZE = 0x20 * MAX_COSET_SIZE; uint256 constant internal FRI_CTX_TO_COSET_EVALUATIONS_OFFSET = 0; uint256 constant internal FRI_CTX_TO_FRI_GROUP_OFFSET = FRI_GROUP_SIZE; uint256 constant internal FRI_CTX_TO_FRI_HALF_INV_GROUP_OFFSET = FRI_CTX_TO_FRI_GROUP_OFFSET + FRI_GROUP_SIZE; uint256 constant internal FRI_CTX_SIZE = FRI_CTX_TO_FRI_HALF_INV_GROUP_OFFSET + (FRI_GROUP_SIZE / 2); function nextLayerElementFromTwoPreviousLayerElements( uint256 fX, uint256 fMinusX, uint256 evalPoint, uint256 xInv) internal pure returns (uint256 res) { // Folding formula: // f(x) = g(x^2) + xh(x^2) // f(-x) = g((-x)^2) - xh((-x)^2) = g(x^2) - xh(x^2) // => // 2g(x^2) = f(x) + f(-x) // 2h(x^2) = (f(x) - f(-x))/x // => The 2*interpolation at evalPoint is: // 2*(g(x^2) + evalPoint*h(x^2)) = f(x) + f(-x) + evalPoint*(f(x) - f(-x))*xInv. // // Note that multiplying by 2 doesn't affect the degree, // so we can just agree to do that on both the prover and verifier. assembly { // PRIME is PrimeFieldElement6.K_MODULUS. let PRIME := 0x30000003000000010000000000000001 // Note that whenever we call add(), the result is always less than 2*PRIME, // so there are no overflows. res := addmod(add(fX, fMinusX), mulmod(mulmod(evalPoint, xInv, PRIME), add(fX, /*-fMinusX*/sub(PRIME, fMinusX)), PRIME), PRIME) } } /* Reads 4 elements, and applies 2 + 1 FRI transformations to obtain a single element. FRI layer n: f0 f1 f2 f3 ----------------------------------------- \ / -- \ / ----------- FRI layer n+1: f0 f2 -------------------------------------------- \ ---/ ------------- FRI layer n+2: f0 The basic FRI transformation is described in nextLayerElementFromTwoPreviousLayerElements(). */ function do2FriSteps( uint256 friHalfInvGroupPtr, uint256 evaluationsOnCosetPtr, uint256 cosetOffset_, uint256 friEvalPoint) internal pure returns (uint256 nextLayerValue, uint256 nextXInv) { assembly { let PRIME := 0x30000003000000010000000000000001 let friEvalPointDivByX := mulmod(friEvalPoint, cosetOffset_, PRIME) let f0 := mload(evaluationsOnCosetPtr) { let f1 := mload(add(evaluationsOnCosetPtr, 0x20)) // f0 < 3P ( = 1 + 1 + 1). f0 := add(add(f0, f1), mulmod(friEvalPointDivByX, add(f0, /*-fMinusX*/sub(PRIME, f1)), PRIME)) } let f2 := mload(add(evaluationsOnCosetPtr, 0x40)) { let f3 := mload(add(evaluationsOnCosetPtr, 0x60)) f2 := addmod(add(f2, f3), mulmod(add(f2, /*-fMinusX*/sub(PRIME, f3)), mulmod(mload(add(friHalfInvGroupPtr, 0x20)), friEvalPointDivByX, PRIME), PRIME), PRIME) } { let newXInv := mulmod(cosetOffset_, cosetOffset_, PRIME) nextXInv := mulmod(newXInv, newXInv, PRIME) } // f0 + f2 < 4P ( = 3 + 1). nextLayerValue := addmod(add(f0, f2), mulmod(mulmod(friEvalPointDivByX, friEvalPointDivByX, PRIME), add(f0, /*-fMinusX*/sub(PRIME, f2)), PRIME), PRIME) } } /* Reads 8 elements, and applies 4 + 2 + 1 FRI transformation to obtain a single element. See do2FriSteps for more detailed explanation. */ function do3FriSteps( uint256 friHalfInvGroupPtr, uint256 evaluationsOnCosetPtr, uint256 cosetOffset_, uint256 friEvalPoint) internal pure returns (uint256 nextLayerValue, uint256 nextXInv) { assembly { let PRIME := 0x30000003000000010000000000000001 let MPRIME := 0x300000030000000100000000000000010 let f0 := mload(evaluationsOnCosetPtr) let friEvalPointDivByX := mulmod(friEvalPoint, cosetOffset_, PRIME) let friEvalPointDivByXSquared := mulmod(friEvalPointDivByX, friEvalPointDivByX, PRIME) let imaginaryUnit := mload(add(friHalfInvGroupPtr, 0x20)) { let f1 := mload(add(evaluationsOnCosetPtr, 0x20)) // f0 < 3P ( = 1 + 1 + 1). f0 := add(add(f0, f1), mulmod(friEvalPointDivByX, add(f0, /*-fMinusX*/sub(PRIME, f1)), PRIME)) } { let f2 := mload(add(evaluationsOnCosetPtr, 0x40)) { let f3 := mload(add(evaluationsOnCosetPtr, 0x60)) // f2 < 3P ( = 1 + 1 + 1). f2 := add(add(f2, f3), mulmod(add(f2, /*-fMinusX*/sub(PRIME, f3)), mulmod(friEvalPointDivByX, imaginaryUnit, PRIME), PRIME)) } // f0 < 7P ( = 3 + 3 + 1). f0 := add(add(f0, f2), mulmod(friEvalPointDivByXSquared, add(f0, /*-fMinusX*/sub(MPRIME, f2)), PRIME)) } { let f4 := mload(add(evaluationsOnCosetPtr, 0x80)) { let friEvalPointDivByX2 := mulmod(friEvalPointDivByX, mload(add(friHalfInvGroupPtr, 0x40)), PRIME) { let f5 := mload(add(evaluationsOnCosetPtr, 0xa0)) // f4 < 3P ( = 1 + 1 + 1). f4 := add(add(f4, f5), mulmod(friEvalPointDivByX2, add(f4, /*-fMinusX*/sub(PRIME, f5)), PRIME)) } let f6 := mload(add(evaluationsOnCosetPtr, 0xc0)) { let f7 := mload(add(evaluationsOnCosetPtr, 0xe0)) // f6 < 3P ( = 1 + 1 + 1). f6 := add(add(f6, f7), mulmod(add(f6, /*-fMinusX*/sub(PRIME, f7)), // friEvalPointDivByX2 * imaginaryUnit == // friEvalPointDivByX * mload(add(friHalfInvGroupPtr, 0x60)). mulmod(friEvalPointDivByX2, imaginaryUnit, PRIME), PRIME)) } // f4 < 7P ( = 3 + 3 + 1). f4 := add(add(f4, f6), mulmod(mulmod(friEvalPointDivByX2, friEvalPointDivByX2, PRIME), add(f4, /*-fMinusX*/sub(MPRIME, f6)), PRIME)) } // f0, f4 < 7P -> f0 + f4 < 14P && 9P < f0 + (MPRIME - f4) < 23P. nextLayerValue := addmod(add(f0, f4), mulmod(mulmod(friEvalPointDivByXSquared, friEvalPointDivByXSquared, PRIME), add(f0, /*-fMinusX*/sub(MPRIME, f4)), PRIME), PRIME) } { let xInv2 := mulmod(cosetOffset_, cosetOffset_, PRIME) let xInv4 := mulmod(xInv2, xInv2, PRIME) nextXInv := mulmod(xInv4, xInv4, PRIME) } } } /* This function reads 16 elements, and applies 8 + 4 + 2 + 1 fri transformation to obtain a single element. See do2FriSteps for more detailed explanation. */ function do4FriSteps( uint256 friHalfInvGroupPtr, uint256 evaluationsOnCosetPtr, uint256 cosetOffset_, uint256 friEvalPoint) internal pure returns (uint256 nextLayerValue, uint256 nextXInv) { assembly { let friEvalPointDivByXTessed let PRIME := 0x30000003000000010000000000000001 let MPRIME := 0x300000030000000100000000000000010 let f0 := mload(evaluationsOnCosetPtr) let friEvalPointDivByX := mulmod(friEvalPoint, cosetOffset_, PRIME) let imaginaryUnit := mload(add(friHalfInvGroupPtr, 0x20)) { let f1 := mload(add(evaluationsOnCosetPtr, 0x20)) // f0 < 3P ( = 1 + 1 + 1). f0 := add(add(f0, f1), mulmod(friEvalPointDivByX, add(f0, /*-fMinusX*/sub(PRIME, f1)), PRIME)) } { let f2 := mload(add(evaluationsOnCosetPtr, 0x40)) { let f3 := mload(add(evaluationsOnCosetPtr, 0x60)) // f2 < 3P ( = 1 + 1 + 1). f2 := add(add(f2, f3), mulmod(add(f2, /*-fMinusX*/sub(PRIME, f3)), mulmod(friEvalPointDivByX, imaginaryUnit, PRIME), PRIME)) } { let friEvalPointDivByXSquared := mulmod(friEvalPointDivByX, friEvalPointDivByX, PRIME) friEvalPointDivByXTessed := mulmod(friEvalPointDivByXSquared, friEvalPointDivByXSquared, PRIME) // f0 < 7P ( = 3 + 3 + 1). f0 := add(add(f0, f2), mulmod(friEvalPointDivByXSquared, add(f0, /*-fMinusX*/sub(MPRIME, f2)), PRIME)) } } { let f4 := mload(add(evaluationsOnCosetPtr, 0x80)) { let friEvalPointDivByX2 := mulmod(friEvalPointDivByX, mload(add(friHalfInvGroupPtr, 0x40)), PRIME) { let f5 := mload(add(evaluationsOnCosetPtr, 0xa0)) // f4 < 3P ( = 1 + 1 + 1). f4 := add(add(f4, f5), mulmod(friEvalPointDivByX2, add(f4, /*-fMinusX*/sub(PRIME, f5)), PRIME)) } let f6 := mload(add(evaluationsOnCosetPtr, 0xc0)) { let f7 := mload(add(evaluationsOnCosetPtr, 0xe0)) // f6 < 3P ( = 1 + 1 + 1). f6 := add(add(f6, f7), mulmod(add(f6, /*-fMinusX*/sub(PRIME, f7)), // friEvalPointDivByX2 * imaginaryUnit == // friEvalPointDivByX * mload(add(friHalfInvGroupPtr, 0x60)). mulmod(friEvalPointDivByX2, imaginaryUnit, PRIME), PRIME)) } // f4 < 7P ( = 3 + 3 + 1). f4 := add(add(f4, f6), mulmod(mulmod(friEvalPointDivByX2, friEvalPointDivByX2, PRIME), add(f4, /*-fMinusX*/sub(MPRIME, f6)), PRIME)) } // f0 < 15P ( = 7 + 7 + 1). f0 := add(add(f0, f4), mulmod(friEvalPointDivByXTessed, add(f0, /*-fMinusX*/sub(MPRIME, f4)), PRIME)) } { let f8 := mload(add(evaluationsOnCosetPtr, 0x100)) { let friEvalPointDivByX4 := mulmod(friEvalPointDivByX, mload(add(friHalfInvGroupPtr, 0x80)), PRIME) { let f9 := mload(add(evaluationsOnCosetPtr, 0x120)) // f8 < 3P ( = 1 + 1 + 1). f8 := add(add(f8, f9), mulmod(friEvalPointDivByX4, add(f8, /*-fMinusX*/sub(PRIME, f9)), PRIME)) } let f10 := mload(add(evaluationsOnCosetPtr, 0x140)) { let f11 := mload(add(evaluationsOnCosetPtr, 0x160)) // f10 < 3P ( = 1 + 1 + 1). f10 := add(add(f10, f11), mulmod(add(f10, /*-fMinusX*/sub(PRIME, f11)), // friEvalPointDivByX4 * imaginaryUnit == // friEvalPointDivByX * mload(add(friHalfInvGroupPtr, 0xa0)). mulmod(friEvalPointDivByX4, imaginaryUnit, PRIME), PRIME)) } // f8 < 7P ( = 3 + 3 + 1). f8 := add(add(f8, f10), mulmod(mulmod(friEvalPointDivByX4, friEvalPointDivByX4, PRIME), add(f8, /*-fMinusX*/sub(MPRIME, f10)), PRIME)) } { let f12 := mload(add(evaluationsOnCosetPtr, 0x180)) { let friEvalPointDivByX6 := mulmod(friEvalPointDivByX, mload(add(friHalfInvGroupPtr, 0xc0)), PRIME) { let f13 := mload(add(evaluationsOnCosetPtr, 0x1a0)) // f12 < 3P ( = 1 + 1 + 1). f12 := add(add(f12, f13), mulmod(friEvalPointDivByX6, add(f12, /*-fMinusX*/sub(PRIME, f13)), PRIME)) } let f14 := mload(add(evaluationsOnCosetPtr, 0x1c0)) { let f15 := mload(add(evaluationsOnCosetPtr, 0x1e0)) // f14 < 3P ( = 1 + 1 + 1). f14 := add(add(f14, f15), mulmod(add(f14, /*-fMinusX*/sub(PRIME, f15)), // friEvalPointDivByX6 * imaginaryUnit == // friEvalPointDivByX * mload(add(friHalfInvGroupPtr, 0xe0)). mulmod(friEvalPointDivByX6, imaginaryUnit, PRIME), PRIME)) } // f12 < 7P ( = 3 + 3 + 1). f12 := add(add(f12, f14), mulmod(mulmod(friEvalPointDivByX6, friEvalPointDivByX6, PRIME), add(f12, /*-fMinusX*/sub(MPRIME, f14)), PRIME)) } // f8 < 15P ( = 7 + 7 + 1). f8 := add(add(f8, f12), mulmod(mulmod(friEvalPointDivByXTessed, imaginaryUnit, PRIME), add(f8, /*-fMinusX*/sub(MPRIME, f12)), PRIME)) } // f0, f8 < 15P -> f0 + f8 < 30P && 16P < f0 + (MPRIME - f8) < 31P. nextLayerValue := addmod(add(f0, f8), mulmod(mulmod(friEvalPointDivByXTessed, friEvalPointDivByXTessed, PRIME), add(f0, /*-fMinusX*/sub(MPRIME, f8)), PRIME), PRIME) } { let xInv2 := mulmod(cosetOffset_, cosetOffset_, PRIME) let xInv4 := mulmod(xInv2, xInv2, PRIME) let xInv8 := mulmod(xInv4, xInv4, PRIME) nextXInv := mulmod(xInv8, xInv8, PRIME) } } } /* Gathers the "cosetSize" elements that belong to the same coset as the item at the top of the FRI queue and stores them in ctx[MM_FRI_STEP_VALUES:]. Returns friQueueHead - friQueueHead_ + 0x60 * (# elements that were taken from the queue). cosetIdx - the start index of the coset that was gathered. cosetOffset_ - the xInv field element that corresponds to cosetIdx. */ function gatherCosetInputs( uint256 channelPtr, uint256 friCtx, uint256 friQueueHead_, uint256 cosetSize) internal pure returns (uint256 friQueueHead, uint256 cosetIdx, uint256 cosetOffset_) { uint256 evaluationsOnCosetPtr = friCtx + FRI_CTX_TO_COSET_EVALUATIONS_OFFSET; uint256 friGroupPtr = friCtx + FRI_CTX_TO_FRI_GROUP_OFFSET; friQueueHead = friQueueHead_; assembly { let queueItemIdx := mload(friQueueHead) // The coset index is represented by the most significant bits of the queue item index. cosetIdx := and(queueItemIdx, not(sub(cosetSize, 1))) let nextCosetIdx := add(cosetIdx, cosetSize) let PRIME := 0x30000003000000010000000000000001 // Get the algebraic coset offset: // I.e. given c*g^(-k) compute c, where // g is the generator of the coset group. // k is bitReverse(offsetWithinCoset, log2(cosetSize)). // // To do this we multiply the algebraic coset offset at the top of the queue (c*g^(-k)) // by the group element that corresponds to the index inside the coset (g^k). cosetOffset_ := mulmod( /*(c*g^(-k)*/ mload(add(friQueueHead, 0x40)), /*(g^k)*/ mload(add(friGroupPtr, mul(/*offsetWithinCoset*/sub(queueItemIdx, cosetIdx), 0x20))), PRIME) let proofPtr := mload(channelPtr) for { let index := cosetIdx } lt(index, nextCosetIdx) { index := add(index, 1) } { // Inline channel operation: // Assume we are going to read the next element from the proof. // If this is not the case add(proofPtr, 0x20) will be reverted. let fieldElementPtr := proofPtr proofPtr := add(proofPtr, 0x20) // Load the next index from the queue and check if it is our sibling. if eq(index, queueItemIdx) { // Take element from the queue rather than from the proof // and convert it back to Montgomery form for Merkle verification. fieldElementPtr := add(friQueueHead, 0x20) // Revert the read from proof. proofPtr := sub(proofPtr, 0x20) // Reading the next index here is safe due to the // delimiter after the queries. friQueueHead := add(friQueueHead, 0x60) queueItemIdx := mload(friQueueHead) } // Note that we apply the modulo operation to convert the field elements we read // from the proof to canonical representation (in the range [0, PRIME - 1]). mstore(evaluationsOnCosetPtr, mod(mload(fieldElementPtr), PRIME)) evaluationsOnCosetPtr := add(evaluationsOnCosetPtr, 0x20) } mstore(channelPtr, proofPtr) } } /* Returns the bit reversal of num assuming it has the given number of bits. For example, if we have numberOfBits = 6 and num = (0b)1101 == (0b)001101, the function will return (0b)101100. */ function bitReverse(uint256 num, uint256 numberOfBits) internal pure returns(uint256 numReversed) { assert((numberOfBits == 256) || (num < 2 ** numberOfBits)); uint256 n = num; uint256 r = 0; for (uint256 k = 0; k < numberOfBits; k++) { r = (r * 2) | (n % 2); n = n / 2; } return r; } /* Initializes the FRI group and half inv group in the FRI context. */ function initFriGroups(uint256 friCtx) internal { uint256 friGroupPtr = friCtx + FRI_CTX_TO_FRI_GROUP_OFFSET; uint256 friHalfInvGroupPtr = friCtx + FRI_CTX_TO_FRI_HALF_INV_GROUP_OFFSET; // FRI_GROUP_GEN is the coset generator. // Raising it to the (MAX_COSET_SIZE - 1) power gives us the inverse. uint256 genFriGroup = FRI_GROUP_GEN; uint256 genFriGroupInv = fpow(genFriGroup, (MAX_COSET_SIZE - 1)); uint256 lastVal = ONE_VAL; uint256 lastValInv = ONE_VAL; uint256 prime = PrimeFieldElement6.K_MODULUS; assembly { // ctx[mmHalfFriInvGroup + 0] = ONE_VAL; mstore(friHalfInvGroupPtr, lastValInv) // ctx[mmFriGroup + 0] = ONE_VAL; mstore(friGroupPtr, lastVal) // ctx[mmFriGroup + 1] = fsub(0, ONE_VAL); mstore(add(friGroupPtr, 0x20), sub(prime, lastVal)) } // To compute [1, -1 (== g^n/2), g^n/4, -g^n/4, ...] // we compute half the elements and derive the rest using negation. uint256 halfCosetSize = MAX_COSET_SIZE / 2; for (uint256 i = 1; i < halfCosetSize; i++) { lastVal = fmul(lastVal, genFriGroup); lastValInv = fmul(lastValInv, genFriGroupInv); uint256 idx = bitReverse(i, FRI_MAX_FRI_STEP-1); assembly { // ctx[mmHalfFriInvGroup + idx] = lastValInv; mstore(add(friHalfInvGroupPtr, mul(idx, 0x20)), lastValInv) // ctx[mmFriGroup + 2*idx] = lastVal; mstore(add(friGroupPtr, mul(idx, 0x40)), lastVal) // ctx[mmFriGroup + 2*idx + 1] = fsub(0, lastVal); mstore(add(friGroupPtr, add(mul(idx, 0x40), 0x20)), sub(prime, lastVal)) } } } /* Operates on the coset of size friFoldedCosetSize that start at index. It produces 3 outputs: 1. The field elements that result from doing FRI reductions on the coset. 2. The pointInv elements for the location that corresponds to the first output. 3. The root of a Merkle tree for the input layer. The input is read either from the queue or from the proof depending on data availability. Since the function reads from the queue it returns an updated head pointer. */ function doFriSteps( uint256 friCtx, uint256 friQueueTail, uint256 cosetOffset_, uint256 friEvalPoint, uint256 friCosetSize, uint256 index, uint256 merkleQueuePtr) internal pure { uint256 friValue; uint256 evaluationsOnCosetPtr = friCtx + FRI_CTX_TO_COSET_EVALUATIONS_OFFSET; uint256 friHalfInvGroupPtr = friCtx + FRI_CTX_TO_FRI_HALF_INV_GROUP_OFFSET; // Compare to expected FRI step sizes in order of likelihood, step size 3 being most common. if (friCosetSize == 8) { (friValue, cosetOffset_) = do3FriSteps( friHalfInvGroupPtr, evaluationsOnCosetPtr, cosetOffset_, friEvalPoint); } else if (friCosetSize == 4) { (friValue, cosetOffset_) = do2FriSteps( friHalfInvGroupPtr, evaluationsOnCosetPtr, cosetOffset_, friEvalPoint); } else if (friCosetSize == 16) { (friValue, cosetOffset_) = do4FriSteps( friHalfInvGroupPtr, evaluationsOnCosetPtr, cosetOffset_, friEvalPoint); } else { require(false, "Only step sizes of 2, 3 or 4 are supported."); } uint256 lhashMask = getHashMask(); assembly { let indexInNextStep := div(index, friCosetSize) mstore(merkleQueuePtr, indexInNextStep) mstore(add(merkleQueuePtr, 0x20), and(lhashMask, keccak256(evaluationsOnCosetPtr, mul(0x20,friCosetSize)))) mstore(friQueueTail, indexInNextStep) mstore(add(friQueueTail, 0x20), friValue) mstore(add(friQueueTail, 0x40), cosetOffset_) } } /* Computes the FRI step with eta = log2(friCosetSize) for all the live queries. The input and output data is given in array of triplets: (query index, FRI value, FRI inversed point) in the address friQueuePtr (which is &ctx[mmFriQueue:]). The function returns the number of live queries remaining after computing the FRI step. The number of live queries decreases whenever multiple query points in the same coset are reduced to a single query in the next FRI layer. As the function computes the next layer it also collects that data from the previous layer for Merkle verification. */ function computeNextLayer( uint256 channelPtr, uint256 friQueuePtr, uint256 merkleQueuePtr, uint256 nQueries, uint256 friEvalPoint, uint256 friCosetSize, uint256 friCtx) internal pure returns (uint256 nLiveQueries) { uint256 merkleQueueTail = merkleQueuePtr; uint256 friQueueHead = friQueuePtr; uint256 friQueueTail = friQueuePtr; uint256 friQueueEnd = friQueueHead + (0x60 * nQueries); do { uint256 cosetOffset; uint256 index; (friQueueHead, index, cosetOffset) = gatherCosetInputs( channelPtr, friCtx, friQueueHead, friCosetSize); doFriSteps( friCtx, friQueueTail, cosetOffset, friEvalPoint, friCosetSize, index, merkleQueueTail); merkleQueueTail += 0x40; friQueueTail += 0x60; } while (friQueueHead < friQueueEnd); return (friQueueTail - friQueuePtr) / 0x60; } } contract HornerEvaluator is PrimeFieldElement6 { /* Computes the evaluation of a polynomial f(x) = sum(a_i * x^i) on the given point. The coefficients of the polynomial are given in a_0 = coefsStart[0], ..., a_{n-1} = coefsStart[n - 1] where n = nCoefs = friLastLayerDegBound. Note that coefsStart is not actually an array but a direct pointer. The function requires that n is divisible by 8. */ function hornerEval(uint256 coefsStart, uint256 point, uint256 nCoefs) internal pure returns (uint256) { uint256 result = 0; uint256 prime = PrimeFieldElement6.K_MODULUS; require(nCoefs % 8 == 0, "Number of polynomial coefficients must be divisible by 8"); require(nCoefs < 4096, "No more than 4096 coefficients are supported"); assembly { let coefsPtr := add(coefsStart, mul(nCoefs, 0x20)) for { } gt(coefsPtr, coefsStart) { } { // Reduce coefsPtr by 8 field elements. coefsPtr := sub(coefsPtr, 0x100) // Apply 4 Horner steps (result := result * point + coef). result := add(mload(add(coefsPtr, 0x80)), mulmod( add(mload(add(coefsPtr, 0xa0)), mulmod( add(mload(add(coefsPtr, 0xc0)), mulmod( add(mload(add(coefsPtr, 0xe0)), mulmod( result, point, prime)), point, prime)), point, prime)), point, prime)) // Apply 4 additional Horner steps. result := add(mload(coefsPtr), mulmod( add(mload(add(coefsPtr, 0x20)), mulmod( add(mload(add(coefsPtr, 0x40)), mulmod( add(mload(add(coefsPtr, 0x60)), mulmod( result, point, prime)), point, prime)), point, prime)), point, prime)) } } // Since the last operation was "add" (instead of "addmod"), we need to take result % prime. return result % prime; } } contract MemoryAccessUtils is MemoryMap { function getPtr(uint256[] memory ctx, uint256 offset) internal pure returns (uint256) { uint256 ctxPtr; require(offset < MM_CONTEXT_SIZE, "Overflow protection failed"); assembly { ctxPtr := add(ctx, 0x20) } return ctxPtr + offset * 0x20; } function getProofPtr(uint256[] memory proof) internal pure returns (uint256) { uint256 proofPtr; assembly { proofPtr := proof } return proofPtr; } function getChannelPtr(uint256[] memory ctx) internal pure returns (uint256) { uint256 ctxPtr; assembly { ctxPtr := add(ctx, 0x20) } return ctxPtr + MM_CHANNEL * 0x20; } function getQueries(uint256[] memory ctx) internal pure returns (uint256[] memory) { uint256[] memory queries; // Dynamic array holds length followed by values. uint256 offset = 0x20 + 0x20*MM_N_UNIQUE_QUERIES; assembly { queries := add(ctx, offset) } return queries; } function getMerkleQueuePtr(uint256[] memory ctx) internal pure returns (uint256) { return getPtr(ctx, MM_MERKLE_QUEUE); } function getFriSteps(uint256[] memory ctx) internal pure returns (uint256[] memory friSteps) { uint256 friStepsPtr = getPtr(ctx, MM_FRI_STEPS_PTR); assembly { friSteps := mload(friStepsPtr) } } } contract MimcOods is MemoryMap, StarkParameters { // For each query point we want to invert (2 + N_ROWS_IN_MASK) items: // The query point itself (x). // The denominator for the constraint polynomial (x-z^constraintDegree) // [(x-(g^rowNumber)z) for rowNumber in mask]. uint256 constant internal BATCH_INVERSE_CHUNK = (2 + N_ROWS_IN_MASK); uint256 constant internal BATCH_INVERSE_SIZE = MAX_N_QUERIES * BATCH_INVERSE_CHUNK; /* Builds and sums boundary constraints that check that the prover provided the proper evaluations out of domain evaluations for the trace and composition columns. The inputs to this function are: The verifier context. The boundary constraints for the trace enforce claims of the form f(g^k*z) = c by requiring the quotient (f(x) - c)/(x-g^k*z) to be a low degree polynomial. The boundary constraints for the composition enforce claims of the form h(z^d) = c by requiring the quotient (h(x) - c)/(x-z^d) to be a low degree polynomial. Where: f is a trace column. h is a composition column. z is the out of domain sampling point. g is the trace generator k is the offset in the mask. d is the degree of the composition polynomial. c is the evaluation sent by the prover. */ function() external { // This funciton assumes that the calldata contains the context as defined in MemoryMap.sol. // Note that ctx is a variable size array so the first uint256 cell contrains it's length. uint256[] memory ctx; assembly { let ctxSize := mul(add(calldataload(0), 1), 0x20) ctx := mload(0x40) mstore(0x40, add(ctx, ctxSize)) calldatacopy(ctx, 0, ctxSize) } uint256[] memory batchInverseArray = new uint256[](2 * BATCH_INVERSE_SIZE); oodsPrepareInverses(ctx, batchInverseArray); uint256 kMontgomeryRInv_ = PrimeFieldElement6.K_MONTGOMERY_R_INV; assembly { let PRIME := 0x30000003000000010000000000000001 let kMontgomeryRInv := kMontgomeryRInv_ let context := ctx let friQueue := /*friQueue*/ add(context, 0xda0) let friQueueEnd := add(friQueue, mul(/*n_unique_queries*/ mload(add(context, 0x120)), 0x60)) let traceQueryResponses := /*traceQueryQesponses*/ add(context, 0x3d80) let compositionQueryResponses := /*composition_query_responses*/ add(context, 0xb580) // Set denominatorsPtr to point to the batchInverseOut array. // The content of batchInverseOut is described in oodsPrepareInverses. let denominatorsPtr := add(batchInverseArray, 0x20) for {} lt(friQueue, friQueueEnd) {friQueue := add(friQueue, 0x60)} { // res accumulates numbers modulo PRIME. Since 1814839283484201961915354863390654471405*PRIME < 2**256, we may add up to // 1814839283484201961915354863390654471405 numbers without fear of overflow, and use addmod modulo PRIME only every // 1814839283484201961915354863390654471405 iterations, and once more at the very end. let res := 0 // Trace constraints. // Mask items for column #0. { // Read the next element. let columnValue := mulmod(mload(traceQueryResponses), kMontgomeryRInv, PRIME) // res += c_0*(f_0(x) - f_0(z)) / (x - z). res := add( res, mulmod(mulmod(/*(x - z)^(-1)*/ mload(denominatorsPtr), /*oods_coefficients[0]*/ mload(add(context, 0x3a80)), PRIME), add(columnValue, sub(PRIME, /*oods_values[0]*/ mload(add(context, 0x3180)))), PRIME)) // res += c_1*(f_0(x) - f_0(g * z)) / (x - g * z). res := add( res, mulmod(mulmod(/*(x - g * z)^(-1)*/ mload(add(denominatorsPtr, 0x20)), /*oods_coefficients[1]*/ mload(add(context, 0x3aa0)), PRIME), add(columnValue, sub(PRIME, /*oods_values[1]*/ mload(add(context, 0x31a0)))), PRIME)) } // Mask items for column #1. { // Read the next element. let columnValue := mulmod(mload(add(traceQueryResponses, 0x20)), kMontgomeryRInv, PRIME) // res += c_2*(f_1(x) - f_1(z)) / (x - z). res := add( res, mulmod(mulmod(/*(x - z)^(-1)*/ mload(denominatorsPtr), /*oods_coefficients[2]*/ mload(add(context, 0x3ac0)), PRIME), add(columnValue, sub(PRIME, /*oods_values[2]*/ mload(add(context, 0x31c0)))), PRIME)) } // Mask items for column #2. { // Read the next element. let columnValue := mulmod(mload(add(traceQueryResponses, 0x40)), kMontgomeryRInv, PRIME) // res += c_3*(f_2(x) - f_2(z)) / (x - z). res := add( res, mulmod(mulmod(/*(x - z)^(-1)*/ mload(denominatorsPtr), /*oods_coefficients[3]*/ mload(add(context, 0x3ae0)), PRIME), add(columnValue, sub(PRIME, /*oods_values[3]*/ mload(add(context, 0x31e0)))), PRIME)) } // Mask items for column #3. { // Read the next element. let columnValue := mulmod(mload(add(traceQueryResponses, 0x60)), kMontgomeryRInv, PRIME) // res += c_4*(f_3(x) - f_3(z)) / (x - z). res := add( res, mulmod(mulmod(/*(x - z)^(-1)*/ mload(denominatorsPtr), /*oods_coefficients[4]*/ mload(add(context, 0x3b00)), PRIME), add(columnValue, sub(PRIME, /*oods_values[4]*/ mload(add(context, 0x3200)))), PRIME)) } // Mask items for column #4. { // Read the next element. let columnValue := mulmod(mload(add(traceQueryResponses, 0x80)), kMontgomeryRInv, PRIME) // res += c_5*(f_4(x) - f_4(z)) / (x - z). res := add( res, mulmod(mulmod(/*(x - z)^(-1)*/ mload(denominatorsPtr), /*oods_coefficients[5]*/ mload(add(context, 0x3b20)), PRIME), add(columnValue, sub(PRIME, /*oods_values[5]*/ mload(add(context, 0x3220)))), PRIME)) } // Mask items for column #5. { // Read the next element. let columnValue := mulmod(mload(add(traceQueryResponses, 0xa0)), kMontgomeryRInv, PRIME) // res += c_6*(f_5(x) - f_5(z)) / (x - z). res := add( res, mulmod(mulmod(/*(x - z)^(-1)*/ mload(denominatorsPtr), /*oods_coefficients[6]*/ mload(add(context, 0x3b40)), PRIME), add(columnValue, sub(PRIME, /*oods_values[6]*/ mload(add(context, 0x3240)))), PRIME)) } // Mask items for column #6. { // Read the next element. let columnValue := mulmod(mload(add(traceQueryResponses, 0xc0)), kMontgomeryRInv, PRIME) // res += c_7*(f_6(x) - f_6(z)) / (x - z). res := add( res, mulmod(mulmod(/*(x - z)^(-1)*/ mload(denominatorsPtr), /*oods_coefficients[7]*/ mload(add(context, 0x3b60)), PRIME), add(columnValue, sub(PRIME, /*oods_values[7]*/ mload(add(context, 0x3260)))), PRIME)) } // Mask items for column #7. { // Read the next element. let columnValue := mulmod(mload(add(traceQueryResponses, 0xe0)), kMontgomeryRInv, PRIME) // res += c_8*(f_7(x) - f_7(z)) / (x - z). res := add( res, mulmod(mulmod(/*(x - z)^(-1)*/ mload(denominatorsPtr), /*oods_coefficients[8]*/ mload(add(context, 0x3b80)), PRIME), add(columnValue, sub(PRIME, /*oods_values[8]*/ mload(add(context, 0x3280)))), PRIME)) } // Mask items for column #8. { // Read the next element. let columnValue := mulmod(mload(add(traceQueryResponses, 0x100)), kMontgomeryRInv, PRIME) // res += c_9*(f_8(x) - f_8(z)) / (x - z). res := add( res, mulmod(mulmod(/*(x - z)^(-1)*/ mload(denominatorsPtr), /*oods_coefficients[9]*/ mload(add(context, 0x3ba0)), PRIME), add(columnValue, sub(PRIME, /*oods_values[9]*/ mload(add(context, 0x32a0)))), PRIME)) } // Mask items for column #9. { // Read the next element. let columnValue := mulmod(mload(add(traceQueryResponses, 0x120)), kMontgomeryRInv, PRIME) // res += c_10*(f_9(x) - f_9(z)) / (x - z). res := add( res, mulmod(mulmod(/*(x - z)^(-1)*/ mload(denominatorsPtr), /*oods_coefficients[10]*/ mload(add(context, 0x3bc0)), PRIME), add(columnValue, sub(PRIME, /*oods_values[10]*/ mload(add(context, 0x32c0)))), PRIME)) } // Mask items for column #10. { // Read the next element. let columnValue := mulmod(mload(add(traceQueryResponses, 0x140)), kMontgomeryRInv, PRIME) // res += c_11*(f_10(x) - f_10(z)) / (x - z). res := add( res, mulmod(mulmod(/*(x - z)^(-1)*/ mload(denominatorsPtr), /*oods_coefficients[11]*/ mload(add(context, 0x3be0)), PRIME), add(columnValue, sub(PRIME, /*oods_values[11]*/ mload(add(context, 0x32e0)))), PRIME)) // res += c_12*(f_10(x) - f_10(g * z)) / (x - g * z). res := add( res, mulmod(mulmod(/*(x - g * z)^(-1)*/ mload(add(denominatorsPtr, 0x20)), /*oods_coefficients[12]*/ mload(add(context, 0x3c00)), PRIME), add(columnValue, sub(PRIME, /*oods_values[12]*/ mload(add(context, 0x3300)))), PRIME)) } // Mask items for column #11. { // Read the next element. let columnValue := mulmod(mload(add(traceQueryResponses, 0x160)), kMontgomeryRInv, PRIME) // res += c_13*(f_11(x) - f_11(z)) / (x - z). res := add( res, mulmod(mulmod(/*(x - z)^(-1)*/ mload(denominatorsPtr), /*oods_coefficients[13]*/ mload(add(context, 0x3c20)), PRIME), add(columnValue, sub(PRIME, /*oods_values[13]*/ mload(add(context, 0x3320)))), PRIME)) } // Mask items for column #12. { // Read the next element. let columnValue := mulmod(mload(add(traceQueryResponses, 0x180)), kMontgomeryRInv, PRIME) // res += c_14*(f_12(x) - f_12(z)) / (x - z). res := add( res, mulmod(mulmod(/*(x - z)^(-1)*/ mload(denominatorsPtr), /*oods_coefficients[14]*/ mload(add(context, 0x3c40)), PRIME), add(columnValue, sub(PRIME, /*oods_values[14]*/ mload(add(context, 0x3340)))), PRIME)) } // Mask items for column #13. { // Read the next element. let columnValue := mulmod(mload(add(traceQueryResponses, 0x1a0)), kMontgomeryRInv, PRIME) // res += c_15*(f_13(x) - f_13(z)) / (x - z). res := add( res, mulmod(mulmod(/*(x - z)^(-1)*/ mload(denominatorsPtr), /*oods_coefficients[15]*/ mload(add(context, 0x3c60)), PRIME), add(columnValue, sub(PRIME, /*oods_values[15]*/ mload(add(context, 0x3360)))), PRIME)) } // Mask items for column #14. { // Read the next element. let columnValue := mulmod(mload(add(traceQueryResponses, 0x1c0)), kMontgomeryRInv, PRIME) // res += c_16*(f_14(x) - f_14(z)) / (x - z). res := add( res, mulmod(mulmod(/*(x - z)^(-1)*/ mload(denominatorsPtr), /*oods_coefficients[16]*/ mload(add(context, 0x3c80)), PRIME), add(columnValue, sub(PRIME, /*oods_values[16]*/ mload(add(context, 0x3380)))), PRIME)) } // Mask items for column #15. { // Read the next element. let columnValue := mulmod(mload(add(traceQueryResponses, 0x1e0)), kMontgomeryRInv, PRIME) // res += c_17*(f_15(x) - f_15(z)) / (x - z). res := add( res, mulmod(mulmod(/*(x - z)^(-1)*/ mload(denominatorsPtr), /*oods_coefficients[17]*/ mload(add(context, 0x3ca0)), PRIME), add(columnValue, sub(PRIME, /*oods_values[17]*/ mload(add(context, 0x33a0)))), PRIME)) } // Mask items for column #16. { // Read the next element. let columnValue := mulmod(mload(add(traceQueryResponses, 0x200)), kMontgomeryRInv, PRIME) // res += c_18*(f_16(x) - f_16(z)) / (x - z). res := add( res, mulmod(mulmod(/*(x - z)^(-1)*/ mload(denominatorsPtr), /*oods_coefficients[18]*/ mload(add(context, 0x3cc0)), PRIME), add(columnValue, sub(PRIME, /*oods_values[18]*/ mload(add(context, 0x33c0)))), PRIME)) } // Mask items for column #17. { // Read the next element. let columnValue := mulmod(mload(add(traceQueryResponses, 0x220)), kMontgomeryRInv, PRIME) // res += c_19*(f_17(x) - f_17(z)) / (x - z). res := add( res, mulmod(mulmod(/*(x - z)^(-1)*/ mload(denominatorsPtr), /*oods_coefficients[19]*/ mload(add(context, 0x3ce0)), PRIME), add(columnValue, sub(PRIME, /*oods_values[19]*/ mload(add(context, 0x33e0)))), PRIME)) } // Mask items for column #18. { // Read the next element. let columnValue := mulmod(mload(add(traceQueryResponses, 0x240)), kMontgomeryRInv, PRIME) // res += c_20*(f_18(x) - f_18(z)) / (x - z). res := add( res, mulmod(mulmod(/*(x - z)^(-1)*/ mload(denominatorsPtr), /*oods_coefficients[20]*/ mload(add(context, 0x3d00)), PRIME), add(columnValue, sub(PRIME, /*oods_values[20]*/ mload(add(context, 0x3400)))), PRIME)) } // Mask items for column #19. { // Read the next element. let columnValue := mulmod(mload(add(traceQueryResponses, 0x260)), kMontgomeryRInv, PRIME) // res += c_21*(f_19(x) - f_19(z)) / (x - z). res := add( res, mulmod(mulmod(/*(x - z)^(-1)*/ mload(denominatorsPtr), /*oods_coefficients[21]*/ mload(add(context, 0x3d20)), PRIME), add(columnValue, sub(PRIME, /*oods_values[21]*/ mload(add(context, 0x3420)))), PRIME)) } // Advance traceQueryResponses by amount read (0x20 * nTraceColumns). traceQueryResponses := add(traceQueryResponses, 0x280) // Composition constraints. { // Read the next element. let columnValue := mulmod(mload(compositionQueryResponses), kMontgomeryRInv, PRIME) // res += c_22*(h_0(x) - C_0(z^2)) / (x - z^2). res := add( res, mulmod(mulmod(/*(x - z^2)^(-1)*/ mload(add(denominatorsPtr, 0x40)), /*oods_coefficients[22]*/ mload(add(context, 0x3d40)), PRIME), add(columnValue, sub(PRIME, /*composition_oods_values[0]*/ mload(add(context, 0x3440)))), PRIME)) } { // Read the next element. let columnValue := mulmod(mload(add(compositionQueryResponses, 0x20)), kMontgomeryRInv, PRIME) // res += c_23*(h_1(x) - C_1(z^2)) / (x - z^2). res := add( res, mulmod(mulmod(/*(x - z^2)^(-1)*/ mload(add(denominatorsPtr, 0x40)), /*oods_coefficients[23]*/ mload(add(context, 0x3d60)), PRIME), add(columnValue, sub(PRIME, /*composition_oods_values[1]*/ mload(add(context, 0x3460)))), PRIME)) } // Advance compositionQueryResponses by amount read (0x20 * constraintDegree). compositionQueryResponses := add(compositionQueryResponses, 0x40) // Append the friValue, which is the sum of the out-of-domain-sampling boundary // constraints for the trace and composition polynomials, to the friQueue array. mstore(add(friQueue, 0x20), mod(res, PRIME)) // Append the friInvPoint of the current query to the friQueue array. mstore(add(friQueue, 0x40), /*friInvPoint*/ mload(add(denominatorsPtr,0x60))) // Advance denominatorsPtr by chunk size (0x20 * (2+N_ROWS_IN_MASK)). denominatorsPtr := add(denominatorsPtr, 0x80) } return(/*friQueue*/ add(context, 0xda0), 0x1200) } } /* Computes and performs batch inverse on all the denominators required for the out of domain sampling boundary constraints. Since the friEvalPoints are calculated during the computation of the denominators this function also adds those to the batch inverse in prepartion for the fri that follows. After this function returns, the batch_inverse_out array holds #queries chunks of size (2 + N_ROWS_IN_MASK) with the following structure: 0..(N_ROWS_IN_MASK-1): [(x - g^i * z)^(-1) for i in rowsInMask] N_ROWS_IN_MASK: (x - z^constraintDegree)^-1 N_ROWS_IN_MASK+1: friEvalPointInv. */ function oodsPrepareInverses( uint256[] memory context, uint256[] memory batchInverseArray) internal view { uint256 evalCosetOffset_ = PrimeFieldElement6.GENERATOR_VAL; // The array expmodsAndPoints stores subexpressions that are needed // for the denominators computation. // The array is segmented as follows: // expmodsAndPoints[0:0] (.expmods) expmods used during calculations of the points below. // expmodsAndPoints[0:2] (.points) points used during the denominators calculation. uint256[2] memory expmodsAndPoints; assembly { function expmod(base, exponent, modulus) -> res { let p := mload(0x40) mstore(p, 0x20) // Length of Base. mstore(add(p, 0x20), 0x20) // Length of Exponent. mstore(add(p, 0x40), 0x20) // Length of Modulus. mstore(add(p, 0x60), base) // Base. mstore(add(p, 0x80), exponent) // Exponent. mstore(add(p, 0xa0), modulus) // Modulus. // Call modexp precompile. if iszero(staticcall(not(0), 0x05, p, 0xc0, p, 0x20)) { revert(0, 0) } res := mload(p) } let traceGenerator := /*trace_generator*/ mload(add(context, 0x2b40)) let PRIME := 0x30000003000000010000000000000001 // Prepare expmods for computations of trace generator powers. let oodsPoint := /*oods_point*/ mload(add(context, 0x2b60)) { // point = -z. let point := sub(PRIME, oodsPoint) // Compute denominators for rows with nonconst mask expression. // We compute those first because for the const rows we modify the point variable. // Compute denominators for rows with const mask expression. // expmods_and_points.points[0] = -z. mstore(add(expmodsAndPoints, 0x0), point) // point *= g. point := mulmod(point, traceGenerator, PRIME) // expmods_and_points.points[1] = -(g * z). mstore(add(expmodsAndPoints, 0x20), point) } let evalPointsPtr := /*oodsEvalPoints*/ add(context, 0x3480) let evalPointsEndPtr := add(evalPointsPtr, mul(/*n_unique_queries*/ mload(add(context, 0x120)), 0x20)) let productsPtr := add(batchInverseArray, 0x20) let valuesPtr := add(add(batchInverseArray, 0x20), 0x1800) let partialProduct := 1 let minusPointPow := sub(PRIME, mulmod(oodsPoint, oodsPoint, PRIME)) for {} lt(evalPointsPtr, evalPointsEndPtr) {evalPointsPtr := add(evalPointsPtr, 0x20)} { let evalPoint := mload(evalPointsPtr) // Shift evalPoint to evaluation domain coset. let shiftedEvalPoint := mulmod(evalPoint, evalCosetOffset_, PRIME) { // Calculate denominator for row 0: x - z. let denominator := add(shiftedEvalPoint, mload(add(expmodsAndPoints, 0x0))) mstore(productsPtr, partialProduct) mstore(valuesPtr, denominator) partialProduct := mulmod(partialProduct, denominator, PRIME) } { // Calculate denominator for row 1: x - g * z. let denominator := add(shiftedEvalPoint, mload(add(expmodsAndPoints, 0x20))) mstore(add(productsPtr, 0x20), partialProduct) mstore(add(valuesPtr, 0x20), denominator) partialProduct := mulmod(partialProduct, denominator, PRIME) } { // Calculate the denominator for the composition polynomial columns: x - z^2. let denominator := add(shiftedEvalPoint, minusPointPow) mstore(add(productsPtr, 0x40), partialProduct) mstore(add(valuesPtr, 0x40), denominator) partialProduct := mulmod(partialProduct, denominator, PRIME) } // Add evalPoint to batch inverse inputs. // inverse(evalPoint) is going to be used by FRI. mstore(add(productsPtr, 0x60), partialProduct) mstore(add(valuesPtr, 0x60), evalPoint) partialProduct := mulmod(partialProduct, evalPoint, PRIME) // Advance pointers. productsPtr := add(productsPtr, 0x80) valuesPtr := add(valuesPtr, 0x80) } let productsToValuesOffset := 0x1800 let firstPartialProductPtr := add(batchInverseArray, 0x20) // Compute the inverse of the product. let prodInv := expmod(partialProduct, sub(PRIME, 2), PRIME) if eq(prodInv, 0) { // Solidity generates reverts with reason that look as follows: // 1. 4 bytes with the constant 0x08c379a0 (== Keccak256(b'Error(string)')[:4]). // 2. 32 bytes offset bytes (always 0x20 as far as i can tell). // 3. 32 bytes with the length of the revert reason. // 4. Revert reason string. mstore(0, 0x08c379a000000000000000000000000000000000000000000000000000000000) mstore(0x4, 0x20) mstore(0x24, 0x1e) mstore(0x44, "Batch inverse product is zero.") revert(0, 0x62) } // Compute the inverses. // Loop over denominator_invs in reverse order. // currentPartialProductPtr is initialized to one past the end. let currentPartialProductPtr := productsPtr // Loop in blocks of size 8 as much as possible: we can loop over a full block as long as // currentPartialProductPtr >= firstPartialProductPtr + 8*0x20, or equivalently, // currentPartialProductPtr > firstPartialProductPtr + 7*0x20. // We use the latter comparison since there is no >= evm opcode. let midPartialProductPtr := add(firstPartialProductPtr, 0xe0) for { } gt(currentPartialProductPtr, midPartialProductPtr) { } { currentPartialProductPtr := sub(currentPartialProductPtr, 0x20) // Store 1/d_{i} = (d_0 * ... * d_{i-1}) * 1/(d_0 * ... * d_{i}). mstore(currentPartialProductPtr, mulmod(mload(currentPartialProductPtr), prodInv, PRIME)) // Update prodInv to be 1/(d_0 * ... * d_{i-1}) by multiplying by d_i. prodInv := mulmod(prodInv, mload(add(currentPartialProductPtr, productsToValuesOffset)), PRIME) currentPartialProductPtr := sub(currentPartialProductPtr, 0x20) // Store 1/d_{i} = (d_0 * ... * d_{i-1}) * 1/(d_0 * ... * d_{i}). mstore(currentPartialProductPtr, mulmod(mload(currentPartialProductPtr), prodInv, PRIME)) // Update prodInv to be 1/(d_0 * ... * d_{i-1}) by multiplying by d_i. prodInv := mulmod(prodInv, mload(add(currentPartialProductPtr, productsToValuesOffset)), PRIME) currentPartialProductPtr := sub(currentPartialProductPtr, 0x20) // Store 1/d_{i} = (d_0 * ... * d_{i-1}) * 1/(d_0 * ... * d_{i}). mstore(currentPartialProductPtr, mulmod(mload(currentPartialProductPtr), prodInv, PRIME)) // Update prodInv to be 1/(d_0 * ... * d_{i-1}) by multiplying by d_i. prodInv := mulmod(prodInv, mload(add(currentPartialProductPtr, productsToValuesOffset)), PRIME) currentPartialProductPtr := sub(currentPartialProductPtr, 0x20) // Store 1/d_{i} = (d_0 * ... * d_{i-1}) * 1/(d_0 * ... * d_{i}). mstore(currentPartialProductPtr, mulmod(mload(currentPartialProductPtr), prodInv, PRIME)) // Update prodInv to be 1/(d_0 * ... * d_{i-1}) by multiplying by d_i. prodInv := mulmod(prodInv, mload(add(currentPartialProductPtr, productsToValuesOffset)), PRIME) currentPartialProductPtr := sub(currentPartialProductPtr, 0x20) // Store 1/d_{i} = (d_0 * ... * d_{i-1}) * 1/(d_0 * ... * d_{i}). mstore(currentPartialProductPtr, mulmod(mload(currentPartialProductPtr), prodInv, PRIME)) // Update prodInv to be 1/(d_0 * ... * d_{i-1}) by multiplying by d_i. prodInv := mulmod(prodInv, mload(add(currentPartialProductPtr, productsToValuesOffset)), PRIME) currentPartialProductPtr := sub(currentPartialProductPtr, 0x20) // Store 1/d_{i} = (d_0 * ... * d_{i-1}) * 1/(d_0 * ... * d_{i}). mstore(currentPartialProductPtr, mulmod(mload(currentPartialProductPtr), prodInv, PRIME)) // Update prodInv to be 1/(d_0 * ... * d_{i-1}) by multiplying by d_i. prodInv := mulmod(prodInv, mload(add(currentPartialProductPtr, productsToValuesOffset)), PRIME) currentPartialProductPtr := sub(currentPartialProductPtr, 0x20) // Store 1/d_{i} = (d_0 * ... * d_{i-1}) * 1/(d_0 * ... * d_{i}). mstore(currentPartialProductPtr, mulmod(mload(currentPartialProductPtr), prodInv, PRIME)) // Update prodInv to be 1/(d_0 * ... * d_{i-1}) by multiplying by d_i. prodInv := mulmod(prodInv, mload(add(currentPartialProductPtr, productsToValuesOffset)), PRIME) currentPartialProductPtr := sub(currentPartialProductPtr, 0x20) // Store 1/d_{i} = (d_0 * ... * d_{i-1}) * 1/(d_0 * ... * d_{i}). mstore(currentPartialProductPtr, mulmod(mload(currentPartialProductPtr), prodInv, PRIME)) // Update prodInv to be 1/(d_0 * ... * d_{i-1}) by multiplying by d_i. prodInv := mulmod(prodInv, mload(add(currentPartialProductPtr, productsToValuesOffset)), PRIME) } // Loop over the remainder. for { } gt(currentPartialProductPtr, firstPartialProductPtr) { } { currentPartialProductPtr := sub(currentPartialProductPtr, 0x20) // Store 1/d_{i} = (d_0 * ... * d_{i-1}) * 1/(d_0 * ... * d_{i}). mstore(currentPartialProductPtr, mulmod(mload(currentPartialProductPtr), prodInv, PRIME)) // Update prodInv to be 1/(d_0 * ... * d_{i-1}) by multiplying by d_i. prodInv := mulmod(prodInv, mload(add(currentPartialProductPtr, productsToValuesOffset)), PRIME) } } } } contract Fri is MemoryMap, MemoryAccessUtils, HornerEvaluator, FriLayer { event LogGas(string name, uint256 val); function verifyLastLayer(uint256[] memory ctx, uint256 nPoints) internal { uint256 friLastLayerDegBound = ctx[MM_FRI_LAST_LAYER_DEG_BOUND]; uint256 groupOrderMinusOne = friLastLayerDegBound * ctx[MM_BLOW_UP_FACTOR] - 1; uint256 coefsStart = ctx[MM_FRI_LAST_LAYER_PTR]; for (uint256 i = 0; i < nPoints; i++) { uint256 point = ctx[MM_FRI_QUEUE + 3*i + 2]; // Invert point using inverse(point) == fpow(point, ord(point) - 1). point = fpow(point, groupOrderMinusOne); require( hornerEval(coefsStart, point, friLastLayerDegBound) == ctx[MM_FRI_QUEUE + 3*i + 1], "Bad Last layer value."); } } /* Verifies FRI layers. Upon entry and every time we pass through the "if (index < layerSize)" condition, ctx[mmFriQueue:] holds an array of triplets (query index, FRI value, FRI inversed point), i.e. ctx[mmFriQueue::3] holds query indices. ctx[mmFriQueue + 1::3] holds the input for the next layer. ctx[mmFriQueue + 2::3] holds the inverses of the evaluation points: ctx[mmFriQueue + 3*i + 2] = inverse( fpow(layerGenerator, bitReverse(ctx[mmFriQueue + 3*i], logLayerSize)). */ function friVerifyLayers( uint256[] memory ctx) internal { uint256 friCtx = getPtr(ctx, MM_FRI_CTX); require( MAX_SUPPORTED_MAX_FRI_STEP == FRI_MAX_FRI_STEP, "Incosistent MAX_FRI_STEP between MemoryMap.sol and FriLayer.sol"); initFriGroups(friCtx); // emit LogGas("FRI offset precomputation", gasleft()); uint256 channelPtr = getChannelPtr(ctx); uint256 merkleQueuePtr = getMerkleQueuePtr(ctx); uint256 friStep = 1; uint256 nLiveQueries = ctx[MM_N_UNIQUE_QUERIES]; // Add 0 at the end of the queries array to avoid empty array check in readNextElment. ctx[MM_FRI_QUERIES_DELIMITER] = 0; // Rather than converting all the values from Montgomery to standard form, // we can just pretend that the values are in standard form but all // the committed polynomials are multiplied by MontgomeryR. // // The values in the proof are already multiplied by MontgomeryR, // but the inputs from the OODS oracle need to be fixed. for (uint256 i = 0; i < nLiveQueries; i++ ) { ctx[MM_FRI_QUEUE + 3*i + 1] = fmul(ctx[MM_FRI_QUEUE + 3*i + 1], K_MONTGOMERY_R); } uint256 friQueue = getPtr(ctx, MM_FRI_QUEUE); uint256[] memory friSteps = getFriSteps(ctx); uint256 nFriSteps = friSteps.length; while (friStep < nFriSteps) { uint256 friCosetSize = 2**friSteps[friStep]; nLiveQueries = computeNextLayer( channelPtr, friQueue, merkleQueuePtr, nLiveQueries, ctx[MM_FRI_EVAL_POINTS + friStep], friCosetSize, friCtx); // emit LogGas( // string(abi.encodePacked("FRI layer ", bytes1(uint8(48 + friStep)))), gasleft()); // Layer is done, verify the current layer and move to next layer. // ctx[mmMerkleQueue: merkleQueueIdx) holds the indices // and values of the merkle leaves that need verification. verify( channelPtr, merkleQueuePtr, bytes32(ctx[MM_FRI_COMMITMENTS + friStep - 1]), nLiveQueries); // emit LogGas( // string(abi.encodePacked("Merkle of FRI layer ", bytes1(uint8(48 + friStep)))), // gasleft()); friStep++; } verifyLastLayer(ctx, nLiveQueries); // emit LogGas("last FRI layer", gasleft()); } } contract StarkVerifier is MemoryMap, MemoryAccessUtils, VerifierChannel, IStarkVerifier, Fri { /* The work required to generate an invalid proof is 2^numSecurityBits. Typical values: 80-128. */ uint256 numSecurityBits; /* The secuirty of a proof is a composition of bits obtained by PoW and bits obtained by FRI queries. The verifier requires at least minProofOfWorkBits to be obtained by PoW. Typical values: 20-30. */ uint256 minProofOfWorkBits; constructor(uint256 numSecurityBits_, uint256 minProofOfWorkBits_) public { numSecurityBits = numSecurityBits_; minProofOfWorkBits = minProofOfWorkBits_; } /* To print LogDebug messages from assembly use code like the following: assembly { let val := 0x1234 mstore(0, val) // uint256 val // log to the LogDebug(uint256) topic log1(0, 0x20, 0x2feb477e5c8c82cfb95c787ed434e820b1a28fa84d68bbf5aba5367382f5581c) } Note that you can't use log in a contract that was called with staticcall (ContraintPoly, Oods,...) If logging is needed replace the staticcall to call and add a third argument of 0. */ event LogBool(bool val); event LogDebug(uint256 val); address oodsContractAddress; function airSpecificInit(uint256[] memory publicInput) internal returns (uint256[] memory ctx, uint256 logTraceLength); uint256 constant internal PROOF_PARAMS_N_QUERIES_OFFSET = 0; uint256 constant internal PROOF_PARAMS_LOG_BLOWUP_FACTOR_OFFSET = 1; uint256 constant internal PROOF_PARAMS_PROOF_OF_WORK_BITS_OFFSET = 2; uint256 constant internal PROOF_PARAMS_FRI_LAST_LAYER_DEG_BOUND_OFFSET = 3; uint256 constant internal PROOF_PARAMS_N_FRI_STEPS_OFFSET = 4; uint256 constant internal PROOF_PARAMS_FRI_STEPS_OFFSET = 5; function validateFriParams( uint256[] memory friSteps, uint256 logTraceLength, uint256 logFriLastLayerDegBound) internal pure { require (friSteps[0] == 0, "Only eta0 == 0 is currently supported"); uint256 expectedLogDegBound = logFriLastLayerDegBound; uint256 nFriSteps = friSteps.length; for (uint256 i = 1; i < nFriSteps; i++) { uint256 friStep = friSteps[i]; require(friStep > 0, "Only the first fri step can be 0"); require(friStep <= 4, "Max supported fri step is 4."); expectedLogDegBound += friStep; } // FRI starts with a polynomial of degree 'traceLength'. // After applying all the FRI steps we expect to get a polynomial of degree less // than friLastLayerDegBound. require ( expectedLogDegBound == logTraceLength, "Fri params do not match trace length"); } function initVerifierParams(uint256[] memory publicInput, uint256[] memory proofParams) internal returns (uint256[] memory ctx) { require (proofParams.length > PROOF_PARAMS_FRI_STEPS_OFFSET, "Invalid proofParams."); require ( proofParams.length == ( PROOF_PARAMS_FRI_STEPS_OFFSET + proofParams[PROOF_PARAMS_N_FRI_STEPS_OFFSET]), "Invalid proofParams."); uint256 logBlowupFactor = proofParams[PROOF_PARAMS_LOG_BLOWUP_FACTOR_OFFSET]; require (logBlowupFactor <= 16, "logBlowupFactor must be at most 16"); require (logBlowupFactor >= 1, "logBlowupFactor must be at least 1"); uint256 proofOfWorkBits = proofParams[PROOF_PARAMS_PROOF_OF_WORK_BITS_OFFSET]; require (proofOfWorkBits <= 50, "proofOfWorkBits must be at most 50"); require (proofOfWorkBits >= minProofOfWorkBits, "minimum proofOfWorkBits not satisfied"); require (proofOfWorkBits < numSecurityBits, "Proofs may not be purely based on PoW."); uint256 logFriLastLayerDegBound = ( proofParams[PROOF_PARAMS_FRI_LAST_LAYER_DEG_BOUND_OFFSET] ); require ( logFriLastLayerDegBound <= 10, "logFriLastLayerDegBound must be at most 10."); uint256 nFriSteps = proofParams[PROOF_PARAMS_N_FRI_STEPS_OFFSET]; require (nFriSteps <= 10, "Too many fri steps."); require (nFriSteps > 1, "Not enough fri steps."); uint256[] memory friSteps = new uint256[](nFriSteps); for (uint256 i = 0; i < nFriSteps; i++) { friSteps[i] = proofParams[PROOF_PARAMS_FRI_STEPS_OFFSET + i]; } uint256 logTraceLength; (ctx, logTraceLength) = airSpecificInit(publicInput); validateFriParams(friSteps, logTraceLength, logFriLastLayerDegBound); uint256 friStepsPtr = getPtr(ctx, MM_FRI_STEPS_PTR); assembly { mstore(friStepsPtr, friSteps) } ctx[MM_FRI_LAST_LAYER_DEG_BOUND] = 2**logFriLastLayerDegBound; ctx[MM_TRACE_LENGTH] = 2 ** logTraceLength; ctx[MM_BLOW_UP_FACTOR] = 2**logBlowupFactor; ctx[MM_PROOF_OF_WORK_BITS] = proofOfWorkBits; uint256 nQueries = proofParams[PROOF_PARAMS_N_QUERIES_OFFSET]; require (nQueries > 0, "Number of queries must be at least one"); require (nQueries <= MAX_N_QUERIES, "Too many queries."); require ( nQueries * logBlowupFactor + proofOfWorkBits >= numSecurityBits, "Proof params do not satisfy security requirements."); ctx[MM_N_UNIQUE_QUERIES] = nQueries; // We start with log_evalDomainSize = logTraceSize and update it here. ctx[MM_LOG_EVAL_DOMAIN_SIZE] = logTraceLength + logBlowupFactor; ctx[MM_EVAL_DOMAIN_SIZE] = 2**ctx[MM_LOG_EVAL_DOMAIN_SIZE]; uint256 gen_evalDomain = fpow(GENERATOR_VAL, (K_MODULUS - 1) / ctx[MM_EVAL_DOMAIN_SIZE]); ctx[MM_EVAL_DOMAIN_GENERATOR] = gen_evalDomain; uint256 genTraceDomain = fpow(gen_evalDomain, ctx[MM_BLOW_UP_FACTOR]); ctx[MM_TRACE_GENERATOR] = genTraceDomain; } function getPublicInputHash(uint256[] memory publicInput) internal pure returns (bytes32); function oodsConsistencyCheck(uint256[] memory ctx) internal; function getNColumnsInTrace() internal pure returns(uint256); function getNColumnsInComposition() internal pure returns(uint256); function getMmCoefficients() internal pure returns(uint256); function getMmOodsValues() internal pure returns(uint256); function getMmOodsCoefficients() internal pure returns(uint256); function getNCoefficients() internal pure returns(uint256); function getNOodsValues() internal pure returns(uint256); function getNOodsCoefficients() internal pure returns(uint256); function hashRow(uint256[] memory ctx, uint256 offset, uint256 length) internal pure returns (uint256 res) { assembly { res := keccak256(add(add(ctx, 0x20), offset), length) } res &= getHashMask(); } /* Adjusts the query indices and generates evaluation points for each query index. The operations above are independent but we can save gas by combining them as both operations require us to iterate the queries array. Indices adjustment: The query indices adjustment is needed because both the Merkle verification and FRI expect queries "full binary tree in array" indices. The adjustment is simply adding evalDomainSize to each query. Note that evalDomainSize == 2^(#FRI layers) == 2^(Merkle tree hight). evalPoints generation: for each query index "idx" we compute the corresponding evaluation point: g^(bitReverse(idx, log_evalDomainSize). */ function adjustQueryIndicesAndPrepareEvalPoints(uint256[] memory ctx) internal { uint256 nUniqueQueries = ctx[MM_N_UNIQUE_QUERIES]; uint256 friQueue = getPtr(ctx, MM_FRI_QUEUE); uint256 friQueueEnd = friQueue + nUniqueQueries * 0x60; uint256 evalPointsPtr = getPtr(ctx, MM_OODS_EVAL_POINTS); uint256 log_evalDomainSize = ctx[MM_LOG_EVAL_DOMAIN_SIZE]; uint256 evalDomainSize = ctx[MM_EVAL_DOMAIN_SIZE]; uint256 evalDomainGenerator = ctx[MM_EVAL_DOMAIN_GENERATOR]; assembly { /* Returns the bit reversal of value assuming it has the given number of bits. numberOfBits must be <= 64. */ function bitReverse(value, numberOfBits) -> res { // Bit reverse value by swapping 1 bit chunks then 2 bit chunks and so forth. // Each swap is done by masking out and shifting one of the chunks by twice its size. // Finally, we use div to align the result to the right. res := value // Swap 1 bit chunks. res := or(mul(and(res, 0x5555555555555555), 0x4), and(res, 0xaaaaaaaaaaaaaaaa)) // Swap 2 bit chunks. res := or(mul(and(res, 0x6666666666666666), 0x10), and(res, 0x19999999999999998)) // Swap 4 bit chunks. res := or(mul(and(res, 0x7878787878787878), 0x100), and(res, 0x78787878787878780)) // Swap 8 bit chunks. res := or(mul(and(res, 0x7f807f807f807f80), 0x10000), and(res, 0x7f807f807f807f8000)) // Swap 16 bit chunks. res := or(mul(and(res, 0x7fff80007fff8000), 0x100000000), and(res, 0x7fff80007fff80000000)) // Swap 32 bit chunks. res := or(mul(and(res, 0x7fffffff80000000), 0x10000000000000000), and(res, 0x7fffffff8000000000000000)) // Right align the result. res := div(res, exp(2, sub(127, numberOfBits))) } function expmod(base, exponent, modulus) -> res { let p := mload(0x40) mstore(p, 0x20) // Length of Base. mstore(add(p, 0x20), 0x20) // Length of Exponent. mstore(add(p, 0x40), 0x20) // Length of Modulus. mstore(add(p, 0x60), base) // Base. mstore(add(p, 0x80), exponent) // Exponent. mstore(add(p, 0xa0), modulus) // Modulus. // Call modexp precompile. if iszero(call(not(0), 0x05, 0, p, 0xc0, p, 0x20)) { revert(0, 0) } res := mload(p) } let PRIME := 0x30000003000000010000000000000001 for {} lt(friQueue, friQueueEnd) {friQueue := add(friQueue, 0x60)} { let queryIdx := mload(friQueue) // Adjust queryIdx, see comment in function description. let adjustedQueryIdx := add(queryIdx, evalDomainSize) mstore(friQueue, adjustedQueryIdx) // Compute the evaluation point corresponding to the current queryIdx. mstore(evalPointsPtr, expmod(evalDomainGenerator, bitReverse(queryIdx, log_evalDomainSize), PRIME)) evalPointsPtr := add(evalPointsPtr, 0x20) } } } function readQueryResponsesAndDecommit( uint256[] memory ctx, uint256 nColumns, uint256 proofDataPtr, bytes32 merkleRoot) internal view { require(nColumns <= getNColumnsInTrace() + getNColumnsInComposition(), "Too many columns."); uint256 nUniqueQueries = ctx[MM_N_UNIQUE_QUERIES]; uint256 channelPtr = getPtr(ctx, MM_CHANNEL); uint256 friQueue = getPtr(ctx, MM_FRI_QUEUE); uint256 friQueueEnd = friQueue + nUniqueQueries * 0x60; uint256 merkleQueuePtr = getPtr(ctx, MM_MERKLE_QUEUE); uint256 rowSize = 0x20 * nColumns; uint256 lhashMask = getHashMask(); assembly { let proofPtr := mload(channelPtr) let merklePtr := merkleQueuePtr for {} lt(friQueue, friQueueEnd) {friQueue := add(friQueue, 0x60)} { let merkleLeaf := and(keccak256(proofPtr, rowSize), lhashMask) if eq(rowSize, 0x20) { // If a leaf contains only 1 field element we don't hash it. merkleLeaf := mload(proofPtr) } // push(queryIdx, hash(row)) to merkleQueue. mstore(merklePtr, mload(friQueue)) mstore(add(merklePtr, 0x20), merkleLeaf) merklePtr := add(merklePtr, 0x40) // Copy query responses to proofData array. // This array will be sent to the OODS contract. for {let proofDataChunk_end := add(proofPtr, rowSize)} lt(proofPtr, proofDataChunk_end) {proofPtr := add(proofPtr, 0x20)} { mstore(proofDataPtr, mload(proofPtr)) proofDataPtr := add(proofDataPtr, 0x20) } } mstore(channelPtr, proofPtr) } verify(channelPtr, merkleQueuePtr, merkleRoot, nUniqueQueries); } /* Computes the first FRI layer by reading the query responses and calling the OODS contract. The OODS contract will build and sum boundary constraints that check that the prover provided the proper evaluations for the Out of Domain Sampling. I.e. if the prover said that f(z) = c, the first FRI layer will include the term (f(x) - c)/(x-z). */ function computeFirstFriLayer(uint256[] memory ctx) internal { adjustQueryIndicesAndPrepareEvalPoints(ctx); // emit LogGas("Prepare evaluation points", gasleft()); readQueryResponsesAndDecommit( ctx, getNColumnsInTrace(), getPtr(ctx, MM_TRACE_QUERY_RESPONSES), bytes32(ctx[MM_TRACE_COMMITMENT])); // emit LogGas("Read and decommit trace", gasleft()); readQueryResponsesAndDecommit( ctx, getNColumnsInComposition(), getPtr(ctx, MM_COMPOSITION_QUERY_RESPONSES), bytes32(ctx[MM_OODS_COMMITMENT])); // emit LogGas("Read and decommit composition", gasleft()); address oodsAddress = oodsContractAddress; uint256 friQueue = getPtr(ctx, MM_FRI_QUEUE); uint256 returnDataSize = MAX_N_QUERIES * 0x60; assembly { // Call the OODS contract. if iszero(staticcall(not(0), oodsAddress, ctx, /*sizeof(ctx)*/ mul(add(mload(ctx), 1), 0x20), friQueue, returnDataSize)) { returndatacopy(0, 0, returndatasize) revert(0, returndatasize) } } // emit LogGas("OODS virtual oracle", gasleft()); } /* Reads the last FRI layer (i.e. the polynomial's coefficients) from the channel. This differs from standard reading of channel field elements in several ways: -- The digest is updated by hashing it once with all coefficients simultaneously, rather than iteratively one by one. -- The coefficients are kept in Montgomery form, as is the case throughout the FRI computation. -- The coefficients are not actually read and copied elsewhere, but rather only a pointer to their location in the channel is stored. */ function readLastFriLayer(uint256[] memory ctx) internal pure { uint256 lmmChannel = MM_CHANNEL; uint256 friLastLayerDegBound = ctx[MM_FRI_LAST_LAYER_DEG_BOUND]; uint256 lastLayerPtr; uint256 badInput = 0; assembly { let primeMinusOne := 0x30000003000000010000000000000000 let channelPtr := add(add(ctx, 0x20), mul(lmmChannel, 0x20)) lastLayerPtr := mload(channelPtr) // Make sure all the values are valid field elements. let length := mul(friLastLayerDegBound, 0x20) let lastLayerEnd := add(lastLayerPtr, length) for { let coefsPtr := lastLayerPtr } lt(coefsPtr, lastLayerEnd) { coefsPtr := add(coefsPtr, 0x20) } { badInput := or(badInput, gt(mload(coefsPtr), primeMinusOne)) } // Copy the digest to the proof area // (store it before the coefficients - this is done because // keccak256 needs all data to be consecutive), // then hash and place back in digestPtr. let newDigestPtr := sub(lastLayerPtr, 0x20) let digestPtr := add(channelPtr, 0x20) // Overwriting the proof to minimize copying of data. mstore(newDigestPtr, mload(digestPtr)) // prng.digest := keccak256(digest||lastLayerCoefs). mstore(digestPtr, keccak256(newDigestPtr, add(length, 0x20))) // prng.counter := 0. mstore(add(channelPtr, 0x40), 0) // Note: proof pointer is not incremented until this point. mstore(channelPtr, lastLayerEnd) } require(badInput == 0, "Invalid field element."); ctx[MM_FRI_LAST_LAYER_PTR] = lastLayerPtr; } function verifyProof( uint256[] memory proofParams, uint256[] memory proof, uint256[] memory publicInput) internal { // emit LogGas("Transmission", gasleft()); uint256[] memory ctx = initVerifierParams(publicInput, proofParams); uint256 channelPtr = getChannelPtr(ctx); initChannel(channelPtr, getProofPtr(proof), getPublicInputHash(publicInput)); // emit LogGas("Initializations", gasleft()); // Read trace commitment. ctx[MM_TRACE_COMMITMENT] = uint256(readHash(channelPtr, true)); VerifierChannel.sendFieldElements( channelPtr, getNCoefficients(), getPtr(ctx, getMmCoefficients())); // emit LogGas("Generate coefficients", gasleft()); ctx[MM_OODS_COMMITMENT] = uint256(readHash(channelPtr, true)); // Send Out of Domain Sampling point. VerifierChannel.sendFieldElements(channelPtr, 1, getPtr(ctx, MM_OODS_POINT)); // Read the answers to the Out of Domain Sampling. uint256 lmmOodsValues = getMmOodsValues(); for (uint256 i = lmmOodsValues; i < lmmOodsValues+getNOodsValues(); i++) { ctx[i] = VerifierChannel.readFieldElement(channelPtr, true); } // emit LogGas("Read OODS commitments", gasleft()); oodsConsistencyCheck(ctx); // emit LogGas("OODS consistency check", gasleft()); VerifierChannel.sendFieldElements( channelPtr, getNOodsCoefficients(), getPtr(ctx, getMmOodsCoefficients())); // emit LogGas("Generate OODS coefficients", gasleft()); ctx[MM_FRI_COMMITMENTS] = uint256(VerifierChannel.readHash(channelPtr, true)); uint256 nFriSteps = getFriSteps(ctx).length; uint256 fri_evalPointPtr = getPtr(ctx, MM_FRI_EVAL_POINTS); for (uint256 i = 1; i < nFriSteps - 1; i++) { VerifierChannel.sendFieldElements(channelPtr, 1, fri_evalPointPtr + i * 0x20); ctx[MM_FRI_COMMITMENTS + i] = uint256(VerifierChannel.readHash(channelPtr, true)); } // Send last random FRI evaluation point. VerifierChannel.sendFieldElements( channelPtr, 1, getPtr(ctx, MM_FRI_EVAL_POINTS + nFriSteps - 1)); // Read FRI last layer commitment. readLastFriLayer(ctx); // Generate queries. // emit LogGas("Read FRI commitments", gasleft()); VerifierChannel.verifyProofOfWork(channelPtr, ctx[MM_PROOF_OF_WORK_BITS]); ctx[MM_N_UNIQUE_QUERIES] = VerifierChannel.sendRandomQueries( channelPtr, ctx[MM_N_UNIQUE_QUERIES], ctx[MM_EVAL_DOMAIN_SIZE] - 1, getPtr(ctx, MM_FRI_QUEUE), 0x60); // emit LogGas("Send queries", gasleft()); computeFirstFriLayer(ctx); friVerifyLayers(ctx); } } contract MimcVerifier is StarkParameters, StarkVerifier, FactRegistry, PublicInputOffsets{ MimcConstraintPoly constraintPoly; PeriodicColumnContract[20] constantsCols; uint256 internal constant PUBLIC_INPUT_SIZE = 5; constructor( address[] memory auxPolynomials, MimcOods oodsContract, uint256 numSecurityBits_, uint256 minProofOfWorkBits_) StarkVerifier( numSecurityBits_, minProofOfWorkBits_ ) public { constraintPoly = MimcConstraintPoly(auxPolynomials[0]); for (uint256 i = 0; i < 20; i++) { constantsCols[i] = PeriodicColumnContract(auxPolynomials[i+1]); } oodsContractAddress = address(oodsContract); } function verifyProofAndRegister( uint256[] calldata proofParams, uint256[] calldata proof, uint256[] calldata publicInput ) external { verifyProof(proofParams, proof, publicInput); registerFact( keccak256( abi.encodePacked( 10 * 2**publicInput[OFFSET_LOG_TRACE_LENGTH] - 1, publicInput[OFFSET_VDF_OUTPUT_X], publicInput[OFFSET_VDF_OUTPUT_Y], publicInput[OFFSET_VDF_INPUT_X], publicInput[OFFSET_VDF_INPUT_Y] ) ) ); } function getNColumnsInTrace() internal pure returns (uint256) { return N_COLUMNS_IN_MASK; } function getNColumnsInComposition() internal pure returns (uint256) { return CONSTRAINTS_DEGREE_BOUND; } function getMmCoefficients() internal pure returns (uint256) { return MM_COEFFICIENTS; } function getMmOodsValues() internal pure returns (uint256) { return MM_OODS_VALUES; } function getMmOodsCoefficients() internal pure returns (uint256) { return MM_OODS_COEFFICIENTS; } function getNCoefficients() internal pure returns (uint256) { return N_COEFFICIENTS; } function getNOodsValues() internal pure returns (uint256) { return N_OODS_VALUES; } function getNOodsCoefficients() internal pure returns (uint256) { return N_OODS_COEFFICIENTS; } function airSpecificInit(uint256[] memory publicInput) internal returns (uint256[] memory ctx, uint256 logTraceLength) { require(publicInput.length == PUBLIC_INPUT_SIZE, "INVALID_PUBLIC_INPUT_LENGTH" ); ctx = new uint256[](MM_CONTEXT_SIZE); // Note that the prover does the VDF computation the other way around (uses the inverse // function), hence vdf_output is the input for its calculation, and vdf_input should be the // result of the calculation. ctx[MM_INPUT_VALUE_A] = publicInput[OFFSET_VDF_OUTPUT_X]; ctx[MM_INPUT_VALUE_B] = publicInput[OFFSET_VDF_OUTPUT_Y]; ctx[MM_OUTPUT_VALUE_A] = publicInput[OFFSET_VDF_INPUT_X]; ctx[MM_OUTPUT_VALUE_B] = publicInput[OFFSET_VDF_INPUT_Y]; // Initialize the MDS matrix values with fixed predefined values. ctx[MM_MAT00] = 0x109bbc181e07a285856e0d8bde02619; ctx[MM_MAT01] = 0x1eb8859b1b789cd8a80927a32fdf41f7; ctx[MM_MAT10] = 0xdc8eaac802c8f9cb9dff6ed0728012d; ctx[MM_MAT11] = 0x2c18506f35eab63b58143a34181c89e; logTraceLength = publicInput[OFFSET_LOG_TRACE_LENGTH]; require(logTraceLength <= 50, "logTraceLength must not exceed 50."); } function getPublicInputHash(uint256[] memory publicInput) internal pure returns (bytes32) { return keccak256( abi.encodePacked( uint64(2 ** publicInput[OFFSET_LOG_TRACE_LENGTH]), publicInput[OFFSET_VDF_OUTPUT_X], publicInput[OFFSET_VDF_OUTPUT_Y], publicInput[OFFSET_VDF_INPUT_X], publicInput[OFFSET_VDF_INPUT_Y]) ); } /* Checks that the trace and the composition agree on the Out of Domain Sampling point, assuming the prover provided us with the proper evaluations. Later, we use boundary constraints to check that those evaluations are actually consistent with the committed trace and composition polynomials. */ function oodsConsistencyCheck(uint256[] memory ctx) internal { uint256 oodsPoint = ctx[MM_OODS_POINT]; uint256 nRows = 256; uint256 zPointPow = fpow(oodsPoint, ctx[MM_TRACE_LENGTH] / nRows); ctx[MM_PERIODIC_COLUMN__CONSTS0_A] = constantsCols[0].compute(zPointPow); ctx[MM_PERIODIC_COLUMN__CONSTS1_A] = constantsCols[1].compute(zPointPow); ctx[MM_PERIODIC_COLUMN__CONSTS2_A] = constantsCols[2].compute(zPointPow); ctx[MM_PERIODIC_COLUMN__CONSTS3_A] = constantsCols[3].compute(zPointPow); ctx[MM_PERIODIC_COLUMN__CONSTS4_A] = constantsCols[4].compute(zPointPow); ctx[MM_PERIODIC_COLUMN__CONSTS5_A] = constantsCols[5].compute(zPointPow); ctx[MM_PERIODIC_COLUMN__CONSTS6_A] = constantsCols[6].compute(zPointPow); ctx[MM_PERIODIC_COLUMN__CONSTS7_A] = constantsCols[7].compute(zPointPow); ctx[MM_PERIODIC_COLUMN__CONSTS8_A] = constantsCols[8].compute(zPointPow); ctx[MM_PERIODIC_COLUMN__CONSTS9_A] = constantsCols[9].compute(zPointPow); ctx[MM_PERIODIC_COLUMN__CONSTS0_B] = constantsCols[10].compute(zPointPow); ctx[MM_PERIODIC_COLUMN__CONSTS1_B] = constantsCols[11].compute(zPointPow); ctx[MM_PERIODIC_COLUMN__CONSTS2_B] = constantsCols[12].compute(zPointPow); ctx[MM_PERIODIC_COLUMN__CONSTS3_B] = constantsCols[13].compute(zPointPow); ctx[MM_PERIODIC_COLUMN__CONSTS4_B] = constantsCols[14].compute(zPointPow); ctx[MM_PERIODIC_COLUMN__CONSTS5_B] = constantsCols[15].compute(zPointPow); ctx[MM_PERIODIC_COLUMN__CONSTS6_B] = constantsCols[16].compute(zPointPow); ctx[MM_PERIODIC_COLUMN__CONSTS7_B] = constantsCols[17].compute(zPointPow); ctx[MM_PERIODIC_COLUMN__CONSTS8_B] = constantsCols[18].compute(zPointPow); ctx[MM_PERIODIC_COLUMN__CONSTS9_B] = constantsCols[19].compute(zPointPow); uint256 compositionFromTraceValue; address lconstraintPoly = address(constraintPoly); uint256 offset = 0x20 * (1 + MM_CONSTRAINT_POLY_ARGS_START); uint256 size = 0x20 * (MM_CONSTRAINT_POLY_ARGS_END - MM_CONSTRAINT_POLY_ARGS_START); assembly { // Call MimcConstraintPoly contract. let p := mload(0x40) if iszero(staticcall(not(0), lconstraintPoly, add(ctx, offset), size, p, 0x20)) { returndatacopy(0, 0, returndatasize) revert(0, returndatasize) } compositionFromTraceValue := mload(p) } uint256 claimedComposition = fadd( ctx[MM_OODS_VALUES + MASK_SIZE], fmul(oodsPoint, ctx[MM_OODS_VALUES + MASK_SIZE + 1])); require( compositionFromTraceValue == claimedComposition, "claimedComposition does not match trace"); } }
Note that the prover does the VDF computation the other way around (uses the inverse function), hence vdf_output is the input for its calculation, and vdf_input should be the result of the calculation. Initialize the MDS matrix values with fixed predefined values.
function airSpecificInit(uint256[] memory publicInput) internal returns (uint256[] memory ctx, uint256 logTraceLength) { require(publicInput.length == PUBLIC_INPUT_SIZE, "INVALID_PUBLIC_INPUT_LENGTH" ); ctx = new uint256[](MM_CONTEXT_SIZE); ctx[MM_INPUT_VALUE_A] = publicInput[OFFSET_VDF_OUTPUT_X]; ctx[MM_INPUT_VALUE_B] = publicInput[OFFSET_VDF_OUTPUT_Y]; ctx[MM_OUTPUT_VALUE_A] = publicInput[OFFSET_VDF_INPUT_X]; ctx[MM_OUTPUT_VALUE_B] = publicInput[OFFSET_VDF_INPUT_Y]; ctx[MM_MAT00] = 0x109bbc181e07a285856e0d8bde02619; ctx[MM_MAT01] = 0x1eb8859b1b789cd8a80927a32fdf41f7; ctx[MM_MAT10] = 0xdc8eaac802c8f9cb9dff6ed0728012d; ctx[MM_MAT11] = 0x2c18506f35eab63b58143a34181c89e; logTraceLength = publicInput[OFFSET_LOG_TRACE_LENGTH]; require(logTraceLength <= 50, "logTraceLength must not exceed 50."); }
7,338,300
pragma solidity ^0.6.10; pragma experimental ABIEncoderV2; import "./OpenOraclePriceData.sol"; import "./Verifier.sol"; import "./Uniswap/UniswapLib.sol"; struct Observation { uint timestamp; uint acc; } contract OracleView { using FixedPoint for *; /// @notice The Open Oracle Price Data contract OpenOraclePriceData public immutable priceData; /// @notice The number of wei in 1 ETH uint public constant ethBaseUnit = 1e18; /// @notice A common scaling factor to maintain precision uint public constant expScale = 1e18; /// @notice The Open Oracle Reporter address public immutable reporter; /// @notice Official prices by symbol hash mapping(bytes32 => uint) public prices; /// @notice Circuit breaker for using anchor price oracle directly, ignoring reporter bool public reporterInvalidated; /// @notice The old observation for each symbolHash mapping(bytes32 => Observation) public oldObservations; /// @notice The new observation for each symbolHash mapping(bytes32 => Observation) public newObservations; /// @notice The event emitted when new prices are posted but the stored price is not updated due to the anchor event PriceGuarded(string symbol, uint reporter, uint anchor); /// @notice The event emitted when the stored price is updated event PriceUpdated(string symbol, uint price); /// @notice The event emitted when anchor price is updated event AnchorPriceUpdated(string symbol, uint anchorPrice, uint oldTimestamp, uint newTimestamp); /// @notice The event emitted when the uniswap window changes event UniswapWindowUpdated(bytes32 indexed symbolHash, uint oldTimestamp, uint newTimestamp, uint oldPrice, uint newPrice); /// @notice The event emitted when reporter invalidates itself event ReporterInvalidated(address reporter); bytes32 constant ethHash = keccak256(abi.encodePacked("ETH")); bytes32 constant rotateHash = keccak256(abi.encodePacked("rotate")); /** * @notice Construct a uniswap anchored view for a set of token configurations * @dev Note that to avoid immature TWAPs, the system must run for at least a single anchorPeriod before using. * @param reporter_ The reporter whose prices are to be used * @param priceData_ The address of the oracle data contract which is backing the view */ constructor(OpenOraclePriceData priceData_, address reporter_) public { priceData = priceData_; reporter = reporter_; } /** * @notice Post open oracle reporter prices, and recalculate stored price by comparing to anchor * @dev We let anyone pay to post anything, but only prices from configured reporter will be stored in the view. * @param messages The messages to post to the oracle * @param signatures The signatures for the corresponding messages */ function postPrices(bytes[] calldata messages, bytes[] calldata signatures, Proof[] calldata proofs, PublicInput[] calldata inputs) external { require(messages.length == signatures.length, "messages and signatures must be 1:1"); // Save the prices for (uint i = 0; i < messages.length; i++) { priceData.put(messages[i], signatures[i], proofs[i], inputs[i]); } } /** * @notice Use priceData.getCSRange() directly * @param source The verifiable author of the data * @param key The selector for the value to return (symbol in case of uniswap) * @return Price range denominated in USD, with 6 decimals */ function price(address source, string calldata key) external view returns (uint64, uint64) { uint64 min; uint64 max; (min, max) = priceData.getCSRange(source, key); return (min, max); } }
Use priceData.getCSRange() directly source The verifiable author of the data key The selector for the value to return (symbol in case of uniswap) return Price range denominated in USD, with 6 decimals/
function price(address source, string calldata key) external view returns (uint64, uint64) { uint64 min; uint64 max; (min, max) = priceData.getCSRange(source, key); return (min, max); }
12,810,455
./partial_match/1/0xc6e97C87A3782328c76cE788f24469D09d88669a/sources/ExchangerV3.sol
/Now do the trade if conditions are metAccounting - so we can pull the fees out without changing the balance
function buy(uint minPurchaseReturn) public payable { uint amount = formulaContract.calculatePurchaseReturn( (tokenContract.totalSupply() - uncirculatedSupplyCount) - tokenContract.balanceOf(this), (address(this).balance + virtualReserveBalance) - msg.value, weight, msg.value); amount = (amount - ((amount * fee) / 1000000)); require (amount >= minPurchaseReturn); require (tokenContract.balanceOf(this) >= amount); collectedFees += (msg.value * fee) / 1000000; emit Buy(msg.sender, msg.value, amount); tokenContract.transfer(msg.sender, amount); } @param quantity Number of tokens to sell @param minSaleReturn Minimum amount of ether (in wei) you will accept for your tokens
9,351,057
// SPDX-License-Identifier: MIT pragma solidity >= 0.8.7 < 0.9.0; //import "../utils/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 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; } } //import "@openzeppelin/contracts/access/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() { _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); } } //import "./IERC721Receiver.sol"; /** * @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); } //import "../../utils/introspection/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); } //import "./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; } //import "./extensions/IERC721Metadata.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); } //import "../../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) { // 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); } } } } //import "../../utils/Strings.sol"; /** * @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); } } // import "../../utils/introspection/ERC165.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; } } //import "@openzeppelin/contracts/token/ERC721/ERC721.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 {} } //import "./IPresaleInfo.sol"; //----------------------------------------------------------------------- // 事前販売情報:インターフェイス //----------------------------------------------------------------------- interface IPresaleInfo { //---------------------------------------- // 登録確認されているか? //---------------------------------------- function isRegistered( address user ) external view returns (bool); } //import "./LibString.sol"; library LibString { function toString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } } //------------------- // トークン //------------------- contract Token is Ownable, ERC721{ //---------------------------------------------- // Events //---------------------------------------------- event TokenStake( address indexed holder, uint256 indexed tokenId ); event TokenUnstake( address indexed holder, uint256 indexed tokenId ); //---------------------------------------------- // 定数 //---------------------------------------------- string constant private TOKEN_NAME = "Comical Girl"; string constant private TOKEN_SYMBOL = "CG"; uint256 constant private PUBLIC_SALE_MAX_SHOT = 7; uint256 constant private PRE_SALE_MAX_SHOT = 2; uint256 constant private PRE_SALE_LIMIT = 2; uint256 constant private ID_PHASE_GA = 0; uint256 constant private ID_PHASE_1ST = 1; uint256 constant private ID_PHASE_2ND = 2; uint256 constant private ID_PHASE_3RD = 3; uint256 constant private ID_PHASE_MAX = 4; //---------------------------------------------- // 管理データ //---------------------------------------------- // 売り上げを引き出せる人 address private _accountant; // 排出管理 uint256[ID_PHASE_MAX] private _arr_id_offset; uint256[ID_PHASE_MAX] private _arr_num_mintable; uint256[ID_PHASE_MAX] private _arr_num_minted; // metadata参照先 string[ID_PHASE_MAX] private _arr_base_url; mapping( uint256 => string ) private _repaired_urls; // 販売関連 uint256 private _sale_phase; uint256 private _sale_price; uint256 private _sale_start; uint256 private _sale_end; bool private _sale_suspended; uint256 private _presale_price; uint256 private _presale_start; uint256 private _presale_end; IPresaleInfo[] private _presale_infos; mapping( address => uint256 ) private _address_to_presale_minted_1st; mapping( address => uint256 ) private _address_to_presale_minted_2nd; mapping( address => uint256 ) private _address_to_presale_minted_3rd; bool private _presale_suspended; // ステーク関連 bool private _stake_suspended; bool private _unstake_suspended; mapping( uint256 => address ) private _token_to_stake_holder; //-------------------------------------------- // コンストラクタ //-------------------------------------------- constructor() Ownable() ERC721( TOKEN_NAME, TOKEN_SYMBOL ){ // お金を引き出せる人 _accountant = 0xda1B1849EeF51f1F5EfF49dA1220ebb89a5ef2FF; // 本番 // id_offset _arr_id_offset[ID_PHASE_GA] = 1; _arr_id_offset[ID_PHASE_1ST] = 113; _arr_id_offset[ID_PHASE_2ND] = 1668; _arr_id_offset[ID_PHASE_3RD] = 4223; // num_mintable _arr_num_mintable[ID_PHASE_GA] = 112; _arr_num_mintable[ID_PHASE_1ST] = 1555; _arr_num_mintable[ID_PHASE_2ND] = 2555; _arr_num_mintable[ID_PHASE_3RD] = 3555; // ステーク関連(リリース時はオフにしておく) _stake_suspended = true; _unstake_suspended = true; } //--------------------------------------------------- // [public] 一般販売が利用可能か? //--------------------------------------------------- function isSaleAvailable() public view returns (bool) { // フェーズが無効 if( _sale_phase < ID_PHASE_1ST || _sale_phase > ID_PHASE_3RD ){ return( false ); } // 一時停止中 if( _sale_suspended ){ return( false ); } // 開始前 if( _sale_start > block.timestamp ){ return( false ); } // 終了:_sale_endが0の場合は無期限 if( _sale_end != 0 && _sale_end <= block.timestamp ){ return( false ); } // 利用可能 return( true ); } //-------------------------------------------- // [external] 一般販売 //-------------------------------------------- function mintTokens( uint256 num ) external payable { // 購入可能か? require( isSaleAvailable(), "sale: not available" ); // 試行回数は有効か? require( num > 0 && num <= PUBLIC_SALE_MAX_SHOT, "sale: invalid num" ); // 残りはあるか? require( _arr_num_mintable[_sale_phase] >= (_arr_num_minted[_sale_phase]+num), "sale: remaining not enough" ); // 入金額は有効か? uint256 amount = _sale_price * num; require( amount <= msg.value , "sale: insufficient value" ); //-------------------------- // ここまできたらチェック完了 //-------------------------- for( uint256 i=0; i<num; i++ ){ _safeMint( msg.sender, _arr_num_minted[_sale_phase] + _arr_id_offset[_sale_phase] ); _arr_num_minted[_sale_phase]++; } } //--------------------------------------------------- // [public] 事前販売が利用可能か? //--------------------------------------------------- function isPresaleAvailable() public view returns (bool) { // フェーズが無効 if( _sale_phase < ID_PHASE_1ST || _sale_phase > ID_PHASE_3RD ){ return( false ); } // 一時停止中 if( _presale_suspended ){ return( false ); } // 開始前 if( _presale_start > block.timestamp ){ return( false ); } // 終了:_presale_endが0の場合は無期限 if( _presale_end != 0 && _presale_end <= block.timestamp ){ return( false ); } // 利用可能 return( true ); } //--------------------------------------------------- // [public] 事前登録済みのユーザーか? //--------------------------------------------------- function isRegisteredUser( address user ) public view returns (bool) { for( uint256 i=0; i<_presale_infos.length; i++ ){ if( _presale_infos[i].isRegistered( user ) ){ return( true ); } } return( false ); } //-------------------------------------------- // [external] 事前販売 //-------------------------------------------- function mintTokensForPresale( uint256 num ) external payable { // 購入可能か? require( isPresaleAvailable(), "pre-sale: not available" ); // 事前登録に登録しているか? require( isRegisteredUser(msg.sender), "pre-sale: not registered" ); // 試行回数は有効か? require( num > 0 && num <= PRE_SALE_MAX_SHOT, "pre-sale: invalid num" ); // 発行上限未満か? uint256 minted = PRE_SALE_LIMIT; if( _sale_phase == ID_PHASE_1ST){ minted = _address_to_presale_minted_1st[msg.sender]; } else if( _sale_phase == ID_PHASE_2ND){ minted = _address_to_presale_minted_2nd[msg.sender]; } else if( _sale_phase == ID_PHASE_3RD){ minted = _address_to_presale_minted_3rd[msg.sender]; } require( PRE_SALE_LIMIT >= (minted+num), "pre-sale: limitation" ); // 残りはあるか? require( _arr_num_mintable[_sale_phase] >= (_arr_num_minted[_sale_phase]+num), "pre-sale: remaining not enough" ); // 入金額は有効か? uint256 amount = _presale_price * num; require( amount <= msg.value , "pre-sale: insufficient value" ); //-------------------------- // ここまできたらチェック完了 //-------------------------- for( uint256 i=0; i<num; i++ ){ _safeMint( msg.sender, _arr_num_minted[_sale_phase] + _arr_id_offset[_sale_phase] ); _arr_num_minted[_sale_phase]++; } if( _sale_phase == ID_PHASE_1ST){ _address_to_presale_minted_1st[msg.sender] += num; } else if( _sale_phase == ID_PHASE_2ND){ _address_to_presale_minted_2nd[msg.sender] += num; } else if( _sale_phase == ID_PHASE_3RD){ _address_to_presale_minted_3rd[msg.sender] += num; } } //-------------------------------------------- // [external/onlyOwner] トークンのgiveaway //-------------------------------------------- function giveawayTokens( address[] calldata users ) external onlyOwner { // 発行上限未満か? require( users.length > 0 && _arr_num_mintable[ID_PHASE_GA] >= (_arr_num_minted[ID_PHASE_GA]+users.length), "giveaway: invalid length" ); // 用心 for( uint256 i=0; i<users.length; i++ ){ require( users[i] != address(0), "giveaway: invalid user" ); } //-------------------------- // ここまできたらチェック完了 //-------------------------- for( uint256 i=0; i<users.length; i++ ){ _safeMint( users[i], _arr_num_minted[ID_PHASE_GA] + _arr_id_offset[ID_PHASE_GA] ); _arr_num_minted[ID_PHASE_GA]++; } } //-------------------------------------------------------- // [external] 引き出せるアカウントの確認 //-------------------------------------------------------- function accountant() external view returns (address) { return( _accountant ); } //-------------------------------------------------------- // [external/onlyOwner] 引き出せるアカウントの設定 //-------------------------------------------------------- function setaAccountant( address target ) external onlyOwner { _accountant = target; } //-------------------------------------------------------- // [external] 各種確認 //-------------------------------------------------------- function idOffsetAt( uint256 id ) external view returns (uint256) { return( _arr_id_offset[id] ); } function numMintableAt( uint256 id ) external view returns (uint256) { return( _arr_num_mintable[id] ); } function numMintedAt( uint256 id ) external view returns (uint256) { return( _arr_num_minted[id] ); } //-------------------------------------------------------- // [external] 発行可能数の確認 //-------------------------------------------------------- function totalMintable() external view returns (uint256) { uint256 mintable = 0; for( uint256 i=0; i<ID_PHASE_MAX; i++ ){ mintable += _arr_num_mintable[i]; } return( mintable ); } //-------------------------------------------------------- // [external] 発行数の確認 //-------------------------------------------------------- function totalMinted() external view returns (uint256) { uint256 minted = 0; for( uint256 i=0; i<ID_PHASE_MAX; i++ ){ minted += _arr_num_minted[i]; } return( minted ); } //-------------------------------------------------------- // [external] _base_url の確認 //-------------------------------------------------------- function baseUrlAt( uint256 at ) external view returns (string memory) { return( _arr_base_url[at] ); } //-------------------------------------------------------- // [external/onlyOwner] _base_url の設定 //-------------------------------------------------------- function setBaseUrlAt( uint256 at, string calldata url ) external onlyOwner { _arr_base_url[at] = url; } //--------------------------------------------------- // [public] 修復されたURLの確認 //--------------------------------------------------- function repairedUrl( uint256 tokenId ) public view returns (string memory) { require( _exists( tokenId ), "nonexistent token" ); return( _repaired_urls[tokenId] ); } //--------------------------------------------------- // [external/onlyOwner] メタデータのURLの修復 //--------------------------------------------------- function repairUrl( uint256 tokenId, string calldata url ) external onlyOwner { require( _exists( tokenId ), "nonexistent token" ); _repaired_urls[tokenId] = url; } //---------------------------------------------- // [public] tokenURI //---------------------------------------------- function tokenURI( uint256 tokenId ) public view override returns (string memory) { require( _exists( tokenId ), "nonexistent token" ); // 修復データがあれば string memory url = repairedUrl( tokenId ); if( bytes(url).length > 0 ){ return( url ); } uint256 at = ID_PHASE_MAX; for( uint256 i=0; i<ID_PHASE_MAX; i++ ){ if( tokenId >= _arr_id_offset[i] && tokenId < (_arr_id_offset[i]+_arr_num_mintable[i]) ){ at = i; break; } } require( at < ID_PHASE_MAX, "invalid phase" ); // ここまできたらリリース時のメタを返す string memory strId = LibString.toString( tokenId ); return( string( abi.encodePacked( _arr_base_url[at], strId ) ) ); } //--------------------------------------------------- // [external/onlyOwner] 販売設定 //--------------------------------------------------- function setSale( uint256 phase, uint256 saleP, uint256 saleF, uint256 saleT, uint256 presaleP, uint256 presaleF, uint256 presaleT, address[] calldata arrInfo ) external onlyOwner { _sale_phase = phase; _sale_price = saleP; _sale_start = saleF; _sale_end = saleT; _presale_price = presaleP; _presale_start = presaleF; _presale_end = presaleT; delete _presale_infos; for( uint256 i=0; i<arrInfo.length; i++ ){ _presale_infos.push( IPresaleInfo( arrInfo[i] ) ); } } //--------------------------------------------------- // [external] 設定確認 //--------------------------------------------------- function salePhase() external view returns (uint256) { return(_sale_phase); } function salePrice() external view returns (uint256) { return(_sale_price); } function saleStart() external view returns (uint256) { return( _sale_start ); } function saleEnd() external view returns (uint256) { return( _sale_end ); } function presalePrice() external view returns (uint256) { return(_presale_price); } function presaleStart() external view returns (uint256) { return( _presale_start ); } function presaleEnd() external view returns (uint256) { return( _presale_end ); } function presaleInfoAt( uint256 at ) external view returns (address) { if( at < _presale_infos.length ){ return( address(_presale_infos[at]) ); } return( address(0) ); } function presaleMintedAt( uint256 at, address user ) external view returns (uint256) { if( at == ID_PHASE_1ST){ return( _address_to_presale_minted_1st[user] ); } if( at == ID_PHASE_2ND){ return( _address_to_presale_minted_2nd[user] ); } if( at == ID_PHASE_3RD){ return( _address_to_presale_minted_3rd[user] ); } return( 0 ); } //--------------------------------------------------- // [external] 情報の一括取得(フロント向け) //--------------------------------------------------- function saleInfo() external view returns (uint256[12] memory) { require( _sale_phase >= ID_PHASE_1ST && _sale_phase <= ID_PHASE_3RD, "invalid phase" ); uint256[12] memory info; // 状況 info[0] = _sale_phase; info[1] = _arr_id_offset[_sale_phase]; info[2] = _arr_num_mintable[_sale_phase]; info[3] = _arr_num_minted[_sale_phase]; // セール情報 if( isSaleAvailable() ){ info[4] = 1; } info[5] = _sale_price; info[6] = _sale_start; info[7] = _sale_end; // プレセール情報 if( isPresaleAvailable() ){ info[8] = 1; } info[9] = _presale_price; info[10] = _presale_start; info[11] = _presale_end; return( info ); } //--------------------------------------------------- // [external/onlyOwner] 販売停止 //--------------------------------------------------- function suspendSale( bool flag ) external onlyOwner { _sale_suspended = flag; } function suspendPresale( bool flag ) external onlyOwner { _presale_suspended = flag; } //--------------------------------------------------- // [external] 販売状況の確認 //--------------------------------------------------- function saleSuspended() external view returns (bool) { return( _sale_suspended ); } function presaleSuspended() external view returns (bool) { return( _presale_suspended ); } //--------------------------------------------------- // [external/onlyOwner] ステークキングの停止 //--------------------------------------------------- function suspendStake( bool flag ) external onlyOwner { _stake_suspended = flag; } function suspendUnstake( bool flag ) external onlyOwner { _unstake_suspended = flag; } //--------------------------------------------------- // [external] ステーキング状況の確認 //--------------------------------------------------- function stakeSuspended() external view returns (bool) { return( _stake_suspended ); } function unstakeSuspended() external view returns (bool) { return( _unstake_suspended ); } //-------------------------------------------------------- // [external] NFTのステーク //-------------------------------------------------------- function stakeTokens( uint256[] calldata tokenIds ) external { require( !_stake_suspended, "stake: not available" ); // 確認 for( uint256 i=0; i<tokenIds.length; i++ ){ require( _exists(tokenIds[i]), "stake: nonexistent token" ); require( ownerOf(tokenIds[i]) == msg.sender, "stake: not owner" ); for( uint256 j=i+1; j<tokenIds.length; j++ ){ require( tokenIds[i] != tokenIds[j], "stake: duplicated token id" ); } } // オーナーに預け入れ for( uint256 i=0; i<tokenIds.length; i++ ){ safeTransferFrom( msg.sender, owner(), tokenIds[i] ); _token_to_stake_holder[tokenIds[i]] = msg.sender; emit TokenStake( msg.sender, tokenIds[i] ); } } //-------------------------------------------------------- // [external] NFTのアンステーク //-------------------------------------------------------- function unstakeTokens( uint256[] calldata tokenIds ) external { require( !_unstake_suspended, "unstake: not available" ); // 確認 for( uint256 i=0; i<tokenIds.length; i++ ){ require( _exists(tokenIds[i]), "unstake: nonexistent token" ); require( _token_to_stake_holder[tokenIds[i]] == msg.sender, "unstake: not holder" ); for( uint256 j=i+1; j<tokenIds.length; j++ ){ require( tokenIds[i] != tokenIds[j], "unstake: duplicated token id" ); } } // オーナーから払い戻し for( uint256 i=0; i<tokenIds.length; i++ ){ safeTransferFrom( owner(), msg.sender, tokenIds[i] ); delete _token_to_stake_holder[tokenIds[i]]; emit TokenUnstake( msg.sender, tokenIds[i] ); } } //-------------------------------------------------------- // [external] トークンをステークしているアドレスの確認 //-------------------------------------------------------- function checkStakeHolder( uint256 tokenId ) external view returns (address) { require( _exists(tokenId), "nonexistent token" ); return( _token_to_stake_holder[tokenId] ); } //-------------------------------------------------------- // [external] 残高の確認 //-------------------------------------------------------- function checkBalance() external view returns (uint256) { return( address(this).balance ); } //-------------------------------------------------------- // [external/onlyAccountant] 引き出し //-------------------------------------------------------- function withdraw( uint256 amount ) external { require( msg.sender == _accountant, "not accountant" ); require( amount <= address(this).balance, "insufficient balance" ); address payable target = payable( msg.sender ); target.transfer( amount ); } }
-------------------------------------------------------- [external] トークンをステークしているアドレスの確認--------------------------------------------------------
function checkStakeHolder( uint256 tokenId ) external view returns (address) { require( _exists(tokenId), "nonexistent token" ); return( _token_to_stake_holder[tokenId] ); }
13,522,707
./full_match/3/0x25a5F12a707Bc30b2081f750976E489b62F567aE/sources/localhost/deployments/Option.full.sol
Initialize, called once
function getOptionDetails() external view returns ( string memory _name, address _baseToken, address _targetToken, address _optionToken, address _proofToken, uint256 _baseAmount, uint256 _targetAmout, uint256 _totalSupply, uint64 _expirationTimestamp, uint64 _expirationDelay, uint64 _optionNonce ); function getOptionDetailsEx() external view returns (IOption.OptionDetails memory _option); function subscribeOption( uint256 _amount ) external; function unsubscribeOption( uint256 _amount ) external; function subscribeOptionByContract(uint256 _amount ) external returns ( uint256 _mintAmount ); function unsubscribeOptionByContract(uint256 _amount ) external returns ( uint256 _burnAmount ); function excuteOption( uint256 _amount ) external; function collectOption( uint256 _amount ) external; function validStatus() external view; } pragma solidity ^0.7.3; } pragma solidity ^0.7.3; } pragma solidity ^0.7.3; } pragma solidity ^0.7.3; ) public initializer { initializeOwner(); option.name = _name; option.baseToken = _baseToken; option.targetToken = _targetToken; option.baseAmount = _baseAmount; option.targetAmout = _targetAmout; option.totalSupply = _totalSupply; option.expirationTimestamp = _expirationTimestamp; option.expirationDelay = _expirationDelay; option.optionNonce = _optionNonce; option.optionToken = _createZoomToken("OPTION"); option.proofToken = _createZoomToken("PROOF"); }
8,097,074
./partial_match/1/0x1C2AC88532f54A046f842B0651f0C2F6A80E729D/sources/contracts/Staking/IStakingV2Factory.sol
Token Staking BEP20 compatible token./
interface IStakingV2Factory { function createVendor(address _parent, IERC20 _token) external returns (address); }
3,695,320
/** *Submitted for verification at Etherscan.io on 2022-01-14 */ // File: interfaces/IExchangeAgent.sol pragma solidity ^0.8.0; interface IExchangeAgent { function getNeededTokenAmount( address _token0, address _token1, uint256 _desiredAmount ) external returns (uint256); function getTokenAmountForUSDC(address _token, uint256 _desiredAmount) external returns (uint256); function getETHAmountForUSDC(uint256 _desiredAmount) external view returns (uint256); function getTokenAmountForETH(address _token, uint256 _desiredAmount) external returns (uint256); function swapTokenWithETH( address _token, uint256 _amount, uint256 _desiredAmount ) external; function swapTokenWithToken( address _token0, address _token1, uint256 _amount, uint256 _desiredAmount ) external; } // File: interfaces/ITwapOraclePriceFeed.sol pragma solidity 0.8.0; interface ITwapOraclePriceFeed { function update() external; function consult(address token, uint256 amountIn) external view returns (uint256 amountOut); } // File: interfaces/ITwapOraclePriceFeedFactory.sol pragma solidity 0.8.0; interface ITwapOraclePriceFeedFactory { function twapOraclePriceFeedList(address _pair) external view returns (address); function getTwapOraclePriceFeed(address _token0, address _token1) external view returns (address twapOraclePriceFeed); } // File: interfaces/IUniswapV2Factory.sol pragma solidity 0.8.0; interface IUniswapV2Factory { function getPair(address tokenA, address tokenB) external view returns (address pair); } // File: interfaces/IUniswapV2Pair.sol pragma solidity ^0.8.0; interface IUniswapV2Pair { function getReserves() external view returns ( uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast ); function token0() external view returns (address); function token1() external view returns (address); } // File: libs/TransferHelper.sol pragma solidity 0.8.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"); } } // File: @openzeppelin/contracts/security/ReentrancyGuard.sol // OpenZeppelin Contracts v4.4.1 (security/ReentrancyGuard.sol) pragma solidity ^0.8.0; /** * @dev Contract module that helps prevent reentrant calls to a function. * * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier * available, which can be applied to functions to make sure there are no nested * (reentrant) calls to them. * * Note that because there is a single `nonReentrant` guard, functions marked as * `nonReentrant` may not call one another. This can be worked around by making * those functions `private`, and then adding `external` `nonReentrant` entry * points to them. * * TIP: If you would like to learn more about reentrancy and alternative ways * to protect against it, check out our blog post * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul]. */ abstract contract ReentrancyGuard { // Booleans are more expensive than uint256 or any type that takes up a full // word because each write operation emits an extra SLOAD to first read the // slot's contents, replace the bits taken up by the boolean, and then write // back. This is the compiler's defense against contract upgrades and // pointer aliasing, and it cannot be disabled. // The values being non-zero value makes deployment a bit more expensive, // but in exchange the refund on every call to nonReentrant will be lower in // amount. Since refunds are capped to a percentage of the total // transaction's gas, it is best to keep them low in cases like this one, to // increase the likelihood of the full refund coming into effect. uint256 private constant _NOT_ENTERED = 1; uint256 private constant _ENTERED = 2; uint256 private _status; constructor() { _status = _NOT_ENTERED; } /** * @dev Prevents a contract from calling itself, directly or indirectly. * Calling a `nonReentrant` function from another `nonReentrant` * function is not supported. It is possible to prevent this from happening * by making the `nonReentrant` function external, and making it call a * `private` function that does the actual work. */ modifier nonReentrant() { // On the first call to nonReentrant, _notEntered will be true require(_status != _ENTERED, "ReentrancyGuard: reentrant call"); // Any calls to nonReentrant after this point will fail _status = _ENTERED; _; // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) _status = _NOT_ENTERED; } } // File: @openzeppelin/contracts/utils/Context.sol // OpenZeppelin Contracts v4.4.1 (utils/Context.sol) pragma solidity ^0.8.0; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } // File: @openzeppelin/contracts/access/Ownable.sol // OpenZeppelin Contracts v4.4.1 (access/Ownable.sol) pragma solidity ^0.8.0; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() { _transferOwnership(_msgSender()); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { _transferOwnership(address(0)); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); _transferOwnership(newOwner); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Internal function without access restriction. */ function _transferOwnership(address newOwner) internal virtual { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } } // File: @openzeppelin/contracts/token/ERC20/IERC20.sol // OpenZeppelin Contracts v4.4.1 (token/ERC20/IERC20.sol) pragma solidity ^0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom( address sender, address recipient, uint256 amount ) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // File: @openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol // OpenZeppelin Contracts v4.4.1 (token/ERC20/extensions/IERC20Metadata.sol) pragma solidity ^0.8.0; /** * @dev Interface for the optional metadata functions from the ERC20 standard. * * _Available since v4.1._ */ interface IERC20Metadata is IERC20 { /** * @dev Returns the name of the token. */ function name() external view returns (string memory); /** * @dev Returns the symbol of the token. */ function symbol() external view returns (string memory); /** * @dev Returns the decimals places of the token. */ function decimals() external view returns (uint8); } // File: ExchangeAgent.sol pragma solidity ^0.8.0; /** * @dev This smart contract is for getting CVR_ETH, CVR_USDT price */ contract ExchangeAgent is Ownable, IExchangeAgent, ReentrancyGuard { event AddGateway(address _sender, address _gateway); event RemoveGateway(address _sender, address _gateway); event AddAvailableCurrency(address _sender, address _currency); event RemoveAvailableCurrency(address _sender, address _currency); event UpdateSlippage(address _sender, uint256 _slippage); event WithdrawAsset(address _user, address _to, address _token, uint256 _amount); event UpdateSlippageRate(address _user, uint256 _slippageRate); mapping(address => bool) public whiteList; // white listed CoverCompared gateways // available currencies in CoverCompared, token => bool // for now we allow CVR mapping(address => bool) public availableCurrencies; address public immutable CVR_ADDRESS; address public immutable USDC_ADDRESS; /** * We are using Uniswap V2 TWAP oracle - so it should be WETH addres in Uniswap V2 */ address public immutable WETH; address public immutable UNISWAP_FACTORY; address public immutable TWAP_ORACLE_PRICE_FEED_FACTORY; uint256 public SLIPPPAGE_RAGE; /** * when users try to use CVR to buy products, we will discount some percentage(25% at first stage) */ uint256 public discountPercentage = 75; constructor( address _CVR_ADDRESS, address _USDC_ADDRESS, address _WETH, address _UNISWAP_FACTORY, address _TWAP_ORACLE_PRICE_FEED_FACTORY ) { CVR_ADDRESS = _CVR_ADDRESS; USDC_ADDRESS = _USDC_ADDRESS; WETH = _WETH; UNISWAP_FACTORY = _UNISWAP_FACTORY; TWAP_ORACLE_PRICE_FEED_FACTORY = _TWAP_ORACLE_PRICE_FEED_FACTORY; SLIPPPAGE_RAGE = 100; } receive() external payable {} modifier onlyWhiteListed(address _gateway) { require(whiteList[_gateway], "Only white listed addresses are acceptable"); _; } /** * @dev If users use CVR, they will pay _discountPercentage % of cost. */ function setDiscountPercentage(uint256 _discountPercentage) external onlyOwner { require(_discountPercentage <= 100, "Exceeded value"); discountPercentage = _discountPercentage; } /** * @dev Get needed _token0 amount for _desiredAmount of _token1 * _desiredAmount should consider decimals based on _token1 */ function _getNeededTokenAmount( address _token0, address _token1, uint256 _desiredAmount ) private view returns (uint256) { address pair = IUniswapV2Factory(UNISWAP_FACTORY).getPair(_token0, _token1); require(pair != address(0), "There's no pair"); address twapOraclePriceFeed = ITwapOraclePriceFeedFactory(TWAP_ORACLE_PRICE_FEED_FACTORY).getTwapOraclePriceFeed( _token0, _token1 ); require(twapOraclePriceFeed != address(0), "There's no twap oracle for this pair"); uint256 neededAmount = ITwapOraclePriceFeed(twapOraclePriceFeed).consult(_token1, _desiredAmount); if (_token0 == CVR_ADDRESS) { neededAmount = (neededAmount * discountPercentage) / 100; } return neededAmount; } /** * @dev Get needed _token0 amount for _desiredAmount of _token1 */ function getNeededTokenAmount( address _token0, address _token1, uint256 _desiredAmount ) external view override returns (uint256) { return _getNeededTokenAmount(_token0, _token1, _desiredAmount); } function getETHAmountForUSDC(uint256 _desiredAmount) external view override returns (uint256) { return _getNeededTokenAmount(WETH, USDC_ADDRESS, _desiredAmount); } /** * get needed _token amount for _desiredAmount of USDC */ function getTokenAmountForUSDC(address _token, uint256 _desiredAmount) external view override returns (uint256) { return _getNeededTokenAmount(_token, USDC_ADDRESS, _desiredAmount); } /** * get needed _token amount for _desiredAmount of ETH */ function getTokenAmountForETH(address _token, uint256 _desiredAmount) external view override returns (uint256) { return _getNeededTokenAmount(_token, WETH, _desiredAmount); } /** * @param _amount: this one is the value with decimals */ function swapTokenWithETH( address _token, uint256 _amount, uint256 _desiredAmount ) external override onlyWhiteListed(msg.sender) nonReentrant { // store CVR in this exchagne contract // send eth to buy gateway based on the uniswap price require(availableCurrencies[_token], "Token should be added in available list"); _swapTokenWithToken(_token, WETH, _amount, _desiredAmount); } function swapTokenWithToken( address _token0, address _token1, uint256 _amount, uint256 _desiredAmount ) external override onlyWhiteListed(msg.sender) nonReentrant { require(availableCurrencies[_token0], "Token should be added in available list"); _swapTokenWithToken(_token0, _token1, _amount, _desiredAmount); } /** * @dev exchange _amount of _token0 with _token1 by twap oracle price */ function _swapTokenWithToken( address _token0, address _token1, uint256 _amount, uint256 _desiredAmount ) private { address twapOraclePriceFeed = ITwapOraclePriceFeedFactory(TWAP_ORACLE_PRICE_FEED_FACTORY).getTwapOraclePriceFeed( _token0, _token1 ); uint256 swapAmount = ITwapOraclePriceFeed(twapOraclePriceFeed).consult(_token0, _amount); uint256 availableMinAmount = (_desiredAmount * (10000 - SLIPPPAGE_RAGE)) / 10000; if (_token0 == CVR_ADDRESS) { availableMinAmount = (availableMinAmount * discountPercentage) / 100; } require(swapAmount > availableMinAmount, "Overflow min amount"); TransferHelper.safeTransferFrom(_token0, msg.sender, address(this), _amount); if (_token1 == WETH) { TransferHelper.safeTransferETH(msg.sender, _desiredAmount); } else { TransferHelper.safeTransfer(_token1, msg.sender, _desiredAmount); } } function addWhiteList(address _gateway) external onlyOwner { require(!whiteList[_gateway], "Already white listed"); whiteList[_gateway] = true; emit AddGateway(msg.sender, _gateway); } function removeWhiteList(address _gateway) external onlyOwner { require(whiteList[_gateway], "Not white listed"); whiteList[_gateway] = false; emit RemoveGateway(msg.sender, _gateway); } function addCurrency(address _currency) external onlyOwner { require(!availableCurrencies[_currency], "Already available"); availableCurrencies[_currency] = true; emit AddAvailableCurrency(msg.sender, _currency); } function removeCurrency(address _currency) external onlyOwner { require(availableCurrencies[_currency], "Not available yet"); availableCurrencies[_currency] = false; emit RemoveAvailableCurrency(msg.sender, _currency); } function setSlippageRate(uint256 _slippageRate) external onlyOwner { require(_slippageRate > 0 && _slippageRate < 100, "Overflow range"); SLIPPPAGE_RAGE = _slippageRate * 100; emit UpdateSlippageRate(msg.sender, _slippageRate); } function withdrawAsset( address _to, address _token, uint256 _amount ) external onlyOwner { if (_token == address(0)) { TransferHelper.safeTransferETH(_to, _amount); } else { TransferHelper.safeTransfer(_token, _to, _amount); } emit WithdrawAsset(owner(), _to, _token, _amount); } }
If users use CVR, they will pay _discountPercentage % of cost./
function setDiscountPercentage(uint256 _discountPercentage) external onlyOwner { require(_discountPercentage <= 100, "Exceeded value"); discountPercentage = _discountPercentage; }
1,985,969
// SPDX-License-Identifier: MIT pragma solidity ^0.6.12; pragma experimental ABIEncoderV2; /* ___ _ _ | _ )_ _ _ _ _ _ _ _ | | | | | _ \ || | ' \| ' \ || | |_| |_| |___/\_,_|_||_|_||_\_, | (_) (_) |__/ * * MIT License * =========== * * Copyright (c) 2020 BunnyFinance * * 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 */ import "@pancakeswap/pancake-swap-lib/contracts/token/BEP20/SafeBEP20.sol"; import "@openzeppelin/contracts/math/Math.sol"; import {PoolConstant} from "../library/PoolConstant.sol"; import "../interfaces/IPancakePair.sol"; import "../interfaces/IPancakeFactory.sol"; import "../interfaces/IStrategy.sol"; import "../interfaces/IMasterChef.sol"; import "../interfaces/IBunnyMinter.sol"; import "../zap/ZapBSC.sol"; import "./VaultController.sol"; contract VaultFlipToFlip is VaultController, IStrategy { using SafeBEP20 for IBEP20; using SafeMath for uint256; /* ========== CONSTANTS ============= */ IBEP20 private constant CAKE = IBEP20(0x0E09FaBB73Bd3Ade0a17ECC321fD13a19e81cE82); IBEP20 private constant WBNB = IBEP20(0xbb4CdB9CBd36B01bD1cBaEBF2De08d9173bc095c); IMasterChef private constant CAKE_MASTER_CHEF = IMasterChef(0x73feaa1eE314F8c655E354234017bE2193C9E24E); PoolConstant.PoolTypes public constant override poolType = PoolConstant.PoolTypes.FlipToFlip; ZapBSC public constant zapBSC = ZapBSC(0xdC2bBB0D33E0e7Dea9F5b98F46EDBaC823586a0C); IPancakeRouter02 private constant ROUTER_V1 = IPancakeRouter02(0x2AD2C5314028897AEcfCF37FD923c079BeEb2C56); IPancakeRouter02 private constant ROUTER_V2 = IPancakeRouter02(0x10ED43C718714eb63d5aA57B78B54704E256024E); IPancakeFactory private constant FACTORY_V1 = IPancakeFactory(0x877Fe7F4e22e21bE397Cd9364fAFd4aF4E15Edb6); uint private constant DUST = 1000; /* ========== STATE VARIABLES ========== */ uint public override pid; address private _token0; address private _token1; uint public totalShares; mapping (address => uint) private _shares; mapping (address => uint) private _principal; mapping (address => uint) private _depositedAt; uint public cakeHarvested; /* ========== MODIFIER ========== */ modifier updateCakeHarvested { uint before = CAKE.balanceOf(address(this)); _; uint _after = CAKE.balanceOf(address(this)); cakeHarvested = cakeHarvested.add(_after).sub(before); } /* ========== INITIALIZER ========== */ function initialize(uint _pid, address _token) external initializer { __VaultController_init(IBEP20(_token)); _stakingToken.safeApprove(address(CAKE_MASTER_CHEF), uint(- 1)); pid = _pid; CAKE.safeApprove(address(zapBSC), uint(- 1)); } /* ========== VIEW FUNCTIONS ========== */ function totalSupply() external view override returns (uint) { return totalShares; } function balance() public view override returns (uint amount) { (amount,) = CAKE_MASTER_CHEF.userInfo(pid, address(this)); } function balanceOf(address account) public view override returns(uint) { if (totalShares == 0) return 0; return balance().mul(sharesOf(account)).div(totalShares); } function withdrawableBalanceOf(address account) public view override returns (uint) { return balanceOf(account); } function sharesOf(address account) public view override returns (uint) { return _shares[account]; } function principalOf(address account) public view override returns (uint) { return _principal[account]; } function earned(address account) public view override returns (uint) { if (balanceOf(account) >= principalOf(account) + DUST) { return balanceOf(account).sub(principalOf(account)); } else { return 0; } } function depositedAt(address account) external view override returns (uint) { return _depositedAt[account]; } function rewardsToken() external view override returns (address) { return address(_stakingToken); } function priceShare() external view override returns(uint) { if (totalShares == 0) return 1e18; return balance().mul(1e18).div(totalShares); } /* ========== MUTATIVE FUNCTIONS ========== */ function deposit(uint _amount) public override { _depositTo(_amount, msg.sender); } function depositAll() external override { deposit(_stakingToken.balanceOf(msg.sender)); } function withdrawAll() external override { uint amount = balanceOf(msg.sender); uint principal = principalOf(msg.sender); uint depositTimestamp = _depositedAt[msg.sender]; totalShares = totalShares.sub(_shares[msg.sender]); delete _shares[msg.sender]; delete _principal[msg.sender]; delete _depositedAt[msg.sender]; amount = _withdrawTokenWithCorrection(amount); uint profit = amount > principal ? amount.sub(principal) : 0; uint withdrawalFee = canMint() ? _minter.withdrawalFee(principal, depositTimestamp) : 0; uint performanceFee = canMint() ? _minter.performanceFee(profit) : 0; if (withdrawalFee.add(performanceFee) > DUST) { _minter.mintForV2(address(_stakingToken), withdrawalFee, performanceFee, msg.sender, depositTimestamp); if (performanceFee > 0) { emit ProfitPaid(msg.sender, profit, performanceFee); } amount = amount.sub(withdrawalFee).sub(performanceFee); } _stakingToken.safeTransfer(msg.sender, amount); emit Withdrawn(msg.sender, amount, withdrawalFee); } function harvest() external override onlyKeeper { _harvest(); uint before = _stakingToken.balanceOf(address(this)); zapBSC.zapInToken(address(CAKE), cakeHarvested, address(_stakingToken)); uint harvested = _stakingToken.balanceOf(address(this)).sub(before); CAKE_MASTER_CHEF.deposit(pid, harvested); emit Harvested(harvested); cakeHarvested = 0; } function _harvest() private updateCakeHarvested { CAKE_MASTER_CHEF.withdraw(pid, 0); } function withdraw(uint shares) external override onlyWhitelisted { uint amount = balance().mul(shares).div(totalShares); totalShares = totalShares.sub(shares); _shares[msg.sender] = _shares[msg.sender].sub(shares); amount = _withdrawTokenWithCorrection(amount); _stakingToken.safeTransfer(msg.sender, amount); emit Withdrawn(msg.sender, amount, 0); } // @dev underlying only + withdrawal fee + no perf fee function withdrawUnderlying(uint _amount) external { uint amount = Math.min(_amount, _principal[msg.sender]); uint shares = Math.min(amount.mul(totalShares).div(balance()), _shares[msg.sender]); totalShares = totalShares.sub(shares); _shares[msg.sender] = _shares[msg.sender].sub(shares); _principal[msg.sender] = _principal[msg.sender].sub(amount); amount = _withdrawTokenWithCorrection(amount); uint depositTimestamp = _depositedAt[msg.sender]; uint withdrawalFee = canMint() ? _minter.withdrawalFee(amount, depositTimestamp) : 0; if (withdrawalFee > DUST) { _minter.mintForV2(address(_stakingToken), withdrawalFee, 0, msg.sender, depositTimestamp); amount = amount.sub(withdrawalFee); } _stakingToken.safeTransfer(msg.sender, amount); emit Withdrawn(msg.sender, amount, withdrawalFee); } // @dev profits only (underlying + bunny) + no withdraw fee + perf fee function getReward() external override { uint amount = earned(msg.sender); uint shares = Math.min(amount.mul(totalShares).div(balance()), _shares[msg.sender]); totalShares = totalShares.sub(shares); _shares[msg.sender] = _shares[msg.sender].sub(shares); _cleanupIfDustShares(); amount = _withdrawTokenWithCorrection(amount); uint depositTimestamp = _depositedAt[msg.sender]; uint performanceFee = canMint() ? _minter.performanceFee(amount) : 0; if (performanceFee > DUST) { _minter.mintForV2(address(_stakingToken), 0, performanceFee, msg.sender, depositTimestamp); amount = amount.sub(performanceFee); } _stakingToken.safeTransfer(msg.sender, amount); emit ProfitPaid(msg.sender, amount, performanceFee); } /* ========== PRIVATE FUNCTIONS ========== */ function _depositTo(uint _amount, address _to) private notPaused updateCakeHarvested { uint _pool = balance(); uint _before = _stakingToken.balanceOf(address(this)); _stakingToken.safeTransferFrom(msg.sender, address(this), _amount); uint _after = _stakingToken.balanceOf(address(this)); _amount = _after.sub(_before); // Additional check for deflationary tokens uint shares = 0; if (totalShares == 0) { shares = _amount; } else { shares = (_amount.mul(totalShares)).div(_pool); } totalShares = totalShares.add(shares); _shares[_to] = _shares[_to].add(shares); _principal[_to] = _principal[_to].add(_amount); _depositedAt[_to] = block.timestamp; CAKE_MASTER_CHEF.deposit(pid, _amount); emit Deposited(_to, _amount); } function _withdrawTokenWithCorrection(uint amount) private updateCakeHarvested returns (uint) { uint before = _stakingToken.balanceOf(address(this)); CAKE_MASTER_CHEF.withdraw(pid, amount); return _stakingToken.balanceOf(address(this)).sub(before); } function _cleanupIfDustShares() private { uint shares = _shares[msg.sender]; if (shares > 0 && shares < DUST) { totalShares = totalShares.sub(shares); delete _shares[msg.sender]; } } /* ========== SALVAGE PURPOSE ONLY ========== */ // @dev stakingToken must not remain balance in this contract. So dev should salvage staking token transferred by mistake. function recoverToken(address token, uint amount) external override onlyOwner { if (token == address(CAKE)) { uint cakeBalance = CAKE.balanceOf(address(this)); require(amount <= cakeBalance.sub(cakeHarvested), "VaultFlipToFlip: cannot recover lp's harvested cake"); } IBEP20(token).safeTransfer(owner(), amount); emit Recovered(token, amount); } /* ========== MIGRATE PANCAKE V1 to V2 ========== */ function migrate(address account, uint amount) public { if (amount == 0) return; _depositTo(amount, account); } function migrateToken(uint amount) public onlyOwner { _stakingToken.safeTransferFrom(msg.sender, address(this), amount); CAKE_MASTER_CHEF.deposit(pid, amount); } function setPidToken(uint _pid, address token) external onlyOwner { require(totalShares == 0); pid = _pid; _stakingToken = IBEP20(token); _stakingToken.safeApprove(address(CAKE_MASTER_CHEF), 0); _stakingToken.safeApprove(address(CAKE_MASTER_CHEF), uint(- 1)); _stakingToken.safeApprove(address(_minter), 0); _stakingToken.safeApprove(address(_minter), uint(- 1)); } function approveZap() external onlyOwner { CAKE.safeApprove(address(zapBSC), uint(- 1)); IPancakePair pair = IPancakePair(address(_stakingToken)); address token0 = pair.token0(); address token1 = pair.token1(); _flipOutV1(token0, token1); _flipInV2(token0, token1); _dustInV2(address(_stakingToken), token0, token1); uint lpAmount = IBEP20(_stakingToken).balanceOf(address(this)); CAKE_MASTER_CHEF.deposit(pid, lpAmount); } function _flipOutV1(address token0, address token1) private { address flipV1 = FACTORY_V1.getPair(token0, token1); _approveTokenIfNeededV1(flipV1); uint amount = IBEP20(flipV1).balanceOf(address (this)); ROUTER_V1.removeLiquidity(token0, token1, amount, 0, 0, address(this), block.timestamp); } function _flipInV2(address token0, address token1) private { uint tokenAmount0 = IBEP20(token0).balanceOf(address(this)); uint tokenAmount1 = IBEP20(token1).balanceOf(address(this)); if (token0 == address(CAKE)) { tokenAmount0 = tokenAmount0.sub(cakeHarvested); } if (token1 == address(CAKE)) { tokenAmount1 = tokenAmount1.sub(cakeHarvested); } _approveTokenIfNeededV2(token0); _approveTokenIfNeededV2(token1); ROUTER_V2.addLiquidity(token0, token1, tokenAmount0, tokenAmount1, 0, 0, address(this), block.timestamp); } function _dustInV2(address flipV2, address token0, address token1) private { uint bnbBalance = address(this).balance; if (bnbBalance > DUST) { zapBSC.zapIn{value : bnbBalance}(flipV2); } uint tokenAmount0 = IBEP20(token0).balanceOf(address(this)); if (token0 == address(CAKE)) { tokenAmount0 = tokenAmount0.sub(cakeHarvested); } if (tokenAmount0 > DUST) { if (IBEP20(token0).allowance(address(this), address(zapBSC)) == 0) { IBEP20(token0).safeApprove(address(zapBSC), uint(- 1)); } zapBSC.zapInToken(token0, tokenAmount0, flipV2); } uint tokenAmount1 = IBEP20(token1).balanceOf(address(this)); if (token1 == address(CAKE)) { tokenAmount1 = tokenAmount1.sub(cakeHarvested); } if (tokenAmount1 > DUST) { if (IBEP20(token1).allowance(address(this), address(zapBSC)) == 0) { IBEP20(token1).safeApprove(address(zapBSC), uint(- 1)); } zapBSC.zapInToken(token1, tokenAmount1, flipV2); } } function _approveTokenIfNeededV1(address token) private { if (IBEP20(token).allowance(address(this), address(ROUTER_V1)) == 0) { IBEP20(token).safeApprove(address(ROUTER_V1), uint(- 1)); } } function _approveTokenIfNeededV2(address token) private { if (IBEP20(token).allowance(address(this), address(ROUTER_V2)) == 0) { IBEP20(token).safeApprove(address(ROUTER_V2), uint(- 1)); } } }
stakingToken must not remain balance in this contract. So dev should salvage staking token transferred by mistake.
function recoverToken(address token, uint amount) external override onlyOwner { if (token == address(CAKE)) { uint cakeBalance = CAKE.balanceOf(address(this)); require(amount <= cakeBalance.sub(cakeHarvested), "VaultFlipToFlip: cannot recover lp's harvested cake"); } IBEP20(token).safeTransfer(owner(), amount); emit Recovered(token, amount); }
6,473,523
pragma solidity ^0.6.9; // SPDX-License-Identifier: GPL-3.0-or-later import "./SafeMath.sol"; import "../../interfaces/IERC20.sol"; // ---------------------------------------------------------------------------- // DutchSwap Auction Contract // // // MVP prototype. DO NOT USE! // // (c) Adrian Guerrera. Deepyr Pty Ltd. // May 26 2020 // ---------------------------------------------------------------------------- contract DutchSwapAuction { using SafeMath for uint256; uint256 private constant TENPOW18 = 10 ** 18; /// @dev The placeholder ETH address. address private constant ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; uint256 public amountRaised; uint256 public startDate; uint256 public endDate; uint256 public startPrice; uint256 public minimumPrice; uint256 public tokenSupply; bool public finalised; IERC20 public auctionToken; IERC20 public paymentCurrency; address payable public wallet; mapping(address => uint256) public commitments; event AddedCommitment(address addr, uint256 commitment, uint256 price); /// @dev Init function function initDutchAuction( address _token, uint256 _tokenSupply, uint256 _startDate, uint256 _endDate, address _paymentCurrency, uint256 _startPrice, uint256 _minimumPrice, address payable _wallet ) external { require(_endDate > _startDate); require(_startPrice > _minimumPrice); require(_minimumPrice > 0); auctionToken = IERC20(_token); paymentCurrency = IERC20(_paymentCurrency); require(IERC20(auctionToken).transferFrom(msg.sender, address(this), _tokenSupply)); tokenSupply =_tokenSupply; startDate = _startDate; endDate = _endDate; startPrice = _startPrice; minimumPrice = _minimumPrice; wallet = _wallet; finalised = false; } // Dutch Auction Price Function // ============================ // // Start Price ----- // \ // \ // \ // \ ------------ Clearing Price // / \ = AmountRaised/TokenSupply // Token Price -- \ // / \ // -- ----------- Minimum Price // Amount raised / End Time // /// @notice The average price of each token from all commitments. function tokenPrice() public view returns (uint256) { return amountRaised.mul(TENPOW18).div(tokenSupply); } /// @notice Token price decreases at this rate during auction. function priceGradient() public view returns (uint256) { uint256 numerator = startPrice.sub(minimumPrice); uint256 denominator = endDate.sub(startDate); return numerator.div(denominator); } /// @notice Returns price during the auction function priceFunction() public view returns (uint256) { /// @dev Return Auction Price if (now <= startDate) { return startPrice; } if (now >= endDate) { return minimumPrice; } uint256 priceDiff = now.sub(startDate).mul(priceGradient()); uint256 price = startPrice.sub(priceDiff); return price; } /// @notice The current clearing price of the Dutch auction function clearingPrice() public view returns (uint256) { /// @dev If auction successful, return tokenPrice if (tokenPrice() > priceFunction()) { return tokenPrice(); } return priceFunction(); } /// @notice How many tokens the user is able to claim function tokensClaimable(address _user) public view returns (uint256) { return commitments[_user].mul(TENPOW18).div(clearingPrice()); } /// @notice Total amount of tokens committed at current auction price function totalTokensCommitted() public view returns(uint256) { return amountRaised.mul(TENPOW18).div(clearingPrice()); } /// @notice Successful if tokens sold equals tokenSupply function auctionSuccessful() public view returns (bool){ return totalTokensCommitted() >= tokenSupply && tokenPrice() >= minimumPrice; } /// @notice Returns bool if successful or time has ended function auctionEnded() public view returns (bool){ return auctionSuccessful() || now > endDate; } //-------------------------------------------------------- // Commit to buying tokens //-------------------------------------------------------- /// @notice Buy Tokens by committing ETH to this contract address receive () external payable { commitEth(msg.sender); } /// @notice Commit ETH to buy tokens on sale function commitEth (address payable _from) public payable { require(address(paymentCurrency) == ETH_ADDRESS); // Get ETH able to be committed uint256 ethToTransfer = calculateCommitment( msg.value); // Accept ETH Payments uint256 ethToRefund = msg.value.sub(ethToTransfer); if (ethToTransfer > 0) { addCommitment(_from, ethToTransfer); } // Return any ETH to be refunded if (ethToRefund > 0) { _from.transfer(ethToRefund); } } /// @notice Commits to an amount during an auction function addCommitment(address _addr, uint256 _commitment) internal { require(now >= startDate && now <= endDate); commitments[_addr] = commitments[_addr].add(_commitment); amountRaised = amountRaised.add(_commitment); emit AddedCommitment(_addr, _commitment, tokenPrice()); } /// @notice Commit approved ERC20 tokens to buy tokens on sale function commitTokens (uint256 _amount) public { commitTokensFrom(msg.sender, _amount); } /// @dev Users must approve contract prior to committing tokens to auction function commitTokensFrom (address _from, uint256 _amount) public { require(address(paymentCurrency) != ETH_ADDRESS); uint256 tokensToTransfer = calculateCommitment( _amount); if (tokensToTransfer > 0) { require(IERC20(paymentCurrency).transferFrom(_from, address(this), _amount)); addCommitment(_from, tokensToTransfer); } } /// @notice Returns the amout able to be committed during an auction function calculateCommitment( uint256 _commitment) public view returns (uint256 committed) { uint256 maxCommitment = tokenSupply.mul(clearingPrice()).div(TENPOW18); if (amountRaised.add(_commitment) > maxCommitment) { return maxCommitment.sub(amountRaised); } return _commitment; } //-------------------------------------------------------- // Finalise Auction //-------------------------------------------------------- /// @notice Auction finishes successfully above the reserve /// @dev Transfer contract funds to initialised wallet. function finaliseAuction () public { require(!finalised); finalised = true; /// @notice Auction did not meet reserve price. if( auctionEnded() && tokenPrice() < minimumPrice ) { _tokenPayment(auctionToken, wallet, tokenSupply); return; } /// @notice Successful auction! Transfer tokens bought. if (auctionSuccessful()) { _tokenPayment(paymentCurrency, wallet, amountRaised); } } /// @notice Withdraw your tokens once the Auction has ended. function withdrawTokens() public { uint256 fundsCommitted = commitments[ msg.sender]; uint256 tokensToClaim = tokensClaimable(msg.sender); commitments[ msg.sender] = 0; /// @notice Auction did not meet reserve price. /// @dev Return committed funds back to user. if( auctionEnded() && tokenPrice() < minimumPrice ) { _tokenPayment(paymentCurrency, msg.sender, fundsCommitted); return; } /// @notice Successful auction! Transfer tokens bought. /// @dev AG: Should hold and distribute tokens vs mint /// @dev AG: Could be only > min to allow early withdraw if (auctionSuccessful() && tokensToClaim > 0 ) { _tokenPayment(auctionToken, msg.sender, tokensToClaim); } } /// @dev Helper function to handle both ETH and ERC20 payments function _tokenPayment(IERC20 _token, address payable _to, uint256 _amount) internal { if (address(_token) == ETH_ADDRESS) { _to.transfer(_amount); } else { require(_token.transfer(_to, _amount)); } } }
Users must approve contract prior to committing tokens to auction
function commitTokensFrom (address _from, uint256 _amount) public { require(address(paymentCurrency) != ETH_ADDRESS); uint256 tokensToTransfer = calculateCommitment( _amount); if (tokensToTransfer > 0) { require(IERC20(paymentCurrency).transferFrom(_from, address(this), _amount)); addCommitment(_from, tokensToTransfer); } }
12,812,464
./full_match/1/0xDf7D56E526eD37834be0e4D2C8aecE552f54cFea/sources/contracts/BaseSmartVaultDeployer.sol
Create and setup action Set holder token out Set holder max slippage Transfer admin permissions to admin Authorize action to wrap and swap from Smart Vault
function _setupHolderAction(SmartVault smartVault, HolderActionParams memory params) internal { Holder holder = Holder(params.impl); Deployer.setupBaseAction(holder, params.admin, address(smartVault)); address[] memory executors = Arrays.from(params.admin, params.managers, new address[](0)); Deployer.setupActionExecutors(holder, executors, holder.call.selector); Deployer.setupTokenThresholdAction(holder, params.admin, params.tokenThresholdActionParams); holder.authorize(params.admin, holder.setTokenOut.selector); holder.authorize(address(this), holder.setTokenOut.selector); holder.setTokenOut(params.tokenOut); holder.unauthorize(address(this), holder.setTokenOut.selector); holder.authorize(params.admin, holder.setMaxSlippage.selector); holder.authorize(address(this), holder.setMaxSlippage.selector); holder.setMaxSlippage(params.maxSlippage); holder.unauthorize(address(this), holder.setMaxSlippage.selector); Deployer.transferAdminPermissions(holder, params.admin); smartVault.authorize(address(holder), smartVault.wrap.selector); smartVault.authorize(address(holder), smartVault.swap.selector); }
17,182,576