file_name
stringlengths
71
779k
comments
stringlengths
0
29.4k
code_string
stringlengths
20
7.69M
__index_level_0__
int64
2
17.2M
pragma solidity ^0.5.0; import "./library/EIP20.sol"; import "./library/SafeMath.sol"; import "./library/Division.sol"; import "./library/Ownable.sol"; /** @title Bonded Curve Implementation of an ERC20 token @author Team: Jessica Marshall, Ashoka Finley @notice This contract implements functionality to be controlled by a TokenRegistry & a ReputationRegistry. @dev This contract must be initialized with both a TokenRegistry & a ReputationRegistry. */ contract HyphaToken is EIP20(0, "Hypha Utility Token", 18, "HYP"), Ownable { using SafeMath for uint256; // ===================================================================== // EVENTS // ===================================================================== event LogMint(uint256 amountMinted, uint256 totalCost, address minter); event LogSell(uint256 amounSold, uint256 totalCost, address seller); // ===================================================================== // STATE VARIABLES // ===================================================================== address tokenRegistryAddress; address reputationRegistryAddress; uint256 public weiBal; // .00005 ether uint256 public baseCost = 50000000000000; bool public freeze; // ===================================================================== // MODIFIERS // ===================================================================== modifier onlyTR() { require(msg.sender == tokenRegistryAddress); _; } modifier onlyTRorRR() { require( msg.sender == tokenRegistryAddress || msg.sender == reputationRegistryAddress ); _; } // ===================================================================== // CONSTRUCTOR // ===================================================================== /** @dev Initialize the HyphaToken contract with the address of a TokenRegistry contract & a ReputationRegistry contract @param _tokenRegistry Address of the TokenRegistry @param _reputationRegistry Address of the ReputationRegistry */ constructor (address _tokenRegistry, address _reputationRegistry) public { require(tokenRegistryAddress == address(0) && reputationRegistryAddress == address(0)); tokenRegistryAddress = _tokenRegistry; reputationRegistryAddress = _reputationRegistry; } // ===================================================================== // OWNABLE // ===================================================================== /** * @dev Freezes the hypha token contract and allows existing token holders to withdraw tokens */ function freezeContract() external onlyOwner { freeze = true; } /** * @dev Unfreezes the hypha token contract and allows existing token holders to withdraw tokens */ function unfreezeContract() external onlyOwner { freeze = false; } /** * @dev Update the address of the token registry * @param _newTokenRegistry Address of the new token registry */ function updateTokenRegistry(address _newTokenRegistry) external onlyOwner { tokenRegistryAddress = _newTokenRegistry; } /** * @dev Update the address of the reputation registry * @param _newReputationRegistry Address of the new reputation registry */ function updateReputationRegistry(address _newReputationRegistry) external onlyOwner { reputationRegistryAddress = _newReputationRegistry; } // ===================================================================== // UTILITY // ===================================================================== /** @notice Returns the current sell price of a token calculated as the contract wei balance divided by the token supply @return The current sell price of 1 token in wei */ function currentPrice() public view returns (uint256) { //calculated current burn reward of 1 token at current weiBal and token supply if (weiBal == 0 || totalSupply == 0) { return baseCost; } // If totalTokenSupply is greater than weiBal this will fail uint256 price = weiBal.div(totalSupply); // added SafeMath return price < baseCost ? baseCost : price; } /** @notice Return the wei required to mint `_tokens` tokens @dev Calulates the target price and multiplies it by the number of tokens desired @dev A helper function to provide clarity for mint() @param _tokens The number of tokens requested to be minted @return The wei required to purchase the given amount of tokens */ function weiRequired(uint256 _tokens) public view returns (uint256) { require(_tokens > 0); return targetPrice(_tokens).mul(_tokens); } /** @notice Calulates the price of `_tokens` tokens dependent on the market share that `_tokens` tokens represent. @dev A helper function to provide clarity for weiRequired() @param _tokens The number of tokens requested to be minted @return The target price of the amount of tokens requested */ function targetPrice(uint _tokens) internal view returns (uint256) { uint256 cp = currentPrice(); uint256 newSupply = totalSupply.add(_tokens); return cp * (1000 + Division.percent(_tokens, newSupply, 3)) / 1000; // does this need SafeMath? } // ===================================================================== // TOKEN // ===================================================================== /** @notice Mint `_tokens` tokens, add `_tokens` to the contract totalSupply and add the weiRequired to the contract weiBalance @dev The required amount of wei must be transferred as the msg.value @param _tokens The number of tokens requested to be minted */ function mint(uint _tokens) external payable { require(!freeze); uint256 weiRequiredVal = weiRequired(_tokens); require(msg.value >= weiRequiredVal); totalSupply = totalSupply.add(_tokens); balances[msg.sender] = balances[msg.sender].add(_tokens); weiBal = weiBal.add(weiRequiredVal); emit LogMint(_tokens, weiRequiredVal, msg.sender); uint256 fundsLeft = msg.value.sub(weiRequiredVal); if (fundsLeft > 0) { msg.sender.transfer(fundsLeft); } } /** @notice Burn `_tokens` tokens by removing them from the total supply, and from the Token Registry balance. @dev Only to be called by the Token Registry initialized during construction @param _tokens The number of tokens to burn */ function burn(uint256 _tokens) external onlyTR { require(!freeze); require(_tokens <= totalSupply && _tokens > 0); balances[msg.sender] = balances[msg.sender].sub(_tokens); totalSupply = totalSupply.sub(_tokens); } /** @notice Sell `_tokens` tokens at the current token price. @dev Checks that `_tokens` is greater than 0 and that `msg.sender` has sufficient balance. The corresponding amount of wei is transferred to the `msg.sender` @param _tokens The number of tokens to sell. */ function sell(uint256 _tokens) external { require(_tokens > 0 && (_tokens <= balances[msg.sender])); uint256 weiVal = _tokens * currentPrice(); balances[msg.sender] = balances[msg.sender].sub(_tokens); totalSupply = totalSupply.sub(_tokens); weiBal = weiBal.sub(weiVal); emit LogSell(_tokens, weiVal, msg.sender); msg.sender.transfer(weiVal); } // ===================================================================== // TRANSFER // ===================================================================== /** @notice Transfer `_weiValue` wei to `_address` // check where this is used and add that here @dev Only callable by the TokenRegistry or ReputationRegistry initialized during contract construction @param _address Recipient of wei value @param _weiValue The amount of wei to transfer to the _address */ function transferWeiTo(address payable _address, uint256 _weiValue) external onlyTRorRR { require(!freeze); require(_weiValue <= weiBal); weiBal = weiBal.sub(_weiValue); _address.transfer(_weiValue); } /** @notice Transfer `_tokens` wei to `_address` // check where this is used and add that here @dev Only callable by the TokenRegistry initialized during contract construction @param _address Recipient of tokens @param _tokens The amount of tokens to transfer to the _address */ function transferTokensTo(address _address, uint256 _tokens) external onlyTR { totalSupply = totalSupply.add(_tokens); balances[_address] = balances[_address].add(_tokens); } /** @notice Return `_weiValue` wei back to Hypha Token contract @dev Only callable by the TokenRegistry initialized during contract construction @param _weiValue The amount of wei to transfer back to the token contract */ function returnWei(uint _weiValue) external onlyTR { require(!freeze); weiBal = weiBal.add(_weiValue); } /** @notice Transfer `_tokens` tokens from the balance of `_owner` to the TokenRegistry escrow @dev Only callable by the TokenRegistry initialized during contract construction @param _owner Owner of the tokens being transferred @param _tokens The number of tokens to transfer */ function transferToEscrow(address _owner, uint256 _tokens) external onlyTR returns (bool) { require(!freeze); require(balances[_owner] >= _tokens); balances[_owner] = balances[_owner].sub(_tokens); balances[tokenRegistryAddress] = balances[tokenRegistryAddress].add(_tokens); return true; } /** @notice Transfer `_tokens` tokens from the TokenRegistry escrow to the balance of `_` @dev Only callable by the TokenRegistry initialized during contract construction @param _receipient address of where the tokens being transferred @param _tokens The number of tokens to transfer */ function transferFromEscrow(address _receipient, uint256 _tokens) external onlyTR returns (bool) { require(!freeze); require(balances[msg.sender] >= _tokens); balances[msg.sender] = balances[msg.sender].sub(_tokens); balances[_receipient] = balances[_receipient].add(_tokens); return true; } // ===================================================================== // FALLBACK // ===================================================================== function() external payable {} }
Unfreezes the hypha token contract and allows existing token holders to withdraw tokens/
function unfreezeContract() external onlyOwner { freeze = false; }
12,783,491
//Address: 0x2998328a3a0c95b6beb64c694b6b60aba386cf98 //Contract name: YRXCrowdsale //Balance: 0 Ether //Verification Date: 1/9/2018 //Transacion Count: 13 // CODE STARTS HERE pragma solidity ^0.4.18; /** * @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 ERC20Basic * @dev Simpler version of ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/179 */ contract ERC20Basic { uint256 public totalSupply; function balanceOf(address who) public view returns (uint256); function transfer(address to, uint256 value) public returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); } /** * @title ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/20 */ contract ERC20 is ERC20Basic { function allowance(address owner, address spender) public view returns (uint256); function transferFrom(address from, address to, uint256 value) public returns (bool); function approve(address spender, uint256 value) public returns (bool); event Approval(address indexed owner, address indexed spender, uint256 value); } pragma solidity ^0.4.18; /** * @title Basic token * @dev Basic version of StandardToken, with no allowances. */ contract BasicToken is ERC20Basic { using SafeMath for uint256; mapping(address => uint256) balances; /** * @dev transfer token for a specified address * @param _to The address to transfer to. * @param _value The amount to be transferred. */ function transfer(address _to, uint256 _value) public returns (bool) { require(_to != address(0)); require(_value <= balances[msg.sender]); // SafeMath.sub will throw if there is not enough balance. balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); Transfer(msg.sender, _to, _value); return true; } /** * @dev Gets the balance of the specified address. * @param _owner The address to query the the balance of. * @return An uint256 representing the amount owned by the passed address. */ function balanceOf(address _owner) public view returns (uint256 balance) { return balances[_owner]; } } /** * @title Standard ERC20 token * * @dev Implementation of the basic standard token. * @dev https://github.com/ethereum/EIPs/issues/20 * @dev Based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol */ contract StandardToken is ERC20, BasicToken { mapping (address => mapping (address => uint256)) internal allowed; /** * @dev Transfer tokens from one address to another * @param _from address The address which you want to send tokens from * @param _to address The address which you want to transfer to * @param _value uint256 the amount of tokens to be transferred */ function transferFrom(address _from, address _to, uint256 _value) public returns (bool) { require(_to != address(0)); require(_value <= balances[_from]); require(_value <= allowed[_from][msg.sender]); balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); Transfer(_from, _to, _value); return true; } /** * @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender. * * Beware that changing an allowance with this method brings the risk that someone may use both the old * and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this * race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * @param _spender The address which will spend the funds. * @param _value The amount of tokens to be spent. */ function approve(address _spender, uint256 _value) public returns (bool) { allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); return true; } /** * @dev Function to check the amount of tokens that an owner allowed to a spender. * @param _owner address The address which owns the funds. * @param _spender address The address which will spend the funds. * @return A uint256 specifying the amount of tokens still available for the spender. */ function allowance(address _owner, address _spender) public view returns (uint256) { return allowed[_owner][_spender]; } /** * approve should be called when allowed[_spender] == 0. To increment * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol */ function increaseApproval(address _spender, uint _addedValue) public returns (bool) { allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue); Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } function decreaseApproval(address _spender, uint _subtractedValue) public returns (bool) { uint oldValue = allowed[msg.sender][_spender]; if (_subtractedValue > oldValue) { allowed[msg.sender][_spender] = 0; } else { allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue); } Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } } /** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */ contract Ownable { address public owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ function Ownable() public { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) public onlyOwner { require(newOwner != address(0)); OwnershipTransferred(owner, newOwner); owner = newOwner; } } /** * @title Mintable token * @dev Simple ERC20 Token example, with mintable token creation * @dev Issue: * https://github.com/OpenZeppelin/zeppelin-solidity/issues/120 * Based on code by TokenMarketNet: https://github.com/TokenMarketNet/ico/blob/master/contracts/MintableToken.sol */ contract MintableToken is StandardToken, Ownable { event Mint(address indexed to, uint256 amount); event MintFinished(); bool public mintingFinished = false; modifier canMint() { require(!mintingFinished); _; } /** * @dev Function to mint tokens * @param _to The address that will receive the minted tokens. * @param _amount The amount of tokens to mint. * @return A boolean that indicates if the operation was successful. */ function mint(address _to, uint256 _amount) onlyOwner canMint public returns (bool) { totalSupply = totalSupply.add(_amount); balances[_to] = balances[_to].add(_amount); Mint(_to, _amount); Transfer(address(0), _to, _amount); return true; } /** * @dev Function to stop minting new tokens. * @return True if the operation was successful. */ function finishMinting() onlyOwner canMint public returns (bool) { mintingFinished = true; MintFinished(); return true; } } /** * @title YRXToken * @dev ERC20 based Token, where all tokens are pre-assigned to the creator. * Note they can later distribute these tokens as they wish using `transfer` and other * `StandardToken` functions. */ contract YRXToken is MintableToken { string public constant name = "Yoritex Token"; string public constant symbol = "YRX"; uint8 public constant decimals = 18; address public crowdsaleAddress; uint256 public constant INITIAL_SUPPLY = 510000000 * 1 ether; modifier nonZeroAddress(address _to) { // Ensures an address is provided require(_to != 0x0); _; } modifier nonZeroAmount(uint _amount) { // Ensures a non-zero amount require(_amount > 0); _; } modifier nonZeroValue() { // Ensures a non-zero value is passed require(msg.value > 0); _; } modifier onlyCrowdsale() { // Ensures only crowdfund can call the function require(msg.sender == crowdsaleAddress); _; } /** * @dev Constructor that gives msg.sender all of existing tokens. */ function YRXToken() public { totalSupply = INITIAL_SUPPLY; balances[msg.sender] = totalSupply; } // ------------------------------------------------- // Sets the crowdsale address, can only be done once // ------------------------------------------------- function setCrowdsaleAddress(address _crowdsaleAddress) external onlyOwner nonZeroAddress(_crowdsaleAddress) returns (bool success){ require(crowdsaleAddress == 0x0); crowdsaleAddress = _crowdsaleAddress; decrementBalance(owner, totalSupply); addToBalance(crowdsaleAddress, totalSupply); Transfer(0x0, _crowdsaleAddress, totalSupply); return true; } // ------------------------------------------------- // Function for the Crowdsale to transfer tokens // ------------------------------------------------- function transferFromCrowdsale(address _to, uint256 _amount) external onlyCrowdsale nonZeroAmount(_amount) nonZeroAddress(_to) returns (bool success) { require(balanceOf(crowdsaleAddress) >= _amount); decrementBalance(crowdsaleAddress, _amount); addToBalance(_to, _amount); Transfer(0x0, _to, _amount); return true; } // ------------------------------------------------- // Adds to balance // ------------------------------------------------- function addToBalance(address _address, uint _amount) internal { balances[_address] = balances[_address].add(_amount); } // ------------------------------------------------- // Removes from balance // ------------------------------------------------- function decrementBalance(address _address, uint _amount) internal { balances[_address] = balances[_address].sub(_amount); } } /** * @title YRXCrowdsale */ contract YRXCrowdsale is Ownable { using SafeMath for uint256; // true for finalised presale bool public isPreSaleFinalised; // true for finalised crowdsale bool public isFinalised; // The token being sold YRXToken public YRX; // address where funds are collected address public wallet; // amount of raised money in wei uint256 public weiRaised; // current amount of purchased tokens for pre-sale and main sale uint256 public preSaleTotalSupply; uint256 public mainSaleTotalSupply; // current amount of minted tokens for bounty uint256 public bountyTotalSupply; uint256 private mainSaleTokensExtra; event WalletAddressChanged(address _wallet); // Triggered upon owner changing the wallet address event AmountRaised(address beneficiary, uint amountRaised); // Triggered upon crowdfund being finalized event Mint(address indexed to, uint256 amount); /** * event for token purchase logging * @param purchaser who paid for the tokens * @param beneficiary who got the tokens * @param value weis paid for purchase * @param amount amount of tokens purchased */ event TokenPurchase(address indexed purchaser, address indexed beneficiary, uint256 value, uint256 amount); modifier nonZeroAddress(address _to) { // Ensures an address is provided require(_to != 0x0); _; } modifier nonZeroAmount(uint _amount) { // Ensures a non-zero amount require(_amount > 0); _; } modifier nonZeroValue() { // Ensures a non-zero value is passed require(msg.value > 0); _; } modifier crowdsaleIsActive() { // Ensures the crowdfund is ongoing require(!isFinalised && (isInPreSale() || isInMainSale())); _; } function YRXCrowdsale(address _wallet, address _token) public { /* default start-end periods dates _preSaleStartTime = '29 Nov 2017 00:00:00 GMT' 1511913600 _preSaleEndTime = '10 Jan 2018 23:59:59 GMT' 1515628799 _mainSaleStartTime = '11 Jan 2018 00:00:00 GMT' 1515628800 _mainSaleEndTime = '11 May 2018 00:00:00 GMT' 1525996800 */ // check dates require(mainSaleStartTime() >= now); // can't start main sale in the past require(preSaleEndTime() < mainSaleStartTime()); // can't start main sale before the end of pre-sale require(preSaleStartTime() < preSaleEndTime()); // the end of pre-sale can't happen before it's start require(mainSaleStartTime() < mainSaleEndTime()); // the end of main sale can't happen before it's start // create token contract YRX = YRXToken(_token); wallet = _wallet; isPreSaleFinalised = false; isFinalised = false; // current amount of purchased tokens for pre-sale and main sale preSaleTotalSupply = 0; mainSaleTotalSupply = 0; bountyTotalSupply = 0; mainSaleTokensExtra = 0; } // ------------------------------------------------- // Changes main contribution wallet // ------------------------------------------------- function changeWalletAddress(address _wallet) external onlyOwner { wallet = _wallet; WalletAddressChanged(_wallet); } function maxTokens() public pure returns(uint256) { return 510000000 * 1 ether; } function preSaleMaxTokens() public pure returns(uint256) { return 51000000 * 1 ether; } function mainSaleMaxTokens() public view returns(uint256) { return 433500000 * 1 ether + mainSaleTokensExtra; } function bountyMaxTokens() public pure returns(uint256) { return 25500000 * 1 ether; } function preSaleStartTime() public pure returns(uint256) { return 1511913600; } function preSaleEndTime() public pure returns(uint256) { return 1515628799; } function mainSaleStartTime() public pure returns(uint256) { return 1515628800; } function mainSaleEndTime() public pure returns(uint256) { return 1525996800; } function rate() public pure returns(uint256) { return 540; } function discountRate() public pure returns(uint256) { return 1350; } function discountICO() public pure returns(uint256) { return 60; } function isInPreSale() public constant returns(bool){ return now >= preSaleStartTime() && now <= preSaleEndTime(); } function isInMainSale() public constant returns(bool){ return now >= mainSaleStartTime() && now <= mainSaleEndTime(); } function totalSupply() public view returns(uint256){ return YRX.totalSupply(); } // fallback function can be used to buy tokens function () public payable { buyTokens(msg.sender); } // low level token purchase function function buyTokens(address beneficiary) public crowdsaleIsActive nonZeroAddress(beneficiary) nonZeroValue payable { uint256 weiAmount = msg.value; // calculate token amount to be created uint256 tokens = weiAmount * rate(); if (isInPreSale()) { require(!isPreSaleFinalised); tokens = weiAmount * discountRate(); require(tokens <= preSaleTokenLeft()); } if (isInMainSale()) { // tokens with discount tokens = weiAmount * discountRate(); require(mainSaleTotalSupply + tokens <= mainSaleMaxTokens()); } // update state weiRaised = weiRaised.add(weiAmount); if (isInPreSale()) preSaleTotalSupply += tokens; if (isInMainSale()) mainSaleTotalSupply += tokens; forwardFunds(); if (!YRX.transferFromCrowdsale(beneficiary, tokens)) {revert();} TokenPurchase(msg.sender, beneficiary, weiAmount, tokens); } // send ether to the fund collection wallet function forwardFunds() internal { wallet.transfer(msg.value); } // mint tokens to beneficiary function mint(address beneficiary, uint256 amount) public onlyOwner crowdsaleIsActive nonZeroAddress(beneficiary) nonZeroAmount(amount) { // check period bool withinPreSalePeriod = isInPreSale(); bool withinMainSalePeriod = isInMainSale(); if (withinPreSalePeriod) { require(!isPreSaleFinalised); require(amount <= preSaleTokenLeft()); } if (withinMainSalePeriod) { require(amount <= (mainSaleMaxTokens() - mainSaleTotalSupply)); } if (withinPreSalePeriod) preSaleTotalSupply += amount; if (withinMainSalePeriod) mainSaleTotalSupply += amount; if (!YRX.transferFromCrowdsale(beneficiary, amount)) {revert();} Mint(beneficiary, amount); } function preSaleTokenLeft() public constant returns(uint256){ return preSaleMaxTokens() - preSaleTotalSupply; } // finalise presale function finalisePreSale() public onlyOwner { require(!isFinalised); require(!isPreSaleFinalised); require(now >= preSaleStartTime()); // can finalise presale only after it starts if (preSaleTokenLeft() > 0) { mainSaleTokensExtra = preSaleTokenLeft(); } isPreSaleFinalised = true; } // finalase crowdsale (mainsale) function finalise() public onlyOwner returns(bool success){ require(!isFinalised); require(now >= mainSaleStartTime()); // can finalise mainsale (crowdsale) only after it starts AmountRaised(wallet, weiRaised); isFinalised = true; return true; } // mint bounty tokens to beneficiary function mintBounty(address beneficiary, uint256 amount) public onlyOwner crowdsaleIsActive nonZeroAddress(beneficiary) nonZeroAmount(amount) { require(amount <= (bountyMaxTokens() - bountyTotalSupply)); bountyTotalSupply += amount; if (!YRX.transferFromCrowdsale(beneficiary, amount)) {revert();} Mint(beneficiary, amount); } }
------------------------------------------------- Adds to balance -------------------------------------------------
function addToBalance(address _address, uint _amount) internal { balances[_address] = balances[_address].add(_amount); }
14,101,250
./full_match/5/0xEf8F1fe8918eB5BB70853F2dF2cAC85626d6FB56/sources/project_/contracts/base/modules/Whitelist.sol
(1) Checks if the address is in the whitelist. _address Address to be checked _merkleProof Merkle proof/
function isInWhitelist(address _address, bytes32[] calldata _merkleProof) public view returns (bool) { bytes32 leaf = keccak256(abi.encode(_address)); return MerkleProof.verifyCalldata(_merkleProof, merkleRoot, leaf); }
7,035,598
./partial_match/61/0x59E34EF31049565D041Aec6137F40f518c2D47c1/sources/contracts/MyToken.sol
Return the total supply of NFTReturn the corresponding ‘tokenId’ through ‘_index’Return the ‘tokenId’ corresponding to the index in the NFT list owned by the ‘_owner'
interface IERC721Enumerable { function totalSupply() external view returns (uint256); function tokenByIndex(uint256 _index) external view returns (uint256); function tokenOfOwnerByIndex(address _owner, uint256 _index) external view returns (uint256); }
16,910,540
./partial_match/1/0x9781C4E9B9cc6Ac18405891DF20Ad3566FB6B301/sources/SavingsManager.sol
Calculates unclaimed rewards from the liquidation stream _mAsset mAsset key _previousCollection Time of previous collection return Units of mAsset that have been unlocked for distribution/
function _unclaimedRewards(address _mAsset, uint256 _previousCollection) internal view returns (uint256) { Stream memory liq = liqStream[_mAsset]; uint256 unclaimedSeconds_liq = _unclaimedSeconds(_previousCollection, liq.end); uint256 subtotal_liq = unclaimedSeconds_liq.mul(liq.rate); Stream memory yield = yieldStream[_mAsset]; uint256 unclaimedSeconds_yield = _unclaimedSeconds(_previousCollection, yield.end); uint256 subtotal_yield = unclaimedSeconds_yield.mul(yield.rate); return subtotal_liq.add(subtotal_yield); }
16,112,400
// File: @openzeppelin/contracts/utils/Counters.sol // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @title Counters * @author Matt Condon (@shrugs) * @dev Provides counters that can only be incremented, decremented or reset. This can be used e.g. to track the number * of elements in a mapping, issuing ERC721 ids, or counting request ids. * * Include with `using Counters for Counters.Counter;` */ library Counters { struct Counter { // This variable should never be directly accessed by users of the library: interactions must be restricted to // the library's function. As of Solidity v0.5.2, this cannot be enforced, though there is a proposal to add // this feature: see https://github.com/ethereum/solidity/issues/4637 uint256 _value; // default: 0 } function current(Counter storage counter) internal view returns (uint256) { return counter._value; } function increment(Counter storage counter) internal { unchecked { counter._value += 1; } } function decrement(Counter storage counter) internal { uint256 value = counter._value; require(value > 0, "Counter: decrement overflow"); unchecked { counter._value = value - 1; } } function reset(Counter storage counter) internal { counter._value = 0; } } // File: @openzeppelin/contracts/access/Ownable.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; } } pragma solidity ^0.8.0; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() { _setOwner(_msgSender()); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { _setOwner(address(0)); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); _setOwner(newOwner); } function _setOwner(address newOwner) private { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } } // File: @openzeppelin/contracts/token/ERC721/extensions/ERC721URIStorage.sol // File: @openzeppelin/contracts/token/ERC721/extensions/IERC721Enumerable.sol pragma solidity ^0.8.0; // File: @openzeppelin/contracts/utils/introspection/IERC165.sol pragma solidity ^0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // File: @openzeppelin/contracts/utils/introspection/ERC165.sol pragma solidity ^0.8.0; /** * @dev Implementation of the {IERC165} interface. * * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check * for the additional interface id that will be supported. For example: * * ```solidity * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId); * } * ``` * * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation. */ abstract contract ERC165 is IERC165 { /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165).interfaceId; } } // File: @openzeppelin/contracts/utils/Strings.sol pragma solidity ^0.8.0; /** * @dev String operations. */ library Strings { bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef"; /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0x00"; } uint256 temp = value; uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return toHexString(value, length); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = _HEX_SYMBOLS[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } } // File: @openzeppelin/contracts/utils/Context.sol // File: @openzeppelin/contracts/utils/Address.sol pragma solidity ^0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); (bool success, bytes memory returndata) = target.delegatecall(data); return _verifyCallResult(success, returndata, errorMessage); } 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); } } } } // File: @openzeppelin/contracts/token/ERC721/IERC721Receiver.sol pragma solidity ^0.8.0; /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ interface IERC721Receiver { /** * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom} * by `operator` from `from`, this function is called. * * It must return its Solidity selector to confirm the token transfer. * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted. * * The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`. */ function onERC721Received( address operator, address from, uint256 tokenId, bytes calldata data ) external returns (bytes4); } // File: @openzeppelin/contracts/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/IERC721Metadata.sol pragma solidity ^0.8.0; /** * @title ERC-721 Non-Fungible Token Standard, optional metadata extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Metadata is IERC721 { /** * @dev Returns the token collection name. */ function name() external view returns (string memory); /** * @dev Returns the token collection symbol. */ function symbol() external view returns (string memory); /** * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token. */ function tokenURI(uint256 tokenId) external view returns (string memory); } /** * @title ERC-721 Non-Fungible Token Standard, optional enumeration extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Enumerable is IERC721 { /** * @dev Returns the total amount of tokens stored by the contract. */ function totalSupply() external view returns (uint256); /** * @dev Returns a token ID owned by `owner` at a given `index` of its token list. * Use along with {balanceOf} to enumerate all of ``owner``'s tokens. */ function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 tokenId); /** * @dev Returns a token ID at a given `index` of all the tokens stored by the contract. * Use along with {totalSupply} to enumerate all tokens. */ function tokenByIndex(uint256 index) external view returns (uint256); } // File: @openzeppelin/contracts/token/ERC721/extensions/ERC721Enumerable.sol pragma solidity ^0.8.0; // File: @openzeppelin/contracts/token/ERC721/ERC721.sol pragma solidity ^0.8.0; /** * @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including * the Metadata extension, but not including the Enumerable extension, which is available separately as * {ERC721Enumerable}. */ contract ERC721 is Context, ERC165, IERC721, IERC721Metadata { using Address for address; using Strings for uint256; // Token name string private _name; // Token symbol string private _symbol; // Mapping from token ID to owner address mapping(uint256 => address) private _owners; // Mapping owner address to token count mapping(address => uint256) private _balances; // Mapping from token ID to approved address mapping(uint256 => address) private _tokenApprovals; // Mapping from owner to operator approvals mapping(address => mapping(address => bool)) private _operatorApprovals; /** * @dev Initializes the contract by setting a `name` and a `symbol` to the token collection. */ constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { return interfaceId == type(IERC721).interfaceId || interfaceId == type(IERC721Metadata).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) public view virtual override returns (uint256) { require(owner != address(0), "ERC721: balance query for the zero address"); return _balances[owner]; } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view virtual override returns (address) { address owner = _owners[tokenId]; require(owner != address(0), "ERC721: owner query for nonexistent token"); return owner; } /** * @dev See {IERC721Metadata-name}. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev See {IERC721Metadata-symbol}. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); string memory baseURI = _baseURI(); return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : ""; } /** * @dev Base URI for computing {tokenURI}. If set, the resulting URI for each * token will be the concatenation of the `baseURI` and the `tokenId`. Empty * by default, can be overriden in child contracts. */ function _baseURI() internal view virtual returns (string memory) { return ""; } /** * @dev See {IERC721-approve}. */ function approve(address to, uint256 tokenId) public virtual override { address owner = ERC721.ownerOf(tokenId); require(to != owner, "ERC721: approval to current owner"); require( _msgSender() == owner || isApprovedForAll(owner, _msgSender()), "ERC721: approve caller is not owner nor approved for all" ); _approve(to, tokenId); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view virtual override returns (address) { require(_exists(tokenId), "ERC721: approved query for nonexistent token"); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { require(operator != _msgSender(), "ERC721: approve to caller"); _operatorApprovals[_msgSender()][operator] = approved; emit ApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC721-isApprovedForAll}. */ function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev See {IERC721-transferFrom}. */ function transferFrom( address from, address to, uint256 tokenId ) public virtual override { //solhint-disable-next-line max-line-length require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _transfer(from, to, tokenId); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId ) public virtual override { safeTransferFrom(from, to, tokenId, ""); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory _data ) public virtual override { require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _safeTransfer(from, to, tokenId, _data); } /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * `_data` is additional data, it has no specified format and it is sent in call to `to`. * * This internal function is equivalent to {safeTransferFrom}, and can be used to e.g. * implement alternative mechanisms to perform token transfer, such as signature-based. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeTransfer( address from, address to, uint256 tokenId, bytes memory _data ) internal virtual { _transfer(from, to, tokenId); require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); } /** * @dev Returns whether `tokenId` exists. * * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}. * * Tokens start existing when they are minted (`_mint`), * and stop existing when they are burned (`_burn`). */ function _exists(uint256 tokenId) internal view virtual returns (bool) { return _owners[tokenId] != address(0); } /** * @dev Returns whether `spender` is allowed to manage `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) { require(_exists(tokenId), "ERC721: operator query for nonexistent token"); address owner = ERC721.ownerOf(tokenId); return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender)); } /** * @dev Safely mints `tokenId` and transfers it to `to`. * * Requirements: * * - `tokenId` must not exist. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeMint(address to, uint256 tokenId) internal virtual { _safeMint(to, tokenId, ""); } /** * @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is * forwarded in {IERC721Receiver-onERC721Received} to contract recipients. */ function _safeMint( address to, uint256 tokenId, bytes memory _data ) internal virtual { _mint(to, tokenId); require( _checkOnERC721Received(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer" ); } /** * @dev Mints `tokenId` and transfers it to `to`. * * WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible * * Requirements: * * - `tokenId` must not exist. * - `to` cannot be the zero address. * * Emits a {Transfer} event. */ function _mint(address to, uint256 tokenId) internal virtual { require(to != address(0), "ERC721: mint to the zero address"); require(!_exists(tokenId), "ERC721: token already minted"); _beforeTokenTransfer(address(0), to, tokenId); _balances[to] += 1; _owners[tokenId] = to; emit Transfer(address(0), to, tokenId); } /** * @dev Destroys `tokenId`. * The approval is cleared when the token is burned. * * Requirements: * * - `tokenId` must exist. * * Emits a {Transfer} event. */ function _burn(uint256 tokenId) internal virtual { address owner = ERC721.ownerOf(tokenId); _beforeTokenTransfer(owner, address(0), tokenId); // Clear approvals _approve(address(0), tokenId); _balances[owner] -= 1; delete _owners[tokenId]; emit Transfer(owner, address(0), tokenId); } /** * @dev Transfers `tokenId` from `from` to `to`. * As opposed to {transferFrom}, this imposes no restrictions on msg.sender. * * Requirements: * * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * * Emits a {Transfer} event. */ function _transfer( address from, address to, uint256 tokenId ) internal virtual { require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own"); require(to != address(0), "ERC721: transfer to the zero address"); _beforeTokenTransfer(from, to, tokenId); // Clear approvals from the previous owner _approve(address(0), tokenId); _balances[from] -= 1; _balances[to] += 1; _owners[tokenId] = to; emit Transfer(from, to, tokenId); } /** * @dev Approve `to` to operate on `tokenId` * * Emits a {Approval} event. */ function _approve(address to, uint256 tokenId) internal virtual { _tokenApprovals[tokenId] = to; emit Approval(ERC721.ownerOf(tokenId), to, tokenId); } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address. * The call is not executed if the target address is not a contract. * * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function _checkOnERC721Received( address from, address to, uint256 tokenId, bytes memory _data ) private returns (bool) { if (to.isContract()) { try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) { return retval == IERC721Receiver(to).onERC721Received.selector; } catch (bytes memory reason) { if (reason.length == 0) { revert("ERC721: transfer to non ERC721Receiver implementer"); } else { assembly { revert(add(32, reason), mload(reason)) } } } } else { return true; } } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual {} } /** * @dev This implements an optional extension of {ERC721} defined in the EIP that adds * enumerability of all the token ids in the contract as well as all token ids owned by each * account. */ abstract contract ERC721Enumerable is ERC721, IERC721Enumerable { // Mapping from owner to list of owned token IDs mapping(address => mapping(uint256 => uint256)) private _ownedTokens; // Mapping from token ID to index of the owner tokens list mapping(uint256 => uint256) private _ownedTokensIndex; // Array with all token ids, used for enumeration uint256[] private _allTokens; // Mapping from token id to position in the allTokens array mapping(uint256 => uint256) private _allTokensIndex; /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(IERC165, ERC721) returns (bool) { return interfaceId == type(IERC721Enumerable).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721Enumerable-tokenOfOwnerByIndex}. */ function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual override returns (uint256) { require(index < ERC721.balanceOf(owner), "ERC721Enumerable: owner index out of bounds"); return _ownedTokens[owner][index]; } /** * @dev See {IERC721Enumerable-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _allTokens.length; } /** * @dev See {IERC721Enumerable-tokenByIndex}. */ function tokenByIndex(uint256 index) public view virtual override returns (uint256) { require(index < ERC721Enumerable.totalSupply(), "ERC721Enumerable: global index out of bounds"); return _allTokens[index]; } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` cannot be the zero address. * - `to` cannot be the zero address. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual override { super._beforeTokenTransfer(from, to, tokenId); if (from == address(0)) { _addTokenToAllTokensEnumeration(tokenId); } else if (from != to) { _removeTokenFromOwnerEnumeration(from, tokenId); } if (to == address(0)) { _removeTokenFromAllTokensEnumeration(tokenId); } else if (to != from) { _addTokenToOwnerEnumeration(to, tokenId); } } /** * @dev Private function to add a token to this extension's ownership-tracking data structures. * @param to address representing the new owner of the given token ID * @param tokenId uint256 ID of the token to be added to the tokens list of the given address */ function _addTokenToOwnerEnumeration(address to, uint256 tokenId) private { uint256 length = ERC721.balanceOf(to); _ownedTokens[to][length] = tokenId; _ownedTokensIndex[tokenId] = length; } /** * @dev Private function to add a token to this extension's token tracking data structures. * @param tokenId uint256 ID of the token to be added to the tokens list */ function _addTokenToAllTokensEnumeration(uint256 tokenId) private { _allTokensIndex[tokenId] = _allTokens.length; _allTokens.push(tokenId); } /** * @dev Private function to remove a token from this extension's ownership-tracking data structures. Note that * while the token is not assigned a new owner, the `_ownedTokensIndex` mapping is _not_ updated: this allows for * gas optimizations e.g. when performing a transfer operation (avoiding double writes). * This has O(1) time complexity, but alters the order of the _ownedTokens array. * @param from address representing the previous owner of the given token ID * @param tokenId uint256 ID of the token to be removed from the tokens list of the given address */ function _removeTokenFromOwnerEnumeration(address from, uint256 tokenId) private { // To prevent a gap in from's tokens array, we store the last token in the index of the token to delete, and // then delete the last slot (swap and pop). uint256 lastTokenIndex = ERC721.balanceOf(from) - 1; uint256 tokenIndex = _ownedTokensIndex[tokenId]; // When the token to delete is the last token, the swap operation is unnecessary if (tokenIndex != lastTokenIndex) { uint256 lastTokenId = _ownedTokens[from][lastTokenIndex]; _ownedTokens[from][tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token _ownedTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index } // This also deletes the contents at the last position of the array delete _ownedTokensIndex[tokenId]; delete _ownedTokens[from][lastTokenIndex]; } /** * @dev Private function to remove a token from this extension's token tracking data structures. * This has O(1) time complexity, but alters the order of the _allTokens array. * @param tokenId uint256 ID of the token to be removed from the tokens list */ function _removeTokenFromAllTokensEnumeration(uint256 tokenId) private { // To prevent a gap in the tokens array, we store the last token in the index of the token to delete, and // then delete the last slot (swap and pop). uint256 lastTokenIndex = _allTokens.length - 1; uint256 tokenIndex = _allTokensIndex[tokenId]; // When the token to delete is the last token, the swap operation is unnecessary. However, since this occurs so // rarely (when the last minted token is burnt) that we still do the swap here to avoid the gas cost of adding // an 'if' statement (like in _removeTokenFromOwnerEnumeration) uint256 lastTokenId = _allTokens[lastTokenIndex]; _allTokens[tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token _allTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index // This also deletes the contents at the last position of the array delete _allTokensIndex[tokenId]; _allTokens.pop(); } } pragma solidity ^0.8.0; /** * @dev ERC721 token with storage based token URI management. */ abstract contract ERC721URIStorage is ERC721 { using Strings for uint256; // Optional mapping for token URIs mapping(uint256 => string) private _tokenURIs; /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId), "ERC721URIStorage: URI query for nonexistent token"); string memory _tokenURI = _tokenURIs[tokenId]; string memory base = _baseURI(); // If there is no base URI, return the token URI. if (bytes(base).length == 0) { return _tokenURI; } // If both are set, concatenate the baseURI and tokenURI (via abi.encodePacked). if (bytes(_tokenURI).length > 0) { return string(abi.encodePacked(base, _tokenURI)); } return super.tokenURI(tokenId); } /** * @dev Sets `_tokenURI` as the tokenURI of `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function _setTokenURI(uint256 tokenId, string memory _tokenURI) internal virtual { require(_exists(tokenId), "ERC721URIStorage: URI set of nonexistent token"); _tokenURIs[tokenId] = _tokenURI; } /** * @dev Destroys `tokenId`. * The approval is cleared when the token is burned. * * Requirements: * * - `tokenId` must exist. * * Emits a {Transfer} event. */ function _burn(uint256 tokenId) internal virtual override { super._burn(tokenId); if (bytes(_tokenURIs[tokenId]).length != 0) { delete _tokenURIs[tokenId]; } } } pragma solidity 0.8.3; contract PizzaNFT is ERC721, ERC721Enumerable,ERC721URIStorage, Ownable { using Counters for Counters.Counter; Counters.Counter private _tokenIds; uint16 public constant maxSupply = 10000; string private _baseTokenURI; uint256 public _startDate = 1629658800; constructor() ERC721("Pizzeria Pizza", "PIZZA") { } function setStartDate(uint256 startDate) public onlyOwner { _startDate = startDate; } function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal override(ERC721, ERC721Enumerable) { super._beforeTokenTransfer(from, to, tokenId); } function _burn(uint256 tokenId) internal override(ERC721, ERC721URIStorage) { super._burn(tokenId); } function supportsInterface(bytes4 interfaceId) public view override(ERC721, ERC721Enumerable) returns (bool) { return super.supportsInterface(interfaceId); } function setBaseURI(string memory _newbaseTokenURI) public onlyOwner { _baseTokenURI = _newbaseTokenURI; } function _baseURI() internal view override returns (string memory) { return _baseTokenURI; } // Get minting limit (for a single transaction) based on current token supply function getCurrentMintLimit() public pure returns (uint8) { return 20; } // Get ether price based on current token supply function getCurrentPrice() public pure returns (uint64) { return 40_000_000_000_000_000; } // Mint new token(s) function mint(uint8 _quantityToMint) public payable { require(_startDate <= block.timestamp, "Sale is not open"); require(_quantityToMint >= 1, "Must mint at least 1"); require( _quantityToMint <= getCurrentMintLimit(), "Maximum current buy limit for individual transaction exceeded" ); require( (_quantityToMint + totalSupply()) <= maxSupply, "Exceeds maximum supply" ); require( msg.value == (getCurrentPrice() * _quantityToMint), "Ether submitted does not match current price" ); for (uint8 i = 0; i < _quantityToMint; i++) { _tokenIds.increment(); uint256 newItemId = _tokenIds.current(); _mint(msg.sender, newItemId); } } function tokenURI(uint256 tokenId) public view override(ERC721, ERC721URIStorage) returns (string memory) { return super.tokenURI(tokenId); } // Withdraw ether from contract function withdraw() public onlyOwner { require(address(this).balance > 0, "Balance must be positive"); (bool success, ) = msg.sender.call{value: address(this).balance}(""); require(success == true, "Failed to withdraw ether"); } function giveawayMint(uint8 _quantityToMint) public onlyOwner{ require(_quantityToMint >= 1, "Must mint at least 1"); require( _quantityToMint <= getCurrentMintLimit(), "Maximum current buy limit for individual transaction exceeded" ); require( (_quantityToMint + totalSupply()) <= maxSupply, "Exceeds maximum supply" ); for (uint8 i = 0; i < _quantityToMint; i++) { _tokenIds.increment(); uint256 newItemId = _tokenIds.current(); _mint(msg.sender, newItemId); } } }
Withdraw ether from contract
function withdraw() public onlyOwner { require(address(this).balance > 0, "Balance must be positive"); require(success == true, "Failed to withdraw ether"); }
553,234
// File: contracts/Ownable.sol pragma solidity >0.4.0 <0.6.0; contract Ownable { address payable public owner; constructor () public { owner = msg.sender; } modifier onlyOwner() { require(msg.sender == owner); _; } function transferOwnership(address payable newOwner) external onlyOwner { require(newOwner != address(0)); owner = newOwner; } } // File: contracts/ReentrancyGuard.sol pragma solidity ^0.5.0; contract ReentrancyGuard { // counter to allow mutex lock with only one SSTORE operation uint256 private _guardCounter; constructor () internal { // The counter starts at one to prevent changing it from zero to a non-zero // value, which is a more expensive operation. _guardCounter = 1; } /** * @dev Prevents a contract from calling itself, directly or indirectly. * Calling a `nonReentrant` function from another `nonReentrant` * function is not supported. It is possible to prevent this from happening * by making the `nonReentrant` function external, and make it call a * `private` function that does the actual work. */ modifier nonReentrant() { _guardCounter += 1; uint256 localCounter = _guardCounter; _; require(localCounter == _guardCounter, "ReentrancyGuard: reentrant call"); } } // File: contracts/SafeMath.sol pragma solidity ^0.5.0; library SafeMath { function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a, "SafeMath: subtraction overflow"); uint256 c = a - b; return c; } function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } function div(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: division by zero"); uint256 c = a / b; return c; } function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b != 0, "SafeMath: modulo by zero"); return a % b; } } // File: contracts/DoubleBullZap.sol pragma solidity ^0.5.0; interface Invest2Fulcrum2xLongBTC { function LetsInvest2Fulcrum2xLongBTC(address _towhomtoissue) external payable; } // this is the underlying contract that invests in 2xLongETH on Fulcrum interface Invest2Fulcrum2xLongETH { function LetsInvest2Fulcrum(address _towhomtoissue) external payable; } // through this contract we are putting 50% allocation to 2xLongETH and 50% to 2xLongBTC contract DoubleBullZap is Ownable { using SafeMath for uint; // state variables // - variables in relation to the percentages uint public BTC2xLongPercentage = 50; Invest2Fulcrum2xLongETH public Invest2Fulcrum2xLong_ETHContract = Invest2Fulcrum2xLongETH(0xAB58BBF6B6ca1B064aa59113AeA204F554E8fBAe); Invest2Fulcrum2xLongBTC public Invest2Fulcrum2xLong_BTCContract = Invest2Fulcrum2xLongBTC(0xd455e7368BcaB144C2944aD679E4Aa10bB3766c1); // - in relation to the ETH held by this contract uint public balance = address(this).balance; // - in relation to the emergency functioning of this contract bool private stopped = false; // circuit breaker modifiers modifier stopInEmergency {if (!stopped) _;} modifier onlyInEmergency {if (stopped) _;} // this function should be called should we ever want to change the underlying Fulcrum Long ETHContract address function set_Invest2Fulcrum2xLong_ETHContract (Invest2Fulcrum2xLongETH _Invest2Fulcrum2xLong_ETHContract) onlyOwner public { Invest2Fulcrum2xLong_ETHContract = _Invest2Fulcrum2xLong_ETHContract; } // this function should be called should we ever want to change the underlying Fulcrum Long ETHContract address function set_Invest2Fulcrum2xLong_BTCContract (Invest2Fulcrum2xLongBTC _Invest2Fulcrum2xLong_BTCContract) onlyOwner public { Invest2Fulcrum2xLong_BTCContract = _Invest2Fulcrum2xLong_BTCContract; } // this function should be called should we ever want to change the portion to be invested in 2xLongBTC function set_BTC2xLongPercentage (uint32 _BTC2xLongPercentage) onlyOwner public { BTC2xLongPercentage = _BTC2xLongPercentage; } // main function which will make the investments function LetsInvest() public payable returns(uint) { require (msg.value > 100000000000000); require (msg.sender != address(0)); uint invest_amt = msg.value; address payable investor = address(msg.sender); uint BTC2xLongPortion = SafeMath.div(SafeMath.mul(invest_amt,BTC2xLongPercentage),100); uint ETH2xLongPortion = SafeMath.sub(invest_amt, BTC2xLongPortion); require (SafeMath.sub(invest_amt, SafeMath.add(BTC2xLongPortion, ETH2xLongPortion)) ==0 ); Invest2Fulcrum2xLong_BTCContract.LetsInvest2Fulcrum2xLongBTC.value(BTC2xLongPortion)(investor); Invest2Fulcrum2xLong_ETHContract.LetsInvest2Fulcrum.value(ETH2xLongPortion)(investor); } // fx in relation to ETH held by the contract sent by the owner // - this function lets you deposit ETH into this wallet function depositETH() payable public onlyOwner returns (uint) { balance += msg.value; } // - fallback function let you / anyone send ETH to this wallet without the need to call any function function() external payable { if (msg.sender == owner) { depositETH(); } else { LetsInvest(); } } // - to withdraw any ETH balance sitting in the contract function withdraw() onlyOwner public{ owner.transfer(address(this).balance); } }
this function should be called should we ever want to change the underlying Fulcrum Long ETHContract address
function set_Invest2Fulcrum2xLong_BTCContract (Invest2Fulcrum2xLongBTC _Invest2Fulcrum2xLong_BTCContract) onlyOwner public { Invest2Fulcrum2xLong_BTCContract = _Invest2Fulcrum2xLong_BTCContract; }
12,846,932
pragma solidity 0.5.0; import "openzeppelin-solidity/contracts/math/SafeMath.sol"; import "openzeppelin-solidity/contracts/token/ERC20/IERC20.sol"; /** * @title Debts Package. * @notice Package of debts tokens to be sold on a time auction. * @author Anibal Catalán <[email protected]>. */ contract Package { using SafeMath for uint256; uint256 public maxRisk; uint256 public maxFund; uint256 public total; uint256 public fundingPeriod; uint256 public auctionPeriod; uint256 public auctionFloorPrice; uint256 public startTime; uint256 public fundingTimeFinished; uint256 public auctionTimeFinished; uint256 public tokenBalance; uint256 public finalPrice; address public liquidityToken; address public owner; address public riskOracle; mapping(address => uint256) public tokenAmount; //token->amount mapping(address => mapping(address => uint256)) public tokenContributions; //contributor->token->amount event LogFunded(address contributor, address token, uint256 contribution, uint256 balance); event LogPackageFunded(); event LogPackageSold(address owner, uint256 finalPrice); event LogCashOut(address contributor, address token, uint256 liquidity); event LogDebtRetrieved(address contributor, address token, uint256 contribution); event LogTokenCollected(address token, uint256 amount); constructor( uint256 _maxRisk, uint256 _maxFundPercentage, uint256 _total, uint256 _fundingPeriod, uint256 _auctionPeriod, uint256 _auctionFloorPricePercentage, address _liquidityToken, address _riskOracle ) public { require(_maxRisk > 0 && _maxRisk <= 100, "risk aout of range"); require(_maxFundPercentage > 0 && _maxFundPercentage <= 100, "max fund per token aut of range"); require(_fundingPeriod > 0, "invalid funding period"); require(_auctionPeriod > 0, "invalid auction period"); require(_auctionFloorPricePercentage > 0 && _auctionFloorPricePercentage <= 100, "auction floor price aout of range"); require(_liquidityToken != address(0), "invalid controller address"); require(_riskOracle != address(0), "invalid risk oracle address"); maxRisk = _maxRisk; maxFund = _total * _maxFundPercentage / 100; total = _total; fundingPeriod = _fundingPeriod * 1 minutes; auctionPeriod = _auctionPeriod * 1 minutes; auctionFloorPrice = _total * _auctionFloorPricePercentage / 100; startTime = now; liquidityToken = _liquidityToken; riskOracle = _riskOracle; } /** * @notice Function controlling by the company, * when the company see that this contract was funded with debt tokens, * they call this function to change the state according. * @param contributor Is who sent the debt token to this contract. * @param token It is the debt token. * @param contribution It how much token was send. */ function fund(address contributor, address token, uint256 contribution) public { require(tokenBalance < total, "package totally funded"); // validate balance require(now <= startTime.add(fundingPeriod) && fundingTimeFinished == 0, "out of period"); //validate funding time //TODO: Validate risk with an external risk Oracle require( contribution >= IERC20(token).allowance(contributor, address(this)), "not enough amount of tokens are allowed" ); // validate if amount of contribution is allowed uint256 contributionAmount; if (tokenAmount[token].add(contribution) > maxFund && tokenBalance.add(contribution) > total) { if (tokenBalance.add(contribution).sub(total) > tokenAmount[token].add(contribution).sub(maxFund)) { contributionAmount = total.sub(tokenBalance); } else { contributionAmount = maxFund.sub(tokenAmount[token]); } } else if (tokenBalance.add(contribution) > total) { contributionAmount = total.sub(tokenBalance); } else if (tokenAmount[token].add(contribution) > maxFund) { contributionAmount = maxFund.sub(tokenAmount[token]); } else { contributionAmount = contribution; } tokenAmount[token] = tokenAmount[token].add(contributionAmount); tokenContributions[contributor][token] = tokenContributions[contributor][token].add(contributionAmount); tokenBalance = tokenBalance.add(contributionAmount); if (tokenBalance == total) { fundingTimeFinished = now; emit LogPackageFunded(); } require(IERC20(token).transferFrom(contributor, address(this), contributionAmount), "transfer from fail"); emit LogFunded(contributor, token, contributionAmount, tokenBalance); } /** * @notice Time auction, the price of the package will decrease linearly, * until reach the floor auction price at the end of the auction period. * @param purchaser Who purchased the package. */ function auction(address purchaser) public { finalPrice = packagePrice(); uint256 amount = IERC20(liquidityToken).allowance(purchaser, address(this)); require(amount >= finalPrice, "not enough liquidity token is allowed"); owner = purchaser; auctionTimeFinished = now; require(IERC20(liquidityToken).transferFrom(purchaser, address(this), finalPrice), "transfer from fail"); emit LogPackageSold(owner, finalPrice); } /** * @notice Contributors can get liquidity as result of selling their debt tokens, * this is proportional to the final package price and the debt token contribution. * @param token Helps to identify the debt token contribution. */ function cashOut(address token) public { require(auctionTimeFinished > 0, "auction is not successfully finished"); uint256 contribution = tokenContributions[msg.sender][token]; require(contribution > 0, "no contributions"); tokenContributions[msg.sender][token] = 0; tokenAmount[token] = tokenAmount[token].sub(contribution); uint256 liquidity = contribution.mul(finalPrice).div(total); require(IERC20(liquidityToken).transfer(msg.sender, liquidity), "fail liquidity transfer"); emit LogCashOut(msg.sender, token, liquidity); } /** * @notice Contributors can retrieve their debt tokens if the funding of the package it was not successful. * @param token Helps to identify the debt token contribution. */ function retrieveDebt(address token) public { require((now > startTime.add(fundingPeriod) && fundingTimeFinished == 0) || (fundingTimeFinished > 0 && now > fundingTimeFinished.add(auctionPeriod) && auctionTimeFinished == 0), "funding or auction running"); uint256 contribution = tokenContributions[msg.sender][token]; require(contribution > 0, "no contributions"); tokenContributions[msg.sender][token] = 0; tokenAmount[token] = tokenAmount[token].sub(contribution); tokenBalance = tokenBalance.sub(contribution); require(IERC20(token).transfer(msg.sender, contribution), "token transfer fail"); emit LogDebtRetrieved(msg.sender, token, contribution); } /** * @notice Package owner can collect the debt tokens. * @param token Helps to identify the debt token to be collect. */ function collectToken(address token) public { require(auctionTimeFinished > 0, "auction is not successfully finished"); require(msg.sender == owner, "caller is not the owner"); uint256 amount = IERC20(token).balanceOf(address(this)); tokenAmount[token] = 0; tokenBalance = tokenBalance.sub(amount); require(IERC20(token).transfer(owner, amount), "token transfer fail"); emit LogTokenCollected(token, amount); } /** * @notice Calculate the package price while the auction is running. * @return price Package price in Wei. */ function packagePrice() public view returns(uint256) { require(fundingTimeFinished > 0, "funding is not complete"); require(now <= fundingTimeFinished.add(auctionPeriod) && auctionTimeFinished == 0, "out of period"); uint256 linearPriceChange = total.sub(auctionFloorPrice).mul(now.sub(fundingTimeFinished)).div(auctionPeriod); return total.sub(linearPriceChange); } /** * @notice Get the amount of tokens contributed by a contributor. * @param contributor where the contribution came from. * @param token it is the token contributed. * @return amount of tokens contributed. */ function contributions(address contributor, address token) public view returns(uint256) { return tokenContributions[contributor][token]; } /** * @notice Get the amount of tokens contributed. * @param token it is the token contributed. * @return amount of tokens contributed. */ function tokens(address token) public view returns(uint256) { return tokenAmount[token]; } }
Package owner can collect the debt tokens. token Helps to identify the debt token to be collect./
function collectToken(address token) public { require(auctionTimeFinished > 0, "auction is not successfully finished"); require(msg.sender == owner, "caller is not the owner"); uint256 amount = IERC20(token).balanceOf(address(this)); tokenAmount[token] = 0; tokenBalance = tokenBalance.sub(amount); require(IERC20(token).transfer(owner, amount), "token transfer fail"); emit LogTokenCollected(token, amount); }
1,070,970
// SPDX-License-Identifier: GPL-3.0 pragma solidity 0.6.12; pragma experimental ABIEncoderV2; // Global Enums and Structs struct PoolInfo { IERC20 lpToken; // Address of LP token contract. uint256 allocPoint; // How many allocation points assigned to this pool. TOKENs to distribute per block. uint256 lastRewardBlock; // Last block number that TOKENs distribution occurs. uint256 accPerShare; // Accumulated TOKENs per share, times 1e12. See below. uint256 lockPeriod; // Lock period of LP pool } // 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]/Context /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with 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; } } // 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: VaultWithdrawAPI interface VaultWithdrawAPI { function withdraw(uint256 maxShares, address recipient) external returns (uint256); } // Part: OpenZeppelin/[email protected]/Ownable /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ 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; } } // 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"); } } } // File: Staking.sol contract Staking is Ownable { using SafeMath for uint256; using SafeERC20 for IERC20; // Info of each user. struct UserInfo { uint256 amount; // How many LP tokens the user has provided. uint256 rewardDebt; // Reward debt. See explanation below. uint256 depositTime; // Last time of deposit/withdraw operation. // // We do some fancy math here. Basically, any point in time, the amount of TOKENs // entitled to a user but is pending to be distributed is: // // pending reward = (user.amount * pool.accPerShare) - user.rewardDebt // // Whenever a user deposits or withdraws LP tokens to a pool. Here's what happens: // 1. The pool's `accPerShare` (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. } IERC20 public token; // tokens created per block. uint256 public tokenPerBlock; uint256 public tokenDistributed; // Info of each pool. PoolInfo[] public poolInfo; // Info of each user that stakes LP tokens. mapping (uint256 => mapping (address => UserInfo)) public userInfo; // Total allocation points. Must be the sum of all allocation points in all pools. uint256 public totalAllocPoint = 0; // The block number when mining starts. uint256 public startBlock; event Deposit(address indexed user, uint256 indexed pid, uint256 amount); event Withdraw(address indexed user, uint256 indexed pid, uint256 amount); event Harvest(address indexed user, uint256 indexed pid, uint256 amount); constructor( IERC20 _token, uint256 _tokenPerBlock, uint256 _startBlock ) public { token = _token; tokenPerBlock = _tokenPerBlock; startBlock = _startBlock; } function poolLength() external view returns (uint256) { return poolInfo.length; } function checkPoolDuplicate(IERC20 _lpToken) internal { uint256 length = poolInfo.length; for (uint256 pid = 0; pid < length; ++pid) { require(poolInfo[pid].lpToken != _lpToken, "add: existing pool"); } } // Add a new lp to the pool. Can only be called by the owner. function add(uint256 _allocPoint, IERC20 _lpToken) external onlyOwner { checkPoolDuplicate(_lpToken); massUpdatePools(); uint256 lastRewardBlock = block.number > startBlock ? block.number : startBlock; totalAllocPoint = totalAllocPoint.add(_allocPoint); poolInfo.push(PoolInfo({ lpToken: _lpToken, allocPoint: _allocPoint, lastRewardBlock: lastRewardBlock, accPerShare: 0, lockPeriod: 0 })); } function setLockPeriod(uint256 _pid, uint256 _lockPeriod) external onlyOwner { poolInfo[_pid].lockPeriod = _lockPeriod; } function remainingLockPeriod(uint256 _pid, address _user) external view returns (uint256) { return _remainingLockPeriod(_pid, _user); } function _remainingLockPeriod(uint256 _pid, address _user) internal view returns (uint256) { uint256 lockPeriod = poolInfo[_pid].lockPeriod; UserInfo storage user= userInfo[_pid][_user]; uint256 timeElapsed = block.timestamp.sub(user.depositTime); if (user.amount > 0 && timeElapsed < lockPeriod) { return lockPeriod.sub(timeElapsed); } else { return 0; } } // Update the given pool's TOKEN allocation point. Can only be called by the owner. function set(uint256 _pid, uint256 _allocPoint) external onlyOwner { massUpdatePools(); totalAllocPoint = totalAllocPoint.sub(poolInfo[_pid].allocPoint).add(_allocPoint); poolInfo[_pid].allocPoint = _allocPoint; } function setTokenPerBlock(uint256 _tokenPerBlock) external onlyOwner { massUpdatePools(); tokenPerBlock = _tokenPerBlock; } // Sweep all STN to owner function sweep(uint256 _amount) external onlyOwner { token.safeTransfer(owner(), _amount); } // Return reward multiplier over the given _from to _to block. function getMultiplier(uint256 _from, uint256 _to) internal pure returns (uint256) { return _to.sub(_from); } function rewardForPoolPerBlock(uint256 _pid) external view returns (uint256) { PoolInfo storage pool = poolInfo[_pid]; return tokenPerBlock.mul(pool.allocPoint).div(totalAllocPoint); } // View function to see deposited TOKENs on frontend. function tokenOfUser(uint256 _pid, address _user) external view returns (uint256) { UserInfo storage user = userInfo[_pid][_user]; return user.amount; } // View function to see pending TOKENs on frontend. function pendingToken(uint256 _pid, address _user) external view returns (uint256) { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][_user]; uint256 accPerShare = pool.accPerShare; uint256 lpSupply = pool.lpToken.balanceOf(address(this)); if (block.number > pool.lastRewardBlock && lpSupply != 0) { uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number); uint256 tokenReward = multiplier.mul(tokenPerBlock).mul(pool.allocPoint).div(totalAllocPoint); accPerShare = accPerShare.add(tokenReward.mul(1e12).div(lpSupply)); } uint256 pending = user.amount.mul(accPerShare).div(1e12).sub(user.rewardDebt); uint256 remaining = token.balanceOf(address(this)); return Math.min(pending, remaining); } // Update reward variables for all pools. Be careful of gas spending! // Should be invoked if pool status changed, such as adding new pool, setting new pool config // otherwise, other pools can't split token reward fairly since they only update state // when someone interact with it directly. function massUpdatePools() internal { uint256 length = poolInfo.length; for (uint256 pid = 0; pid < length; ++pid) { updatePool(pid); } } // Update reward variables of the given pool to be up-to-date. function updatePool(uint256 _pid) internal { PoolInfo storage pool = poolInfo[_pid]; if (block.number <= pool.lastRewardBlock) { return; } uint256 lpSupply = pool.lpToken.balanceOf(address(this)); if (lpSupply == 0) { pool.lastRewardBlock = block.number; return; } uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number); uint256 tokenReward = multiplier.mul(tokenPerBlock).mul(pool.allocPoint).div(totalAllocPoint); pool.accPerShare = pool.accPerShare.add(tokenReward.mul(1e12).div(lpSupply)); pool.lastRewardBlock = block.number; } // Deposit LP tokens. // In normal case, _recipient should be same as msg.sender // In deposit and stake, _recipient should be address of initial user function deposit(uint256 _pid, uint256 _amount, address _recipient) public returns (uint256) { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][_recipient]; uint256 rewards = _harvest(_recipient, _pid); // Update debt before calling external function uint256 newAmount = user.amount.add(_amount); user.rewardDebt = newAmount.mul(pool.accPerShare).div(1e12); if (_amount > 0) { pool.lpToken.safeTransferFrom(msg.sender, address(this), _amount); user.amount = newAmount; user.depositTime = block.timestamp; } emit Deposit(_recipient, _pid, _amount); return rewards; } // Withdraw LP tokens. function unstakeAndWithdraw(uint256 _pid, uint256 _amount, VaultWithdrawAPI vault) external returns (uint256) { address sender = msg.sender; PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][sender]; require(user.amount >= _amount, "withdraw: not good"); require(_remainingLockPeriod(_pid, sender) == 0, "withdraw: still in lockPeriod"); uint256 rewards = _harvest(sender, _pid); // Update debt before calling external function uint256 newAmount = user.amount.sub(_amount); user.rewardDebt = newAmount.mul(pool.accPerShare).div(1e12); if(_amount > 0) { // Update state variable before we call function of external contract user.amount = newAmount; user.depositTime = block.timestamp; IERC20 sVault = IERC20(address(vault)); uint256 beforeBalance = sVault.balanceOf(address(this)); vault.withdraw(_amount, sender); // Detect delta amount by comparing balance uint256 delta = beforeBalance.sub(sVault.balanceOf(address(this))); // Should never withdraw more than _amount assert(delta <= _amount); // If vault didn't burn all shares, we update amount by substracting delta if(delta < _amount) { user.amount = user.amount.add(_amount).sub(delta); user.rewardDebt = user.amount.mul(pool.accPerShare).div(1e12); } } emit Withdraw(sender, _pid, _amount); return rewards; } // Withdraw LP tokens. function withdraw(uint256 _pid, uint256 _amount) external returns (uint256) { address sender = msg.sender; PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][sender]; require(user.amount >= _amount, "withdraw: not good"); require(_remainingLockPeriod(_pid, sender) == 0, "withdraw: still in lockPeriod"); uint256 rewards = _harvest(sender, _pid); // Update debt before calling external function uint256 newAmount = user.amount.sub(_amount); user.rewardDebt = newAmount.mul(pool.accPerShare).div(1e12); if(_amount > 0) { user.amount = newAmount; user.depositTime = block.timestamp; pool.lpToken.safeTransfer(address(sender), _amount); } emit Withdraw(sender, _pid, _amount); return rewards; } // Harvest TOKEN to wallet function harvest(uint256 _pid) external returns (uint256) { address sender = msg.sender; uint256 rewards = _harvest(sender, _pid); PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][sender]; user.rewardDebt = user.amount.mul(pool.accPerShare).div(1e12); return rewards; } function _harvest(address _user, uint256 _pid) internal returns (uint256) { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][_user]; updatePool(_pid); if (user.amount == 0) { return 0; } uint256 pending = user.amount.mul(pool.accPerShare).div(1e12).sub(user.rewardDebt); uint256 remaining = token.balanceOf(address(this)); pending = Math.min(pending, remaining); if(pending > 0) { tokenDistributed = tokenDistributed.add(pending); token.safeTransfer(_user, pending); } emit Harvest(_user, _pid, pending); return pending; } }
Sweep all STN to owner
function sweep(uint256 _amount) external onlyOwner { token.safeTransfer(owner(), _amount); }
5,794,865
./full_match/3/0x103E9df0BF772478b0031F57C424CD856B34EDa9/sources/demo2.sol
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, address brain, uint256 tokenId) internal virtual { _safeMint(to, brain, tokenId, ""); }
14,157,439
pragma solidity >=0.4.24 <0.7.0; import "./SafeMath.sol"; import "../node_modules/@chainlink/contracts/src/v0.5/ChainlinkClient.sol"; contract Ticketh is ChainlinkClient { using SafeMath for uint256; uint256 oraclePrice; bytes32 jobId; address oracleAddress; struct Lottery { uint256 lotteryId; uint256 ticketPrice; uint256 currentSum; uint256 blockNumber; uint256 endBlocks; bool lotteryStatus; address payable[] participatingPlayers; address[] roundWinners; } mapping(uint256 => Lottery) lotteries; struct ChainlinkCallbackDetails { uint256 lotteryId; } mapping(bytes32 => ChainlinkCallbackDetails) chainlinkDetails; address payable public ownerAddress; address self = address(this); modifier onlyOwner() { require(msg.sender == ownerAddress, "Not authorized."); _; } constructor() public payable { setPublicChainlinkToken(); ownerAddress = msg.sender; oraclePrice = 100000000000000000; jobId = "85e21af0bcfb45d5888851286d57ce0c"; oracleAddress = 0x89f70fA9F439dbd0A1BC22a09BEFc56adA04d9b4; lotteries[0] = Lottery( 0, 0.001 ether, 0, 0, 10, true, new address payable[](0), new address[](0) ); lotteries[1] = Lottery( 1, 0.05 ether, 0, 0, 17280, true, new address payable[](0), new address[](0) ); lotteries[2] = Lottery( 2, 0.1 ether, 0, 0, 28800, true, new address payable[](0), new address[](0) ); lotteries[3] = Lottery( 3, 0.5 ether, 0, 0, 40320, true, new address payable[](0), new address[](0) ); } function buyTicket(uint256 lotteryId) public payable { Lottery storage lottery = lotteries[lotteryId]; require( msg.value >= lottery.ticketPrice && lottery.lotteryStatus == true, "Error on buying a ticket!" ); lottery.participatingPlayers.push(msg.sender); lottery.currentSum = lottery.currentSum + msg.value; if (lottery.participatingPlayers.length == 1) { lottery.blockNumber = block.number + lottery.endBlocks; } if (lottery.blockNumber != 0 && block.number >= lottery.blockNumber) { lottery.lotteryStatus = false; requestRandomNumber(lotteryId); } } function requestRandomNumber(uint256 lotteryId) internal { Chainlink.Request memory req = buildChainlinkRequest( jobId, address(this), this.distributePrize.selector ); req.addUint("min", 0); req.addUint( "max", (lotteries[lotteryId].participatingPlayers.length - 1) ); bytes32 requestId = sendChainlinkRequestTo(oracleAddress, req, oraclePrice); chainlinkDetails[requestId] = ChainlinkCallbackDetails(lotteryId); } function distributePrize(bytes32 _requestId, uint256 _number) public recordChainlinkFulfillment(_requestId) { ChainlinkCallbackDetails storage details = chainlinkDetails[_requestId]; Lottery storage lottery = lotteries[details.lotteryId]; lottery.participatingPlayers[_number].transfer( lottery.currentSum - ((lottery.currentSum * 10) / 100) ); lottery.roundWinners.push(lottery.participatingPlayers[_number]); resetLottery(lottery); } function resetLottery(Lottery storage lottery) internal { lottery.participatingPlayers = new address payable[](0); lottery.currentSum = 0; lottery.blockNumber = 0; lottery.lotteryStatus = true; } // Owner functions. function withdraw(uint256 amount) public onlyOwner { uint256 totalSum = 0; for (uint256 i = 0; i < 3; i++) { totalSum = totalSum + lotteries[i].currentSum; } require(amount <= (self.balance - totalSum), "Wrong amount!"); ownerAddress.transfer(amount); } function endManually(uint256 lotteryId) public onlyOwner { requestRandomNumber(lotteryId); } // Change lottery details if necessary. function changeEndBlocks(uint256 lotteryId, uint256 numberOfBlocks) public onlyOwner { lotteries[lotteryId].endBlocks = numberOfBlocks; } function changeTicketPrice(uint256 lotteryId, uint256 ticketPrice) public onlyOwner { lotteries[lotteryId].ticketPrice = ticketPrice; } // Change chainlink details if necessary. function changeOraclePrice(uint256 newPrice) public onlyOwner { oraclePrice = newPrice; } function changeOracleAddress(address newAddress) public onlyOwner { oracleAddress = newAddress; } function changeJobId(bytes32 newJobId) public onlyOwner { jobId = newJobId; } //Ticketh information functions. function getPlayers(uint256 lotteryId) public view returns (address payable[] memory) { return lotteries[lotteryId].participatingPlayers; } function getWinners(uint256 lotteryId) public view returns (address[] memory) { return lotteries[lotteryId].roundWinners; } function getStatus(uint256 lotteryId) public view returns (bool) { return lotteries[lotteryId].lotteryStatus; } function getBlockNum(uint256 lotteryId) public view returns (uint256) { return lotteries[lotteryId].blockNumber; } function getOraclePrice() public view returns (uint256) { return oraclePrice; } function getOracleAddress() public view returns (address) { return oracleAddress; } function getJobId() public view returns (bytes32) { return jobId; } function getLotteryTicketPrice(uint256 lotteryId) public view returns (uint256) { return lotteries[lotteryId].ticketPrice; } function getLotteryEndBlocks(uint256 lotteryId) public view returns (uint256) { return lotteries[lotteryId].endBlocks; } }
Ticketh information functions.
function getPlayers(uint256 lotteryId) public view returns (address payable[] memory) { return lotteries[lotteryId].participatingPlayers; }
6,449,662
./full_match/42/0x9e05606a5c4cdbc38D5468e197A8A7bf47263252/sources/stakingOliver/uniswaprouter.sol
given an output amount of an asset and pair reserves, returns a required input amount of the other asset
function getAmountIn(uint amountOut, uint reserveIn, uint reserveOut, bool status) internal pure returns (uint amountIn) { require(amountOut > 0, 'UniswapV2Library: INSUFFICIENT_OUTPUT_AMOUNT'); require(reserveIn > 0 && reserveOut > 0, 'UniswapV2Library: INSUFFICIENT_LIQUIDITY'); uint256 feeValue = 997; if(status) { feeValue = 997; } uint numerator = reserveIn.mul(amountOut).mul(1000); uint denominator = reserveOut.sub(amountOut).mul(feeValue); amountIn = (numerator / denominator).add(1); }
16,241,518
// SPDX-License-Identifier: MIT pragma solidity 0.6.6; // Part: CryptoTraderInterface interface CryptoTraderInterface { /** * Returns a uri for CryptTraderI (BTC) tokens */ function btcTokenURI() external view returns (string memory); /** * Returns a uri for CryptTraderII (ETH) tokens */ function ethTokenURI() external view returns (string memory); } // Part: smartcontractkit/[email protected]/AggregatorV3Interface 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: CryptoTraderTokenUriProvider.sol /** * Provides token metadata for CryptoTraderI and CryptoTraderII tokens */ contract CryptoTraderTokenUriProvider is CryptoTraderInterface { address owner; struct PriceRange { uint256 low; uint256 high; string tokenUriUp; string tokenUriDown; } PriceRange[] private btcPriceRanges; PriceRange[] private ethPriceRanges; AggregatorV3Interface private btcPriceFeed; AggregatorV3Interface private ethPriceFeed; uint80 private roundInterval = 50; /** * @dev Public constructor * _btcPriceFeed - address for the BTC/USD feed mainnet: 0xF4030086522a5bEEa4988F8cA5B36dbC97BeE88c * _ethPriceFeed - address for the ETH/USD feed mainnet: 0x5f4eC3Df9cbd43714FE2740f5E3616155c5b8419 */ constructor(address _btcPriceFeed, address _ethPriceFeed) public { owner = msg.sender; btcPriceFeed = AggregatorV3Interface(_btcPriceFeed); ethPriceFeed = AggregatorV3Interface(_ethPriceFeed); populateRanges(); } function populateRanges() private { btcPriceRanges.push( PriceRange({ low: 0, high: 30000, tokenUriUp: "QmPXt5xgCCYz8BeiYNB46AraVrgEPHMs1bnWhrUCuAa4yp", tokenUriDown: "QmfTG6WooW25Ry88a6BkBHic6xeVnmuN8DPTuAU5AAeHJv" }) ); btcPriceRanges.push( PriceRange({ low: 30001, high: 40000, tokenUriUp: "QmUgqXRYm5fy1memqr2d3FfEkpaeoziSNLhLE9sYN6Gd8v", tokenUriDown: "QmUGVMELqcUjJT2Zk5ED7DgYXfVgu831qMpiNcZL25VQ6r" }) ); btcPriceRanges.push( PriceRange({ low: 40001, high: 65000, tokenUriUp: "QmP391qVmmweuQouZzC3WQPEkDKmRmbmzq9vyGGNohjBLY", tokenUriDown: "QmVUFkwMsrpsHYx6dEY2ZDWd3ochrgHJpks5iDLSajHpba" }) ); btcPriceRanges.push( PriceRange({ low: 65001, high: 85000, tokenUriUp: "QmVJv6iSrM4vjQhuNi4oWiYdFk2MztSspuwuQvP7zzSd41", tokenUriDown: "QmbvHqmitVN5jpQDwXMc7M9bcABXVLgdSRp1tPVWQeBmyy" }) ); btcPriceRanges.push( PriceRange({ low: 85001, high: 100000, tokenUriUp: "QmfM2wdvEFNqbGpP4gNUqCfE15i8F4ZbCX2VAS3LHGLTbU", tokenUriDown: "QmRGQSgJmvgGYpWWTcXytHksGdHfhAu3pcqkNknRj2KTbP" }) ); btcPriceRanges.push( PriceRange({ low: 100001, high: 1000000, tokenUriUp: "QmZZaoaaLnYPEnwAwymRCWEdevqKTDFq6UdG26FUDwhqds", tokenUriDown: "QmcJQyteLVZwBAdhdZDSv1itMPT3GeicyRvBXDXNwwa8yJ" }) ); ethPriceRanges.push( PriceRange({ low: 0, high: 2000, tokenUriUp: "QmYEwKc5P4X5u1GTv8AgGERpLki3feATDPNhXACRR2fSTt", tokenUriDown: "QmV2MKJDLU6DYsLAnFVUwB5EtyjpYsAcMfK3N4bQT98XoS" }) ); ethPriceRanges.push( PriceRange({ low: 2001, high: 3500, tokenUriUp: "QmbDcmPrDTM3yxk7eEEMj8cs4vEfYywUwKQUZNwhbEy2Nx", tokenUriDown: "QmeAHsUnWWXRvPHbYKTmqU6aVyBqEGWQAZYyjL1Uvn4Xen" }) ); ethPriceRanges.push( PriceRange({ low: 3501, high: 5000, tokenUriUp: "QmW5XvfMo6AmRuFVBkiijZde3rUN76289nGzcMnfuDnbW9", tokenUriDown: "QmPAWc7Gh56rxLgF9KnQbUXmpX7PutL1eB3yn1Vy3K2VJL" }) ); ethPriceRanges.push( PriceRange({ low: 5001, high: 6500, tokenUriUp: "QmbaR2251n4J19wVFKJSaZqtntC5oPq4YYKY1WCfot7yPa", tokenUriDown: "QmewLCu62dim8PbgFeU1vQy6SyKkt1hUvurB3Fe7p3HQeH" }) ); ethPriceRanges.push( PriceRange({ low: 6501, high: 8000, tokenUriUp: "QmbYtK2WFeD6oWqQBRiayZpLjUFjjFGdP9s1aS2RQtHuzi", tokenUriDown: "QmTWaiAfRkzWw4rterJaByNE2QcuLcbp7NaprnGSsLiRsk" }) ); ethPriceRanges.push( PriceRange({ low: 8001, high: 100000, tokenUriUp: "QmSwxyymXnh3jUjr4aWXZLHJKwtsuhUxe9mPsk35as23GB", tokenUriDown: "Qmf7foHZuHZy8w3Adk1jsQdcS5QpJF1aFhYchdCrQwzEfU" }) ); } /** * get the price for 0: BTC, 1: ETH */ function getPrice(uint8 priceType) private view returns (uint256, uint256) { AggregatorV3Interface feed = priceType == 0 ? btcPriceFeed : ethPriceFeed; // current price data (uint80 roundId, int256 answer, , , ) = feed.latestRoundData(); uint256 current = uint256(answer) / (10**uint256(feed.decimals())); // previous price data (, int256 prevAnswer, , , ) = feed.getRoundData( roundId - roundInterval ); uint256 prev = uint256(prevAnswer) / (10**uint256(feed.decimals())); return (prev, current); } /** * Return the token uri for the given type BTC=0, ETH=1 */ function tokenUri( uint8 priceType, uint256 prevPrice, uint256 currentPrice ) private view returns (string memory) { PriceRange[] memory ranges = priceType == 0 ? btcPriceRanges : ethPriceRanges; for (uint256 i = 0; i < ranges.length; i++) { if ( currentPrice >= ranges[i].low && currentPrice <= ranges[i].high ) { if (prevPrice < currentPrice) { return string( abi.encodePacked( "https://ipfs.io/ipfs/", ranges[i].tokenUriUp ) ); } else { return string( abi.encodePacked( "https://ipfs.io/ipfs/", ranges[i].tokenUriDown ) ); } } } // by default return the middle case, but still check if we're up or down if (prevPrice < currentPrice) { return priceType == 0 ? "https://ipfs.io/ipfs/QmP391qVmmweuQouZzC3WQPEkDKmRmbmzq9vyGGNohjBLY" : "https://ipfs.io/ipfs/QmW5XvfMo6AmRuFVBkiijZde3rUN76289nGzcMnfuDnbW9"; } return priceType == 0 ? "https://ipfs.io/ipfs/QmVUFkwMsrpsHYx6dEY2ZDWd3ochrgHJpks5iDLSajHpba" : "https://ipfs.io/ipfs/QmPAWc7Gh56rxLgF9KnQbUXmpX7PutL1eB3yn1Vy3K2VJL"; } /** * @dev Adds a BTC price range for the given _low/_high associated with the given * _tokenURIs. * * Requirements: * Caller must be contract owner */ function addPriceRange( uint8 rangeType, uint256 _low, uint256 _high, string memory _tokenURIUp, string memory _tokenURIDown ) public { require(msg.sender == owner, "OCO"); if (rangeType == 0) { btcPriceRanges.push( PriceRange({ low: _low, high: _high, tokenUriUp: _tokenURIUp, tokenUriDown: _tokenURIDown }) ); } else { ethPriceRanges.push( PriceRange({ low: _low, high: _high, tokenUriUp: _tokenURIUp, tokenUriDown: _tokenURIDown }) ); } } /** * @dev updates an ETH price range at the given _index * * Requirements: * Caller must be contract owner */ function setPriceRange( uint256 rangeType, uint8 _index, uint256 _low, uint256 _high, string memory _tokenURIUp, string memory _tokenURIDown ) public { require(msg.sender == owner, "OCO"); if (rangeType == 0) { btcPriceRanges[_index].low = _low; btcPriceRanges[_index].high = _high; btcPriceRanges[_index].tokenUriUp = _tokenURIUp; btcPriceRanges[_index].tokenUriDown = _tokenURIDown; } else { ethPriceRanges[_index].low = _low; ethPriceRanges[_index].high = _high; ethPriceRanges[_index].tokenUriUp = _tokenURIUp; ethPriceRanges[_index].tokenUriDown = _tokenURIDown; } } /** * @dev Set the round interval (how far back we should look for * for prev price data. Typically it seems ~50 rounds per day) * Requirements: * Only contract owner may call this method */ function setRoundInterval(uint80 _roundInterval) public { require(msg.sender == owner, "OCO"); roundInterval = _roundInterval; } /** * @dev Returns the token metadata URI for CryptoTraderI */ function btcTokenURI() public view override returns (string memory) { (uint256 prevPrice, uint256 currentPrice) = getPrice(0); return tokenUri(0, prevPrice, currentPrice); } /** * @dev Returns the token metadata URI for CryptoTraderII */ function ethTokenURI() public view override returns (string memory) { (uint256 prevPrice, uint256 currentPrice) = getPrice(1); return tokenUri(1, prevPrice, currentPrice); } /** * Get the range at index */ function getRange(uint8 index, uint8 forType) external view returns ( uint256, uint256, string memory, string memory ) { require(forType == 0 || forType == 1, "TYPEERROR"); if (forType == 0) { require(index < btcPriceRanges.length, "IOB"); return ( btcPriceRanges[index].low, btcPriceRanges[index].high, btcPriceRanges[index].tokenUriUp, btcPriceRanges[index].tokenUriDown ); } else { require(index < ethPriceRanges.length, "IOB"); return ( ethPriceRanges[index].low, ethPriceRanges[index].high, ethPriceRanges[index].tokenUriUp, ethPriceRanges[index].tokenUriDown ); } } }
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.
interface AggregatorV3Interface { function decimals() external view returns (uint8); function description() external view returns (string memory); function version() external view returns (uint256); 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 ); } }
5,884,025
./partial_match/42/0x4E951A6FB550c0eab2615619253900B2Dbc5F363/sources/STYK_I.sol
To check the user's status
function _checkUserActiveStatus(address _user)internal view returns(bool){ if(balanceOf(_user) > safeMul(10,1e18)){ return true; } else{ return false; } }
3,304,703
pragma solidity ^0.5.0; /** * @title SafeMath * @dev Unsigned math operations with safety checks that revert on error */ library SafeMath { /** * @dev Multiplies two unsigned integers, reverts on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b); return c; } /** * @dev Integer division of two unsigned integers truncating the quotient, reverts on division by zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // Solidity only automatically asserts when dividing by 0 require(b > 0); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Subtracts two unsigned integers, reverts on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a); uint256 c = a - b; return c; } /** * @dev Adds two unsigned integers, reverts on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a); return c; } /** * @dev Divides two unsigned integers and returns the remainder (unsigned integer modulo), * reverts when dividing by zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b != 0); return a % b; } } /** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */ contract Ownable { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ constructor () internal { _owner = msg.sender; emit OwnershipTransferred(address(0), _owner); } /** * @return the address of the owner. */ function owner() public view returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(isOwner()); _; } /** * @return true if `msg.sender` is the owner of the contract. */ function isOwner() public view returns (bool) { return msg.sender == _owner; } /** * @dev Allows the current owner to relinquish control of the contract. * @notice Renouncing to ownership will leave the contract without an owner. * It will not be possible to call the functions with the `onlyOwner` * modifier anymore. */ function renounceOwnership() public onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) public onlyOwner { _transferOwnership(newOwner); } /** * @dev Transfers control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function _transferOwnership(address newOwner) internal { require(newOwner != address(0)); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } /** * @title ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/20 */ interface IERC20 { function transfer(address to, uint256 value) external returns (bool); function approve(address spender, uint256 value) external returns (bool); function transferFrom(address from, address to, uint256 value) external returns (bool); function totalSupply() external view returns (uint256); function balanceOf(address who) external view returns (uint256); function allowance(address owner, address spender) external view returns (uint256); event Transfer(address indexed from, address indexed to, uint256 value); event Approval(address indexed owner, address indexed spender, uint256 value); } /** * @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(account != address(0)); require(!has(role, account)); role.bearer[account] = true; } /** * @dev remove an account's access to this role */ function remove(Role storage role, address account) internal { require(account != address(0)); require(has(role, account)); 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)); return role.bearer[account]; } } contract MinterRole { using Roles for Roles.Role; event MinterAdded(address indexed account); event MinterRemoved(address indexed account); Roles.Role private _minters; constructor () internal { _addMinter(msg.sender); } modifier onlyMinter() { require(isMinter(msg.sender)); _; } function isMinter(address account) public view returns (bool) { return _minters.has(account); } function addMinter(address account) public onlyMinter { _addMinter(account); } function renounceMinter() public { _removeMinter(msg.sender); } function _addMinter(address account) internal { _minters.add(account); emit MinterAdded(account); } function _removeMinter(address account) internal { _minters.remove(account); emit MinterRemoved(account); } } contract ERC1820Registry { function setInterfaceImplementer(address _addr, bytes32 _interfaceHash, address _implementer) external; function getInterfaceImplementer(address _addr, bytes32 _interfaceHash) external view returns (address); function setManager(address _addr, address _newManager) external; function getManager(address _addr) public view returns (address); } /// Base client to interact with the registry. contract ERC1820Client { ERC1820Registry constant ERC1820REGISTRY = ERC1820Registry(0x1820a4B7618BdE71Dce8cdc73aAB6C95905faD24); function setInterfaceImplementation(string memory _interfaceLabel, address _implementation) internal { bytes32 interfaceHash = keccak256(abi.encodePacked(_interfaceLabel)); ERC1820REGISTRY.setInterfaceImplementer(address(this), interfaceHash, _implementation); } function interfaceAddr(address addr, string memory _interfaceLabel) internal view returns(address) { bytes32 interfaceHash = keccak256(abi.encodePacked(_interfaceLabel)); return ERC1820REGISTRY.getInterfaceImplementer(addr, interfaceHash); } function delegateManagement(address _newManager) internal { ERC1820REGISTRY.setManager(address(this), _newManager); } } /* * This code has not been reviewed. * Do not use or deploy this code before reviewing it personally first. */ contract ERC1820Implementer { bytes32 constant ERC1820_ACCEPT_MAGIC = keccak256(abi.encodePacked("ERC1820_ACCEPT_MAGIC")); mapping(bytes32 => bool) internal _interfaceHashes; function canImplementInterfaceForAddress(bytes32 interfaceHash, address /*addr*/) // Comments to avoid compilation warnings for unused variables. external view returns(bytes32) { if(_interfaceHashes[interfaceHash]) { return ERC1820_ACCEPT_MAGIC; } else { return ""; } } function _setInterface(string memory interfaceLabel) internal { _interfaceHashes[keccak256(abi.encodePacked(interfaceLabel))] = true; } } /* * This code has not been reviewed. * Do not use or deploy this code before reviewing it personally first. */ /** * @title IERC1400 security token standard * @dev See https://github.com/SecurityTokenStandard/EIP-Spec/blob/master/eip/eip-1400.md */ interface IERC1400 /*is IERC20*/ { // Interfaces can currently not inherit interfaces, but IERC1400 shall include IERC20 // ****************** Document Management ******************* function getDocument(bytes32 name) external view returns (string memory, bytes32); function setDocument(bytes32 name, string calldata uri, bytes32 documentHash) external; // ******************* Token Information ******************** function balanceOfByPartition(bytes32 partition, address tokenHolder) external view returns (uint256); function partitionsOf(address tokenHolder) external view returns (bytes32[] memory); // *********************** Transfers ************************ function transferWithData(address to, uint256 value, bytes calldata data) external; function transferFromWithData(address from, address to, uint256 value, bytes calldata data) external; // *************** Partition Token Transfers **************** function transferByPartition(bytes32 partition, address to, uint256 value, bytes calldata data) external returns (bytes32); function operatorTransferByPartition(bytes32 partition, address from, address to, uint256 value, bytes calldata data, bytes calldata operatorData) external returns (bytes32); // ****************** Controller Operation ****************** function isControllable() external view returns (bool); // function controllerTransfer(address from, address to, uint256 value, bytes calldata data, bytes calldata operatorData) external; // removed because same action can be achieved with "operatorTransferByPartition" // function controllerRedeem(address tokenHolder, uint256 value, bytes calldata data, bytes calldata operatorData) external; // removed because same action can be achieved with "operatorRedeemByPartition" // ****************** Operator Management ******************* function authorizeOperator(address operator) external; function revokeOperator(address operator) external; function authorizeOperatorByPartition(bytes32 partition, address operator) external; function revokeOperatorByPartition(bytes32 partition, address operator) external; // ****************** Operator Information ****************** function isOperator(address operator, address tokenHolder) external view returns (bool); function isOperatorForPartition(bytes32 partition, address operator, address tokenHolder) external view returns (bool); // ********************* Token Issuance ********************* function isIssuable() external view returns (bool); function issue(address tokenHolder, uint256 value, bytes calldata data) external; function issueByPartition(bytes32 partition, address tokenHolder, uint256 value, bytes calldata data) external; // ******************** Token Redemption ******************** function redeem(uint256 value, bytes calldata data) external; function redeemFrom(address tokenHolder, uint256 value, bytes calldata data) external; function redeemByPartition(bytes32 partition, uint256 value, bytes calldata data) external; function operatorRedeemByPartition(bytes32 partition, address tokenHolder, uint256 value, bytes calldata operatorData) external; // ******************* Transfer Validity ******************** // We use different transfer validity functions because those described in the interface don't allow to verify the certificate's validity. // Indeed, verifying the ecrtificate's validity requires to keeps the function's arguments in the exact same order as the transfer function. // // function canTransfer(address to, uint256 value, bytes calldata data) external view returns (byte, bytes32); // function canTransferFrom(address from, address to, uint256 value, bytes calldata data) external view returns (byte, bytes32); // function canTransferByPartition(address from, address to, bytes32 partition, uint256 value, bytes calldata data) external view returns (byte, bytes32, bytes32); // ******************* Controller Events ******************** // We don't use this event as we don't use "controllerTransfer" // event ControllerTransfer( // address controller, // address indexed from, // address indexed to, // uint256 value, // bytes data, // bytes operatorData // ); // // We don't use this event as we don't use "controllerRedeem" // event ControllerRedemption( // address controller, // address indexed tokenHolder, // uint256 value, // bytes data, // bytes operatorData // ); // ******************** Document Events ********************* event Document(bytes32 indexed name, string uri, bytes32 documentHash); // ******************** Transfer Events ********************* event TransferByPartition( bytes32 indexed fromPartition, address operator, address indexed from, address indexed to, uint256 value, bytes data, bytes operatorData ); event ChangedPartition( bytes32 indexed fromPartition, bytes32 indexed toPartition, uint256 value ); // ******************** Operator Events ********************* event AuthorizedOperator(address indexed operator, address indexed tokenHolder); event RevokedOperator(address indexed operator, address indexed tokenHolder); event AuthorizedOperatorByPartition(bytes32 indexed partition, address indexed operator, address indexed tokenHolder); event RevokedOperatorByPartition(bytes32 indexed partition, address indexed operator, address indexed tokenHolder); // ************** Issuance / Redemption Events ************** event Issued(address indexed operator, address indexed to, uint256 value, bytes data); event Redeemed(address indexed operator, address indexed from, uint256 value, bytes data); event IssuedByPartition(bytes32 indexed partition, address indexed operator, address indexed to, uint256 value, bytes data, bytes operatorData); event RedeemedByPartition(bytes32 indexed partition, address indexed operator, address indexed from, uint256 value, bytes operatorData); } /** * Reason codes - ERC-1066 * * To improve the token holder experience, canTransfer MUST return a reason byte code * on success or failure based on the ERC-1066 application-specific status codes specified below. * An implementation can also return arbitrary data as a bytes32 to provide additional * information not captured by the reason code. * * Code Reason * 0x50 transfer failure * 0x51 transfer success * 0x52 insufficient balance * 0x53 insufficient allowance * 0x54 transfers halted (contract paused) * 0x55 funds locked (lockup period) * 0x56 invalid sender * 0x57 invalid receiver * 0x58 invalid operator (transfer agent) * 0x59 * 0x5a * 0x5b * 0x5a * 0x5b * 0x5c * 0x5d * 0x5e * 0x5f token meta or info * * These codes are being discussed at: https://ethereum-magicians.org/t/erc-1066-ethereum-status-codes-esc/283/24 */ /* * This code has not been reviewed. * Do not use or deploy this code before reviewing it personally first. */ /** * @title IERC1400TokensValidator * @dev ERC1400TokensValidator interface */ interface IERC1400TokensValidator { function canValidate( address token, bytes4 functionSig, bytes32 partition, address operator, address from, address to, uint value, bytes calldata data, bytes calldata operatorData ) external view returns(bool); function tokensToValidate( bytes4 functionSig, bytes32 partition, address operator, address from, address to, uint value, bytes calldata data, bytes calldata operatorData ) external; } /* * This code has not been reviewed. * Do not use or deploy this code before reviewing it personally first. */ /** * @title IERC1400TokensChecker * @dev IERC1400TokensChecker interface */ interface IERC1400TokensChecker { // function canTransfer( // bytes4 functionSig, // address operator, // address from, // address to, // uint256 value, // bytes calldata data, // bytes calldata operatorData // ) external view returns (byte, bytes32); function canTransferByPartition( bytes4 functionSig, bytes32 partition, address operator, address from, address to, uint256 value, bytes calldata data, bytes calldata operatorData ) external view returns (byte, bytes32, bytes32); } /* * This code has not been reviewed. * Do not use or deploy this code before reviewing it personally first. */ /** * @title IERC1400TokensSender * @dev ERC1400TokensSender interface */ interface IERC1400TokensSender { function canTransfer( bytes4 functionSig, bytes32 partition, address operator, address from, address to, uint value, bytes calldata data, bytes calldata operatorData ) external view returns(bool); function tokensToTransfer( bytes4 functionSig, bytes32 partition, address operator, address from, address to, uint value, bytes calldata data, bytes calldata operatorData ) external; } /* * This code has not been reviewed. * Do not use or deploy this code before reviewing it personally first. */ /** * @title IERC1400TokensRecipient * @dev ERC1400TokensRecipient interface */ interface IERC1400TokensRecipient { function canReceive( bytes4 functionSig, bytes32 partition, address operator, address from, address to, uint value, bytes calldata data, bytes calldata operatorData ) external view returns(bool); function tokensReceived( bytes4 functionSig, bytes32 partition, address operator, address from, address to, uint value, bytes calldata data, bytes calldata operatorData ) external; } /* * This code has not been reviewed. * Do not use or deploy this code before reviewing it personally first. */ // Extensions (hooks triggered by the contract) /** * @title ERC1400 * @dev ERC1400 logic */ contract ERC1400 is IERC20, IERC1400, Ownable, ERC1820Client, ERC1820Implementer, MinterRole { using SafeMath for uint256; // Token string constant internal ERC1400_INTERFACE_NAME = "ERC1400Token"; string constant internal ERC20_INTERFACE_NAME = "ERC20Token"; // Token extensions (hooks triggered by the contract) string constant internal ERC1400_TOKENS_CHECKER = "ERC1400TokensChecker"; string constant internal ERC1400_TOKENS_VALIDATOR = "ERC1400TokensValidator"; // User extensions (hooks triggered by the contract) string constant internal ERC1400_TOKENS_SENDER = "ERC1400TokensSender"; string constant internal ERC1400_TOKENS_RECIPIENT = "ERC1400TokensRecipient"; /************************************* Token description ****************************************/ string internal _name; string internal _symbol; uint256 internal _granularity; uint256 internal _totalSupply; bool internal _migrated; /************************************************************************************************/ /**************************************** Token behaviours **************************************/ // Indicate whether the token can still be controlled by operators or not anymore. bool internal _isControllable; // Indicate whether the token can still be issued by the issuer or not anymore. bool internal _isIssuable; /************************************************************************************************/ /********************************** ERC20 Token mappings ****************************************/ // Mapping from tokenHolder to balance. mapping(address => uint256) internal _balances; // Mapping from (tokenHolder, spender) to allowed value. mapping (address => mapping (address => uint256)) internal _allowed; /************************************************************************************************/ /**************************************** Documents *********************************************/ struct Doc { string docURI; bytes32 docHash; } // Mapping for token URIs. mapping(bytes32 => Doc) internal _documents; /************************************************************************************************/ /*********************************** Partitions mappings ***************************************/ // List of partitions. bytes32[] internal _totalPartitions; // Mapping from partition to their index. mapping (bytes32 => uint256) internal _indexOfTotalPartitions; // Mapping from partition to global balance of corresponding partition. mapping (bytes32 => uint256) internal _totalSupplyByPartition; // Mapping from tokenHolder to their partitions. mapping (address => bytes32[]) internal _partitionsOf; // Mapping from (tokenHolder, partition) to their index. mapping (address => mapping (bytes32 => uint256)) internal _indexOfPartitionsOf; // Mapping from (tokenHolder, partition) to balance of corresponding partition. mapping (address => mapping (bytes32 => uint256)) internal _balanceOfByPartition; // List of token default partitions (for ERC20 compatibility). bytes32[] internal _defaultPartitions; /************************************************************************************************/ /********************************* Global operators mappings ************************************/ // Mapping from (operator, tokenHolder) to authorized status. [TOKEN-HOLDER-SPECIFIC] mapping(address => mapping(address => bool)) internal _authorizedOperator; // Array of controllers. [GLOBAL - NOT TOKEN-HOLDER-SPECIFIC] address[] internal _controllers; // Mapping from operator to controller status. [GLOBAL - NOT TOKEN-HOLDER-SPECIFIC] mapping(address => bool) internal _isController; /************************************************************************************************/ /******************************** Partition operators mappings **********************************/ // Mapping from (partition, tokenHolder, spender) to allowed value. [TOKEN-HOLDER-SPECIFIC] mapping(bytes32 => mapping (address => mapping (address => uint256))) internal _allowedByPartition; // Mapping from (tokenHolder, partition, operator) to 'approved for partition' status. [TOKEN-HOLDER-SPECIFIC] mapping (address => mapping (bytes32 => mapping (address => bool))) internal _authorizedOperatorByPartition; // Mapping from partition to controllers for the partition. [NOT TOKEN-HOLDER-SPECIFIC] mapping (bytes32 => address[]) internal _controllersByPartition; // Mapping from (partition, operator) to PartitionController status. [NOT TOKEN-HOLDER-SPECIFIC] mapping (bytes32 => mapping (address => bool)) internal _isControllerByPartition; /************************************************************************************************/ /***************************************** Modifiers ********************************************/ /** * @dev Modifier to verify if token is issuable. */ modifier isIssuableToken() { require(_isIssuable, "55"); // 0x55 funds locked (lockup period) _; } /** * @dev Modifier to make a function callable only when the contract is not migrated. */ modifier isNotMigratedToken() { require(!_migrated, "54"); // 0x54 transfers halted (contract paused) _; } /************************************************************************************************/ /**************************** Events (additional - not mandatory) *******************************/ event ApprovalByPartition(bytes32 indexed partition, address indexed owner, address indexed spender, uint256 value); /************************************************************************************************/ /** * @dev Initialize ERC1400 + register the contract implementation in ERC1820Registry. * @param name Name of the token. * @param symbol Symbol of the token. * @param granularity Granularity of the token. * @param controllers Array of initial controllers. * @param defaultPartitions Partitions chosen by default, when partition is * not specified, like the case ERC20 tranfers. */ constructor( string memory name, string memory symbol, uint256 granularity, address[] memory controllers, bytes32[] memory defaultPartitions ) public { _name = name; _symbol = symbol; _totalSupply = 0; require(granularity >= 1); // Constructor Blocked - Token granularity can not be lower than 1 _granularity = granularity; _setControllers(controllers); _defaultPartitions = defaultPartitions; _isControllable = true; _isIssuable = true; // Register contract in ERC1820 registry ERC1820Client.setInterfaceImplementation(ERC1400_INTERFACE_NAME, address(this)); ERC1820Client.setInterfaceImplementation(ERC20_INTERFACE_NAME, address(this)); // Indicate token verifies ERC1400 and ERC20 interfaces ERC1820Implementer._setInterface(ERC1400_INTERFACE_NAME); // For migration ERC1820Implementer._setInterface(ERC20_INTERFACE_NAME); // For migration } /************************************************************************************************/ /****************************** EXTERNAL FUNCTIONS (ERC20 INTERFACE) ****************************/ /************************************************************************************************/ /** * @dev Get the total number of issued tokens. * @return Total supply of tokens currently in circulation. */ function totalSupply() external view returns (uint256) { return _totalSupply; } /** * @dev Get the balance of the account with address 'tokenHolder'. * @param tokenHolder Address for which the balance is returned. * @return Amount of token held by 'tokenHolder' in the token contract. */ function balanceOf(address tokenHolder) external view returns (uint256) { return _balances[tokenHolder]; } /** * @dev Transfer token for a specified address. * @param to The address to transfer to. * @param value The value to be transferred. * @return A boolean that indicates if the operation was successful. */ function transfer(address to, uint256 value) external returns (bool) { _transferByDefaultPartitions(msg.sender, msg.sender, to, value, ""); return true; } /** * @dev Check the value 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 value of tokens still available for the spender. */ function allowance(address owner, address spender) external view returns (uint256) { return _allowed[owner][spender]; } /** * @dev Approve the passed address to spend the specified amount of tokens on behalf of 'msg.sender'. * @param spender The address which will spend the funds. * @param value The amount of tokens to be spent. * @return A boolean that indicates if the operation was successful. */ function approve(address spender, uint256 value) external returns (bool) { require(spender != address(0), "56"); // 0x56 invalid sender _allowed[msg.sender][spender] = value; emit Approval(msg.sender, spender, value); return true; } /** * @dev Transfer tokens from one address to another. * @param from The address which you want to transfer tokens from. * @param to The address which you want to transfer to. * @param value The amount of tokens to be transferred. * @return A boolean that indicates if the operation was successful. */ function transferFrom(address from, address to, uint256 value) external returns (bool) { require( _isOperator(msg.sender, from) || (value <= _allowed[from][msg.sender]), "53"); // 0x53 insufficient allowance if(_allowed[from][msg.sender] >= value) { _allowed[from][msg.sender] = _allowed[from][msg.sender].sub(value); } else { _allowed[from][msg.sender] = 0; } _transferByDefaultPartitions(msg.sender, from, to, value, ""); return true; } /************************************************************************************************/ /****************************** EXTERNAL FUNCTIONS (ERC1400 INTERFACE) **************************/ /************************************************************************************************/ /************************************* Document Management **************************************/ /** * @dev Access a document associated with the token. * @param name Short name (represented as a bytes32) associated to the document. * @return Requested document + document hash. */ function getDocument(bytes32 name) external view returns (string memory, bytes32) { require(bytes(_documents[name].docURI).length != 0); // Action Blocked - Empty document return ( _documents[name].docURI, _documents[name].docHash ); } /** * @dev Associate a document with the token. * @param name Short name (represented as a bytes32) associated to the document. * @param uri Document content. * @param documentHash Hash of the document [optional parameter]. */ function setDocument(bytes32 name, string calldata uri, bytes32 documentHash) external { require(_isController[msg.sender]); _documents[name] = Doc({ docURI: uri, docHash: documentHash }); emit Document(name, uri, documentHash); } /************************************************************************************************/ /************************************** Token Information ***************************************/ /** * @dev Get balance of a tokenholder for a specific partition. * @param partition Name of the partition. * @param tokenHolder Address for which the balance is returned. * @return Amount of token of partition 'partition' held by 'tokenHolder' in the token contract. */ function balanceOfByPartition(bytes32 partition, address tokenHolder) external view returns (uint256) { return _balanceOfByPartition[tokenHolder][partition]; } /** * @dev Get partitions index of a tokenholder. * @param tokenHolder Address for which the partitions index are returned. * @return Array of partitions index of 'tokenHolder'. */ function partitionsOf(address tokenHolder) external view returns (bytes32[] memory) { return _partitionsOf[tokenHolder]; } /************************************************************************************************/ /****************************************** Transfers *******************************************/ /** * @dev Transfer the amount of tokens from the address 'msg.sender' to the address 'to'. * @param to Token recipient. * @param value Number of tokens to transfer. * @param data Information attached to the transfer, by the token holder. */ function transferWithData(address to, uint256 value, bytes calldata data) external { _transferByDefaultPartitions(msg.sender, msg.sender, to, value, data); } /** * @dev Transfer the amount of tokens on behalf of the address 'from' to the address 'to'. * @param from Token holder (or 'address(0)' to set from to 'msg.sender'). * @param to Token recipient. * @param value Number of tokens to transfer. * @param data Information attached to the transfer, and intended for the token holder ('from'). */ function transferFromWithData(address from, address to, uint256 value, bytes calldata data) external { require(_isOperator(msg.sender, from), "58"); // 0x58 invalid operator (transfer agent) _transferByDefaultPartitions(msg.sender, from, to, value, data); } /************************************************************************************************/ /********************************** Partition Token Transfers ***********************************/ /** * @dev Transfer tokens from a specific partition. * @param partition Name of the partition. * @param to Token recipient. * @param value Number of tokens to transfer. * @param data Information attached to the transfer, by the token holder. * @return Destination partition. */ function transferByPartition( bytes32 partition, address to, uint256 value, bytes calldata data ) external returns (bytes32) { return _transferByPartition(partition, msg.sender, msg.sender, to, value, data, ""); } /** * @dev Transfer tokens from a specific partition through an operator. * @param partition Name of the partition. * @param from Token holder. * @param to Token recipient. * @param value Number of tokens to transfer. * @param data Information attached to the transfer. [CAN CONTAIN THE DESTINATION PARTITION] * @param operatorData Information attached to the transfer, by the operator. * @return Destination partition. */ function operatorTransferByPartition( bytes32 partition, address from, address to, uint256 value, bytes calldata data, bytes calldata operatorData ) external returns (bytes32) { require(_isOperatorForPartition(partition, msg.sender, from) || (value <= _allowedByPartition[partition][from][msg.sender]), "53"); // 0x53 insufficient allowance if(_allowedByPartition[partition][from][msg.sender] >= value) { _allowedByPartition[partition][from][msg.sender] = _allowedByPartition[partition][from][msg.sender].sub(value); } else { _allowedByPartition[partition][from][msg.sender] = 0; } return _transferByPartition(partition, msg.sender, from, to, value, data, operatorData); } /************************************************************************************************/ /************************************* Controller Operation *************************************/ /** * @dev Know if the token can be controlled by operators. * If a token returns 'false' for 'isControllable()'' then it MUST always return 'false' in the future. * @return bool 'true' if the token can still be controlled by operators, 'false' if it can't anymore. */ function isControllable() external view returns (bool) { return _isControllable; } /************************************************************************************************/ /************************************* Operator Management **************************************/ /** * @dev Set a third party operator address as an operator of 'msg.sender' to transfer * and redeem tokens on its behalf. * @param operator Address to set as an operator for 'msg.sender'. */ function authorizeOperator(address operator) external { require(operator != msg.sender); _authorizedOperator[operator][msg.sender] = true; emit AuthorizedOperator(operator, msg.sender); } /** * @dev Remove the right of the operator address to be an operator for 'msg.sender' * and to transfer and redeem tokens on its behalf. * @param operator Address to rescind as an operator for 'msg.sender'. */ function revokeOperator(address operator) external { require(operator != msg.sender); _authorizedOperator[operator][msg.sender] = false; emit RevokedOperator(operator, msg.sender); } /** * @dev Set 'operator' as an operator for 'msg.sender' for a given partition. * @param partition Name of the partition. * @param operator Address to set as an operator for 'msg.sender'. */ function authorizeOperatorByPartition(bytes32 partition, address operator) external { _authorizedOperatorByPartition[msg.sender][partition][operator] = true; emit AuthorizedOperatorByPartition(partition, operator, msg.sender); } /** * @dev Remove the right of the operator address to be an operator on a given * partition for 'msg.sender' and to transfer and redeem tokens on its behalf. * @param partition Name of the partition. * @param operator Address to rescind as an operator on given partition for 'msg.sender'. */ function revokeOperatorByPartition(bytes32 partition, address operator) external { _authorizedOperatorByPartition[msg.sender][partition][operator] = false; emit RevokedOperatorByPartition(partition, operator, msg.sender); } /************************************************************************************************/ /************************************* Operator Information *************************************/ /** * @dev Indicate whether the operator address is an operator of the tokenHolder address. * @param operator Address which may be an operator of tokenHolder. * @param tokenHolder Address of a token holder which may have the operator address as an operator. * @return 'true' if operator is an operator of 'tokenHolder' and 'false' otherwise. */ function isOperator(address operator, address tokenHolder) external view returns (bool) { return _isOperator(operator, tokenHolder); } /** * @dev Indicate whether the operator address is an operator of the tokenHolder * address for the given partition. * @param partition Name of the partition. * @param operator Address which may be an operator of tokenHolder for the given partition. * @param tokenHolder Address of a token holder which may have the operator address as an operator for the given partition. * @return 'true' if 'operator' is an operator of 'tokenHolder' for partition 'partition' and 'false' otherwise. */ function isOperatorForPartition(bytes32 partition, address operator, address tokenHolder) external view returns (bool) { return _isOperatorForPartition(partition, operator, tokenHolder); } /************************************************************************************************/ /**************************************** Token Issuance ****************************************/ /** * @dev Know if new tokens can be issued in the future. * @return bool 'true' if tokens can still be issued by the issuer, 'false' if they can't anymore. */ function isIssuable() external view returns (bool) { return _isIssuable; } /** * @dev Issue tokens from default partition. * @param tokenHolder Address for which we want to issue tokens. * @param value Number of tokens issued. * @param data Information attached to the issuance, by the issuer. */ function issue(address tokenHolder, uint256 value, bytes calldata data) external onlyMinter isIssuableToken { require(_defaultPartitions.length != 0, "55"); // 0x55 funds locked (lockup period) _issueByPartition(_defaultPartitions[0], msg.sender, tokenHolder, value, data); } /** * @dev Issue tokens from a specific partition. * @param partition Name of the partition. * @param tokenHolder Address for which we want to issue tokens. * @param value Number of tokens issued. * @param data Information attached to the issuance, by the issuer. */ function issueByPartition(bytes32 partition, address tokenHolder, uint256 value, bytes calldata data) external onlyMinter isIssuableToken { _issueByPartition(partition, msg.sender, tokenHolder, value, data); } /************************************************************************************************/ /*************************************** Token Redemption ***************************************/ /** * @dev Redeem the amount of tokens from the address 'msg.sender'. * @param value Number of tokens to redeem. * @param data Information attached to the redemption, by the token holder. */ function redeem(uint256 value, bytes calldata data) external { _redeemByDefaultPartitions(msg.sender, msg.sender, value, data); } /** * @dev Redeem the amount of tokens on behalf of the address from. * @param from Token holder whose tokens will be redeemed (or address(0) to set from to msg.sender). * @param value Number of tokens to redeem. * @param data Information attached to the redemption. */ function redeemFrom(address from, uint256 value, bytes calldata data) external { require(_isOperator(msg.sender, from), "58"); // 0x58 invalid operator (transfer agent) _redeemByDefaultPartitions(msg.sender, from, value, data); } /** * @dev Redeem tokens of a specific partition. * @param partition Name of the partition. * @param value Number of tokens redeemed. * @param data Information attached to the redemption, by the redeemer. */ function redeemByPartition(bytes32 partition, uint256 value, bytes calldata data) external { _redeemByPartition(partition, msg.sender, msg.sender, value, data, ""); } /** * @dev Redeem tokens of a specific partition. * @param partition Name of the partition. * @param tokenHolder Address for which we want to redeem tokens. * @param value Number of tokens redeemed * @param operatorData Information attached to the redemption, by the operator. */ function operatorRedeemByPartition(bytes32 partition, address tokenHolder, uint256 value, bytes calldata operatorData) external { require(_isOperatorForPartition(partition, msg.sender, tokenHolder), "58"); // 0x58 invalid operator (transfer agent) _redeemByPartition(partition, msg.sender, tokenHolder, value, "", operatorData); } /************************************************************************************************/ /************************************************************************************************/ /************************ EXTERNAL FUNCTIONS (ADDITIONAL - NOT MANDATORY) ***********************/ /************************************************************************************************/ /************************************ Token description *****************************************/ /** * @dev Get the name of the token, e.g., "MyToken". * @return Name of the token. */ function name() external view returns(string memory) { return _name; } /** * @dev Get the symbol of the token, e.g., "MYT". * @return Symbol of the token. */ function symbol() external view returns(string memory) { return _symbol; } /** * @dev Get the number of decimals of the token. * @return The number of decimals of the token. For retrocompatibility, decimals are forced to 18 in ERC1400. */ function decimals() external pure returns(uint8) { return uint8(18); } /** * @dev Get the smallest part of the token that’s not divisible. * @return The smallest non-divisible part of the token. */ function granularity() external view returns(uint256) { return _granularity; } /** * @dev Get list of existing partitions. * @return Array of all exisiting partitions. */ function totalPartitions() external view returns (bytes32[] memory) { return _totalPartitions; } /** * @dev Get the total number of issued tokens for a given partition. * @param partition Name of the partition. * @return Total supply of tokens currently in circulation, for a given partition. */ function totalSupplyByPartition(bytes32 partition) external view returns (uint256) { return _totalSupplyByPartition[partition]; } /************************************************************************************************/ /**************************************** Token behaviours **************************************/ /** * @dev Definitely renounce the possibility to control tokens on behalf of tokenHolders. * Once set to false, '_isControllable' can never be set to 'true' again. */ function renounceControl() external onlyOwner { _isControllable = false; } /** * @dev Definitely renounce the possibility to issue new tokens. * Once set to false, '_isIssuable' can never be set to 'true' again. */ function renounceIssuance() external onlyOwner { _isIssuable = false; } /************************************************************************************************/ /************************************ Token controllers *****************************************/ /** * @dev Get the list of controllers as defined by the token contract. * @return List of addresses of all the controllers. */ function controllers() external view returns (address[] memory) { return _controllers; } /** * @dev Get controllers for a given partition. * @param partition Name of the partition. * @return Array of controllers for partition. */ function controllersByPartition(bytes32 partition) external view returns (address[] memory) { return _controllersByPartition[partition]; } /** * @dev Set list of token controllers. * @param operators Controller addresses. */ function setControllers(address[] calldata operators) external onlyOwner { _setControllers(operators); } /** * @dev Set list of token partition controllers. * @param partition Name of the partition. * @param operators Controller addresses. */ function setPartitionControllers(bytes32 partition, address[] calldata operators) external onlyOwner { _setPartitionControllers(partition, operators); } /************************************************************************************************/ /********************************* Token default partitions *************************************/ /** * @dev Get default partitions to transfer from. * Function used for ERC20 retrocompatibility. * For example, a security token may return the bytes32("unrestricted"). * @return Array of default partitions. */ function getDefaultPartitions() external view returns (bytes32[] memory) { return _defaultPartitions; } /** * @dev Set default partitions to transfer from. * Function used for ERC20 retrocompatibility. * @param partitions partitions to use by default when not specified. */ function setDefaultPartitions(bytes32[] calldata partitions) external onlyOwner { _defaultPartitions = partitions; } /************************************************************************************************/ /******************************** Partition Token Allowances ************************************/ /** * @dev Check the value of tokens that an owner allowed to a spender. * @param partition Name of the partition. * @param owner address The address which owns the funds. * @param spender address The address which will spend the funds. * @return A uint256 specifying the value of tokens still available for the spender. */ function allowanceByPartition(bytes32 partition, address owner, address spender) external view returns (uint256) { return _allowedByPartition[partition][owner][spender]; } /** * @dev Approve the passed address to spend the specified amount of tokens on behalf of 'msg.sender'. * @param partition Name of the partition. * @param spender The address which will spend the funds. * @param value The amount of tokens to be spent. * @return A boolean that indicates if the operation was successful. */ function approveByPartition(bytes32 partition, address spender, uint256 value) external returns (bool) { require(spender != address(0), "56"); // 0x56 invalid sender _allowedByPartition[partition][msg.sender][spender] = value; emit ApprovalByPartition(partition, msg.sender, spender, value); return true; } /************************************************************************************************/ /******************* Token extension (hooks triggered by the contract) **************************/ /** * @dev Set validator contract address. * The validator contract needs to verify "ERC1400TokensValidator" interface. * Once setup, the validator will be called everytime a transfer is executed. * @param validatorAddress Address of the validator contract. * @param interfaceLabel Interface label of hook contract. */ function setHookContract(address validatorAddress, string calldata interfaceLabel) external onlyOwner { _setHookContract(validatorAddress, interfaceLabel); } /************************************************************************************************/ /************************************* Token migration ******************************************/ /** * @dev Migrate contract. * * ===> CAUTION: DEFINITIVE ACTION * * This function shall be called once a new version of the smart contract has been created. * Once this function is called: * - The address of the new smart contract is set in ERC1820 registry * - If the choice is definitive, the current smart contract is turned off and can never be used again * * @param newContractAddress Address of the new version of the smart contract. * @param definitive If set to 'true' the contract is turned off definitely. */ function migrate(address newContractAddress, bool definitive) external onlyOwner { _migrate(newContractAddress, definitive); } /************************************************************************************************/ /************************************************************************************************/ /************************************* INTERNAL FUNCTIONS ***************************************/ /************************************************************************************************/ /**************************************** Token Transfers ***************************************/ /** * @dev Perform the transfer of tokens. * @param from Token holder. * @param to Token recipient. * @param value Number of tokens to transfer. */ function _transferWithData( address from, address to, uint256 value ) internal isNotMigratedToken { require(_isMultiple(value), "50"); // 0x50 transfer failure require(to != address(0), "57"); // 0x57 invalid receiver require(_balances[from] >= value, "52"); // 0x52 insufficient balance _balances[from] = _balances[from].sub(value); _balances[to] = _balances[to].add(value); emit Transfer(from, to, value); // ERC20 retrocompatibility } /** * @dev Transfer tokens from a specific partition. * @param fromPartition Partition of the tokens to transfer. * @param operator The address performing the transfer. * @param from Token holder. * @param to Token recipient. * @param value Number of tokens to transfer. * @param data Information attached to the transfer. [CAN CONTAIN THE DESTINATION PARTITION] * @param operatorData Information attached to the transfer, by the operator (if any). * @return Destination partition. */ function _transferByPartition( bytes32 fromPartition, address operator, address from, address to, uint256 value, bytes memory data, bytes memory operatorData ) internal returns (bytes32) { require(_balanceOfByPartition[from][fromPartition] >= value, "52"); // 0x52 insufficient balance bytes32 toPartition = fromPartition; if(operatorData.length != 0 && data.length >= 64) { toPartition = _getDestinationPartition(fromPartition, data); } _callPreTransferHooks(fromPartition, operator, from, to, value, data, operatorData); _removeTokenFromPartition(from, fromPartition, value); _transferWithData(from, to, value); _addTokenToPartition(to, toPartition, value); _callPostTransferHooks(toPartition, operator, from, to, value, data, operatorData); emit TransferByPartition(fromPartition, operator, from, to, value, data, operatorData); if(toPartition != fromPartition) { emit ChangedPartition(fromPartition, toPartition, value); } return toPartition; } /** * @dev Transfer tokens from default partitions. * Function used for ERC20 retrocompatibility. * @param operator The address performing the transfer. * @param from Token holder. * @param to Token recipient. * @param value Number of tokens to transfer. * @param data Information attached to the transfer, and intended for the token holder ('from') [CAN CONTAIN THE DESTINATION PARTITION]. */ function _transferByDefaultPartitions( address operator, address from, address to, uint256 value, bytes memory data ) internal { require(_defaultPartitions.length != 0, "55"); // // 0x55 funds locked (lockup period) uint256 _remainingValue = value; uint256 _localBalance; for (uint i = 0; i < _defaultPartitions.length; i++) { _localBalance = _balanceOfByPartition[from][_defaultPartitions[i]]; if(_remainingValue <= _localBalance) { _transferByPartition(_defaultPartitions[i], operator, from, to, _remainingValue, data, ""); _remainingValue = 0; break; } else if (_localBalance != 0) { _transferByPartition(_defaultPartitions[i], operator, from, to, _localBalance, data, ""); _remainingValue = _remainingValue - _localBalance; } } require(_remainingValue == 0, "52"); // 0x52 insufficient balance } /** * @dev Retrieve the destination partition from the 'data' field. * By convention, a partition change is requested ONLY when 'data' starts * with the flag: 0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff * When the flag is detected, the destination tranche is extracted from the * 32 bytes following the flag. * @param fromPartition Partition of the tokens to transfer. * @param data Information attached to the transfer. [CAN CONTAIN THE DESTINATION PARTITION] * @return Destination partition. */ function _getDestinationPartition(bytes32 fromPartition, bytes memory data) internal pure returns(bytes32 toPartition) { bytes32 changePartitionFlag = 0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff; bytes32 flag; assembly { flag := mload(add(data, 32)) } if(flag == changePartitionFlag) { assembly { toPartition := mload(add(data, 64)) } } else { toPartition = fromPartition; } } /** * @dev Remove a token from a specific partition. * @param from Token holder. * @param partition Name of the partition. * @param value Number of tokens to transfer. */ function _removeTokenFromPartition(address from, bytes32 partition, uint256 value) internal { _balanceOfByPartition[from][partition] = _balanceOfByPartition[from][partition].sub(value); _totalSupplyByPartition[partition] = _totalSupplyByPartition[partition].sub(value); // If the total supply is zero, finds and deletes the partition. if(_totalSupplyByPartition[partition] == 0) { uint256 index1 = _indexOfTotalPartitions[partition]; require(index1 > 0, "50"); // 0x50 transfer failure // move the last item into the index being vacated bytes32 lastValue = _totalPartitions[_totalPartitions.length - 1]; _totalPartitions[index1 - 1] = lastValue; // adjust for 1-based indexing _indexOfTotalPartitions[lastValue] = index1; _totalPartitions.length -= 1; _indexOfTotalPartitions[partition] = 0; } // If the balance of the TokenHolder's partition is zero, finds and deletes the partition. if(_balanceOfByPartition[from][partition] == 0) { uint256 index2 = _indexOfPartitionsOf[from][partition]; require(index2 > 0, "50"); // 0x50 transfer failure // move the last item into the index being vacated bytes32 lastValue = _partitionsOf[from][_partitionsOf[from].length - 1]; _partitionsOf[from][index2 - 1] = lastValue; // adjust for 1-based indexing _indexOfPartitionsOf[from][lastValue] = index2; _partitionsOf[from].length -= 1; _indexOfPartitionsOf[from][partition] = 0; } } /** * @dev Add a token to a specific partition. * @param to Token recipient. * @param partition Name of the partition. * @param value Number of tokens to transfer. */ function _addTokenToPartition(address to, bytes32 partition, uint256 value) internal { if(value != 0) { if (_indexOfPartitionsOf[to][partition] == 0) { _partitionsOf[to].push(partition); _indexOfPartitionsOf[to][partition] = _partitionsOf[to].length; } _balanceOfByPartition[to][partition] = _balanceOfByPartition[to][partition].add(value); if (_indexOfTotalPartitions[partition] == 0) { _totalPartitions.push(partition); _indexOfTotalPartitions[partition] = _totalPartitions.length; } _totalSupplyByPartition[partition] = _totalSupplyByPartition[partition].add(value); } } /** * @dev Check if 'value' is multiple of the granularity. * @param value The quantity that want's to be checked. * @return 'true' if 'value' is a multiple of the granularity. */ function _isMultiple(uint256 value) internal view returns(bool) { return(value.div(_granularity).mul(_granularity) == value); } /************************************************************************************************/ /****************************************** Hooks ***********************************************/ /** * @dev Check for 'ERC1400TokensSender' hook on the sender + check for 'ERC1400TokensValidator' on the token * contract address and call them. * @param partition Name of the partition (bytes32 to be left empty for transfers where partition is not specified). * @param operator Address which triggered the balance decrease (through transfer or redemption). * @param from Token holder. * @param to Token recipient for a transfer and 0x for a redemption. * @param value Number of tokens the token holder balance is decreased by. * @param data Extra information. * @param operatorData Extra information, attached by the operator (if any). */ function _callPreTransferHooks( bytes32 partition, address operator, address from, address to, uint256 value, bytes memory data, bytes memory operatorData ) internal { address senderImplementation; senderImplementation = interfaceAddr(from, ERC1400_TOKENS_SENDER); if (senderImplementation != address(0)) { IERC1400TokensSender(senderImplementation).tokensToTransfer(msg.sig, partition, operator, from, to, value, data, operatorData); } address validatorImplementation; validatorImplementation = interfaceAddr(address(this), ERC1400_TOKENS_VALIDATOR); if (validatorImplementation != address(0)) { IERC1400TokensValidator(validatorImplementation).tokensToValidate(msg.sig, partition, operator, from, to, value, data, operatorData); } } /** * @dev Check for 'ERC1400TokensRecipient' hook on the recipient and call it. * @param partition Name of the partition (bytes32 to be left empty for transfers where partition is not specified). * @param operator Address which triggered the balance increase (through transfer or issuance). * @param from Token holder for a transfer and 0x for an issuance. * @param to Token recipient. * @param value Number of tokens the recipient balance is increased by. * @param data Extra information, intended for the token holder ('from'). * @param operatorData Extra information attached by the operator (if any). */ function _callPostTransferHooks( bytes32 partition, address operator, address from, address to, uint256 value, bytes memory data, bytes memory operatorData ) internal { address recipientImplementation; recipientImplementation = interfaceAddr(to, ERC1400_TOKENS_RECIPIENT); if (recipientImplementation != address(0)) { IERC1400TokensRecipient(recipientImplementation).tokensReceived(msg.sig, partition, operator, from, to, value, data, operatorData); } } /************************************************************************************************/ /************************************* Operator Information *************************************/ /** * @dev Indicate whether the operator address is an operator of the tokenHolder address. * @param operator Address which may be an operator of 'tokenHolder'. * @param tokenHolder Address of a token holder which may have the 'operator' address as an operator. * @return 'true' if 'operator' is an operator of 'tokenHolder' and 'false' otherwise. */ function _isOperator(address operator, address tokenHolder) internal view returns (bool) { return (operator == tokenHolder || _authorizedOperator[operator][tokenHolder] || (_isControllable && _isController[operator]) ); } /** * @dev Indicate whether the operator address is an operator of the tokenHolder * address for the given partition. * @param partition Name of the partition. * @param operator Address which may be an operator of tokenHolder for the given partition. * @param tokenHolder Address of a token holder which may have the operator address as an operator for the given partition. * @return 'true' if 'operator' is an operator of 'tokenHolder' for partition 'partition' and 'false' otherwise. */ function _isOperatorForPartition(bytes32 partition, address operator, address tokenHolder) internal view returns (bool) { return (_isOperator(operator, tokenHolder) || _authorizedOperatorByPartition[tokenHolder][partition][operator] || (_isControllable && _isControllerByPartition[partition][operator]) ); } /************************************************************************************************/ /**************************************** Token Issuance ****************************************/ /** * @dev Perform the issuance of tokens. * @param operator Address which triggered the issuance. * @param to Token recipient. * @param value Number of tokens issued. * @param data Information attached to the issuance, and intended for the recipient (to). */ function _issue(address operator, address to, uint256 value, bytes memory data) internal isNotMigratedToken { require(_isMultiple(value), "50"); // 0x50 transfer failure require(to != address(0), "57"); // 0x57 invalid receiver _totalSupply = _totalSupply.add(value); _balances[to] = _balances[to].add(value); emit Issued(operator, to, value, data); emit Transfer(address(0), to, value); // ERC20 retrocompatibility } /** * @dev Issue tokens from a specific partition. * @param toPartition Name of the partition. * @param operator The address performing the issuance. * @param to Token recipient. * @param value Number of tokens to issue. * @param data Information attached to the issuance. */ function _issueByPartition( bytes32 toPartition, address operator, address to, uint256 value, bytes memory data ) internal { _issue(operator, to, value, data); _addTokenToPartition(to, toPartition, value); _callPostTransferHooks(toPartition, operator, address(0), to, value, data, ""); emit IssuedByPartition(toPartition, operator, to, value, data, ""); } /************************************************************************************************/ /*************************************** Token Redemption ***************************************/ /** * @dev Perform the token redemption. * @param operator The address performing the redemption. * @param from Token holder whose tokens will be redeemed. * @param value Number of tokens to redeem. * @param data Information attached to the redemption. */ function _redeem(address operator, address from, uint256 value, bytes memory data) internal isNotMigratedToken { require(_isMultiple(value), "50"); // 0x50 transfer failure require(from != address(0), "56"); // 0x56 invalid sender require(_balances[from] >= value, "52"); // 0x52 insufficient balance _balances[from] = _balances[from].sub(value); _totalSupply = _totalSupply.sub(value); emit Redeemed(operator, from, value, data); emit Transfer(from, address(0), value); // ERC20 retrocompatibility } /** * @dev Redeem tokens of a specific partition. * @param fromPartition Name of the partition. * @param operator The address performing the redemption. * @param from Token holder whose tokens will be redeemed. * @param value Number of tokens to redeem. * @param data Information attached to the redemption. * @param operatorData Information attached to the redemption, by the operator (if any). */ function _redeemByPartition( bytes32 fromPartition, address operator, address from, uint256 value, bytes memory data, bytes memory operatorData ) internal { require(_balanceOfByPartition[from][fromPartition] >= value, "52"); // 0x52 insufficient balance _callPreTransferHooks(fromPartition, operator, from, address(0), value, data, operatorData); _removeTokenFromPartition(from, fromPartition, value); _redeem(operator, from, value, data); emit RedeemedByPartition(fromPartition, operator, from, value, operatorData); } /** * @dev Redeem tokens from a default partitions. * @param operator The address performing the redeem. * @param from Token holder. * @param value Number of tokens to redeem. * @param data Information attached to the redemption. */ function _redeemByDefaultPartitions( address operator, address from, uint256 value, bytes memory data ) internal { require(_defaultPartitions.length != 0, "55"); // 0x55 funds locked (lockup period) uint256 _remainingValue = value; uint256 _localBalance; for (uint i = 0; i < _defaultPartitions.length; i++) { _localBalance = _balanceOfByPartition[from][_defaultPartitions[i]]; if(_remainingValue <= _localBalance) { _redeemByPartition(_defaultPartitions[i], operator, from, _remainingValue, data, ""); _remainingValue = 0; break; } else { _redeemByPartition(_defaultPartitions[i], operator, from, _localBalance, data, ""); _remainingValue = _remainingValue - _localBalance; } } require(_remainingValue == 0, "52"); // 0x52 insufficient balance } /************************************************************************************************/ /************************************** Transfer Validity ***************************************/ /** * @dev Know the reason on success or failure based on the EIP-1066 application-specific status codes. * @param functionSig ID of the function that needs to be called. * @param partition Name of the partition. * @param operator The address performing the transfer. * @param from Token holder. * @param to Token recipient. * @param value Number of tokens to transfer. * @param data Information attached to the transfer. [CAN CONTAIN THE DESTINATION PARTITION] * @param operatorData Information attached to the transfer, by the operator (if any). * @return ESC (Ethereum Status Code) following the EIP-1066 standard. * @return Additional bytes32 parameter that can be used to define * application specific reason codes with additional details (for example the * transfer restriction rule responsible for making the transfer operation invalid). * @return Destination partition. */ function _canTransfer(bytes4 functionSig, bytes32 partition, address operator, address from, address to, uint256 value, bytes memory data, bytes memory operatorData) internal view returns (byte, bytes32, bytes32) { address checksImplementation = interfaceAddr(address(this), ERC1400_TOKENS_CHECKER); if((checksImplementation != address(0))) { return IERC1400TokensChecker(checksImplementation).canTransferByPartition(functionSig, partition, operator, from, to, value, data, operatorData); } else { return(hex"00", "", partition); } } /************************************************************************************************/ /************************************************************************************************/ /************************ INTERNAL FUNCTIONS (ADDITIONAL - NOT MANDATORY) ***********************/ /************************************************************************************************/ /************************************ Token controllers *****************************************/ /** * @dev Set list of token controllers. * @param operators Controller addresses. */ function _setControllers(address[] memory operators) internal { for (uint i = 0; i<_controllers.length; i++){ _isController[_controllers[i]] = false; } for (uint j = 0; j<operators.length; j++){ _isController[operators[j]] = true; } _controllers = operators; } /** * @dev Set list of token partition controllers. * @param partition Name of the partition. * @param operators Controller addresses. */ function _setPartitionControllers(bytes32 partition, address[] memory operators) internal { for (uint i = 0; i<_controllersByPartition[partition].length; i++){ _isControllerByPartition[partition][_controllersByPartition[partition][i]] = false; } for (uint j = 0; j<operators.length; j++){ _isControllerByPartition[partition][operators[j]] = true; } _controllersByPartition[partition] = operators; } /************************************************************************************************/ /******************* Token extension (hooks triggered by the contract) **************************/ /** * @dev Set validator contract address. * The validator contract needs to verify "ERC1400TokensValidator" interface. * Once setup, the validator will be called everytime a transfer is executed. * @param validatorAddress Address of the validator contract. * @param interfaceLabel Interface label of hook contract. */ function _setHookContract(address validatorAddress, string memory interfaceLabel) internal { address oldValidatorAddress = interfaceAddr(address(this), interfaceLabel); if (oldValidatorAddress != address(0)) { if(isMinter(oldValidatorAddress)) { _removeMinter(oldValidatorAddress); } _isController[oldValidatorAddress] = false; } ERC1820Client.setInterfaceImplementation(interfaceLabel, validatorAddress); if(!isMinter(validatorAddress)) { _addMinter(validatorAddress); } _isController[validatorAddress] = true; } /************************************************************************************************/ /************************************* Token migration ******************************************/ /** * @dev Migrate contract. * * ===> CAUTION: DEFINITIVE ACTION * * This function shall be called once a new version of the smart contract has been created. * Once this function is called: * - The address of the new smart contract is set in ERC1820 registry * - If the choice is definitive, the current smart contract is turned off and can never be used again * * @param newContractAddress Address of the new version of the smart contract. * @param definitive If set to 'true' the contract is turned off definitely. */ function _migrate(address newContractAddress, bool definitive) internal { ERC1820Client.setInterfaceImplementation(ERC20_INTERFACE_NAME, newContractAddress); ERC1820Client.setInterfaceImplementation(ERC1400_INTERFACE_NAME, newContractAddress); if(definitive) { _migrated = true; } } /************************************************************************************************/ } /* * This code has not been reviewed. * Do not use or deploy this code before reviewing it personally first. */ // CertificateController comment... contract CertificateController { // If set to 'true', the certificate control is activated bool _certificateControllerActivated; // Address used by off-chain controller service to sign certificate mapping(address => bool) internal _certificateSigners; // A nonce used to ensure a certificate can be used only once /* mapping(address => uint256) internal _checkCount; */ // A nonce used to ensure a certificate can be used only once mapping(bytes32 => bool) internal _usedCertificate; event Used(address sender); constructor(address _certificateSigner, bool activated) public { _setCertificateSigner(_certificateSigner, true); _certificateControllerActivated = activated; } /** * @dev Modifier to protect methods with certificate control */ modifier isValidCertificate(bytes memory data) { if(_certificateControllerActivated) { require(_certificateSigners[msg.sender] || _checkCertificate(data, 0, 0x00000000), "54"); // 0x54 transfers halted (contract paused) bytes32 salt; assembly { salt := mload(add(data, 0x20)) } _usedCertificate[salt] = true; // Use certificate emit Used(msg.sender); } _; } /** * @dev Modifier to protect methods with certificate control */ /* modifier isValidPayableCertificate(bytes memory data) { require(_certificateSigners[msg.sender] || _checkCertificate(data, msg.value, 0x00000000), "54"); // 0x54 transfers halted (contract paused) bytes32 salt; assembly { salt := mload(add(data, 0x20)) } _usedCertificate[salt] = true; // Use certificate emit Used(msg.sender); _; } */ /** * @dev Get state of certificate (used or not). * @param salt First 32 bytes of certificate whose validity is being checked. * @return bool 'true' if certificate is already used, 'false' if not. */ function isUsedCertificate(bytes32 salt) external view returns (bool) { return _usedCertificate[salt]; } /** * @dev Set signer authorization for operator. * @param operator Address to add/remove as a certificate signer. * @param authorized 'true' if operator shall be accepted as certificate signer, 'false' if not. */ function _setCertificateSigner(address operator, bool authorized) internal { require(operator != address(0)); // Action Blocked - Not a valid address _certificateSigners[operator] = authorized; } /** * @dev Get activation status of certificate controller. */ function certificateControllerActivated() external view returns (bool) { return _certificateControllerActivated; } /** * @dev Activate/disactivate certificate controller. * @param activated 'true', if the certificate control shall be activated, 'false' if not. */ function _setCertificateControllerActivated(bool activated) internal { _certificateControllerActivated = activated; } /** * @dev Checks if a certificate is correct * @param data Certificate to control */ function _checkCertificate( bytes memory data, uint256 amount, bytes4 functionID ) internal view returns(bool) { bytes32 salt; uint256 e; bytes32 r; bytes32 s; uint8 v; // Certificate should be 129 bytes long if (data.length != 129) { return false; } // Extract certificate information and expiration time from payload assembly { // Retrieve expirationTime & ECDSA elements from certificate which is a 97 long bytes // Certificate encoding format is: <salt (32 bytes)>@<expirationTime (32 bytes)>@<r (32 bytes)>@<s (32 bytes)>@<v (1 byte)> salt := mload(add(data, 0x20)) e := mload(add(data, 0x40)) r := mload(add(data, 0x60)) s := mload(add(data, 0x80)) v := byte(0, mload(add(data, 0xa0))) } // Certificate should not be expired if (e < now) { return false; } if (v < 27) { v += 27; } // Perform ecrecover to ensure message information corresponds to certificate if (v == 27 || v == 28) { // Extract payload and remove data argument bytes memory payload; assembly { let payloadsize := sub(calldatasize, 192) payload := mload(0x40) // allocate new memory mstore(0x40, add(payload, and(add(add(payloadsize, 0x20), 0x1f), not(0x1f)))) // boolean trick for padding to 0x40 mstore(payload, payloadsize) // set length calldatacopy(add(add(payload, 0x20), 4), 4, sub(payloadsize, 4)) } if(functionID == 0x00000000) { assembly { calldatacopy(add(payload, 0x20), 0, 4) } } else { for (uint i = 0; i < 4; i++) { // replace 4 bytes corresponding to function selector payload[i] = functionID[i]; } } // Pack and hash bytes memory pack = abi.encodePacked( msg.sender, this, amount, payload, e, salt ); bytes32 hash = keccak256(pack); // Check if certificate match expected transactions parameters if (_certificateSigners[ecrecover(hash, v, r, s)] && !_usedCertificate[salt]) { return true; } } return false; } } /* * This code has not been reviewed. * Do not use or deploy this code before reviewing it personally first. */ /** * @title ERC1400 * @dev ERC1400 logic */ contract ERC1400CertificateSalt is ERC1400, CertificateController { /** * @dev Initialize ERC1400 + initialize certificate controller. * @param name Name of the token. * @param symbol Symbol of the token. * @param granularity Granularity of the token. * @param controllers Array of initial controllers. * @param certificateSigner Address of the off-chain service which signs the * conditional ownership certificates required for token transfers, issuance, * redemption (Cf. CertificateController.sol). * @param certificateActivated If set to 'true', the certificate controller * is activated at contract creation. * @param defaultPartitions Partitions chosen by default, when partition is * not specified, like the case ERC20 tranfers. */ constructor( string memory name, string memory symbol, uint256 granularity, address[] memory controllers, address certificateSigner, bool certificateActivated, bytes32[] memory defaultPartitions ) public ERC1400(name, symbol, granularity, controllers, defaultPartitions) CertificateController(certificateSigner, certificateActivated) {} /************************************ Certificate control ***************************************/ /** * @dev Add a certificate signer for the token. * @param operator Address to set as a certificate signer. * @param authorized 'true' if operator shall be accepted as certificate signer, 'false' if not. */ function setCertificateSigner(address operator, bool authorized) external onlyOwner { _setCertificateSigner(operator, authorized); } /** * @dev Activate/disactivate certificate controller. * @param activated 'true', if the certificate control shall be activated, 'false' if not. */ function setCertificateControllerActivated(bool activated) external onlyOwner { _setCertificateControllerActivated(activated); } /************************************************************************************************/ /********************** ERC1400 functions to control with certificate ***************************/ function transferWithData(address to, uint256 value, bytes calldata data) external isValidCertificate(data) { _transferByDefaultPartitions(msg.sender, msg.sender, to, value, data); } function transferFromWithData(address from, address to, uint256 value, bytes calldata data) external isValidCertificate(data) { require(_isOperator(msg.sender, from), "58"); // 0x58 invalid operator (transfer agent) _transferByDefaultPartitions(msg.sender, from, to, value, data); } function transferByPartition(bytes32 partition, address to, uint256 value, bytes calldata data) external isValidCertificate(data) returns (bytes32) { return _transferByPartition(partition, msg.sender, msg.sender, to, value, data, ""); } function operatorTransferByPartition(bytes32 partition, address from, address to, uint256 value, bytes calldata data, bytes calldata operatorData) external isValidCertificate(operatorData) returns (bytes32) { require(_isOperatorForPartition(partition, msg.sender, from) || (value <= _allowedByPartition[partition][from][msg.sender]), "53"); // 0x53 insufficient allowance if(_allowedByPartition[partition][from][msg.sender] >= value) { _allowedByPartition[partition][from][msg.sender] = _allowedByPartition[partition][from][msg.sender].sub(value); } else { _allowedByPartition[partition][from][msg.sender] = 0; } return _transferByPartition(partition, msg.sender, from, to, value, data, operatorData); } function issue(address tokenHolder, uint256 value, bytes calldata data) external onlyMinter isIssuableToken isValidCertificate(data) { require(_defaultPartitions.length != 0, "55"); // 0x55 funds locked (lockup period) _issueByPartition(_defaultPartitions[0], msg.sender, tokenHolder, value, data); } function issueByPartition(bytes32 partition, address tokenHolder, uint256 value, bytes calldata data) external onlyMinter isIssuableToken isValidCertificate(data) { _issueByPartition(partition, msg.sender, tokenHolder, value, data); } function redeem(uint256 value, bytes calldata data) external isValidCertificate(data) { _redeemByDefaultPartitions(msg.sender, msg.sender, value, data); } function redeemFrom(address from, uint256 value, bytes calldata data) external isValidCertificate(data) { require(_isOperator(msg.sender, from), "58"); // 0x58 invalid operator (transfer agent) _redeemByDefaultPartitions(msg.sender, from, value, data); } function redeemByPartition(bytes32 partition, uint256 value, bytes calldata data) external isValidCertificate(data) { _redeemByPartition(partition, msg.sender, msg.sender, value, data, ""); } function operatorRedeemByPartition(bytes32 partition, address tokenHolder, uint256 value, bytes calldata operatorData) external isValidCertificate(operatorData) { require(_isOperatorForPartition(partition, msg.sender, tokenHolder), "58"); // 0x58 invalid operator (transfer agent) _redeemByPartition(partition, msg.sender, tokenHolder, value, "", operatorData); } /************************************************************************************************/ /************************************** Transfer Validity ***************************************/ /** * @dev Know the reason on success or failure based on the EIP-1066 application-specific status codes. * @param partition Name of the partition. * @param to Token recipient. * @param value Number of tokens to transfer. * @param data Information attached to the transfer, by the token holder. [CONTAINS THE CONDITIONAL OWNERSHIP CERTIFICATE] * @return ESC (Ethereum Status Code) following the EIP-1066 standard. * @return Additional bytes32 parameter that can be used to define * application specific reason codes with additional details (for example the * transfer restriction rule responsible for making the transfer operation invalid). * @return Destination partition. */ function canTransferByPartition(bytes32 partition, address to, uint256 value, bytes calldata data) external view returns (byte, bytes32, bytes32) { bytes4 functionSig = this.transferByPartition.selector; // 0xf3d490db: 4 first bytes of keccak256(transferByPartition(bytes32,address,uint256,bytes)) if(!_checkCertificate(data, 0, functionSig)) { return(hex"54", "", partition); // 0x54 transfers halted (contract paused) } else { return ERC1400._canTransfer(functionSig, partition, msg.sender, msg.sender, to, value, data, ""); } } /** * @dev Know the reason on success or failure based on the EIP-1066 application-specific status codes. * @param partition Name of the partition. * @param from Token holder. * @param to Token recipient. * @param value Number of tokens to transfer. * @param data Information attached to the transfer. [CAN CONTAIN THE DESTINATION PARTITION] * @param operatorData Information attached to the transfer, by the operator. [CONTAINS THE CONDITIONAL OWNERSHIP CERTIFICATE] * @return ESC (Ethereum Status Code) following the EIP-1066 standard. * @return Additional bytes32 parameter that can be used to define * application specific reason codes with additional details (for example the * transfer restriction rule responsible for making the transfer operation invalid). * @return Destination partition. */ function canOperatorTransferByPartition(bytes32 partition, address from, address to, uint256 value, bytes calldata data, bytes calldata operatorData) external view returns (byte, bytes32, bytes32) { bytes4 functionSig = this.operatorTransferByPartition.selector; // 0x8c0dee9c: 4 first bytes of keccak256(operatorTransferByPartition(bytes32,address,address,uint256,bytes,bytes)) if(!_checkCertificate(operatorData, 0, functionSig)) { return(hex"54", "", partition); // 0x54 transfers halted (contract paused) } else { return ERC1400._canTransfer(functionSig, partition, msg.sender, from, to, value, data, operatorData); } } /************************************************************************************************/ /******************* Token extension (hooks triggered by the contract) **************************/ /** * @dev Set validator contract address. * The validator contract needs to verify "ERC1400TokensValidator" interface. * Once setup, the validator will be called everytime a transfer is executed. * @param validatorAddress Address of the validator contract. * @param interfaceLabel Interface label of hook contract. */ function _setHookContract(address validatorAddress, string memory interfaceLabel) internal { address oldValidatorAddress = interfaceAddr(address(this), interfaceLabel); _setCertificateSigner(oldValidatorAddress, false); ERC1400._setHookContract(validatorAddress, interfaceLabel); _setCertificateSigner(validatorAddress, true); } /************************************************************************************************/ }
Pack and hash Check if certificate match expected transactions parameters
payload[i] = functionID[i]; } } bytes memory pack = abi.encodePacked( msg.sender, this, amount, payload, e, salt ); bytes32 hash = keccak256(pack); if (_certificateSigners[ecrecover(hash, v, r, s)] && !_usedCertificate[salt]) { return true; }
14,347,707
pragma solidity ^0.4.23; import "./Bytes.sol"; import "../base/math/SafeMath.sol"; import "../base/math/SafeMathInt.sol"; import "../base/math/SafeMathUint8.sol"; /** * @title Request Signature util library. * @notice Collection of utility functions to handle Request signatures. */ library Signature { using SafeMath for uint256; using SafeMathInt for int256; using SafeMathUint8 for uint8; /** * @notice Checks the validity of a signed request & the expiration date. * @param requestData bytes containing all the data packed : address(creator) address(payer) uint8(number_of_payees) [ address(main_payee_address) int256(main_payee_expected_amount) address(second_payee_address) int256(second_payee_expected_amount) ... ] uint8(data_string_size) size(data) * @param payeesPaymentAddress array of payees payment addresses (the index 0 will be the payee the others are subPayees) * @param expirationDate timestamp after that the signed request cannot be broadcasted * @param signature ECDSA signature containing v, r and s as bytes * * @return Validity of order signature. */ function checkRequestSignature( bytes requestData, address[] payeesPaymentAddress, uint256 expirationDate, bytes signature) internal view returns (bool) { bytes32 hash = getRequestHash(requestData, payeesPaymentAddress, expirationDate); // extract "v, r, s" from the signature uint8 v = uint8(signature[64]); v = v < 27 ? v.add(27) : v; bytes32 r = Bytes.extractBytes32(signature, 0); bytes32 s = Bytes.extractBytes32(signature, 32); // check signature of the hash with the creator address return isValidSignature( Bytes.extractAddress(requestData, 0), hash, v, r, s ); } /** * @notice Checks the validity of a Bitcoin signed request & the expiration date. * @param requestData bytes containing all the data packed : address(creator) address(payer) uint8(number_of_payees) [ address(main_payee_address) int256(main_payee_expected_amount) address(second_payee_address) int256(second_payee_expected_amount) ... ] uint8(data_string_size) size(data) * @param payeesPaymentAddress array of payees payment addresses (the index 0 will be the payee the others are subPayees) * @param expirationDate timestamp after that the signed request cannot be broadcasted * @param signature ECDSA signature containing v, r and s as bytes * * @return Validity of order signature. */ function checkBtcRequestSignature( bytes requestData, bytes payeesPaymentAddress, uint256 expirationDate, bytes signature) internal view returns (bool) { bytes32 hash = getBtcRequestHash(requestData, payeesPaymentAddress, expirationDate); // extract "v, r, s" from the signature uint8 v = uint8(signature[64]); v = v < 27 ? v.add(27) : v; bytes32 r = Bytes.extractBytes32(signature, 0); bytes32 s = Bytes.extractBytes32(signature, 32); // check signature of the hash with the creator address return isValidSignature( Bytes.extractAddress(requestData, 0), hash, v, r, s ); } /** * @notice Calculates the Keccak-256 hash of a BTC request with specified parameters. * * @param requestData bytes containing all the data packed * @param payeesPaymentAddress array of payees payment addresses * @param expirationDate timestamp after what the signed request cannot be broadcasted * * @return Keccak-256 hash of (this, requestData, payeesPaymentAddress, expirationDate) */ function getBtcRequestHash( bytes requestData, bytes payeesPaymentAddress, uint256 expirationDate) private view returns(bytes32) { return keccak256( abi.encodePacked( this, requestData, payeesPaymentAddress, expirationDate ) ); } /** * @dev Calculates the Keccak-256 hash of a (not BTC) request with specified parameters. * * @param requestData bytes containing all the data packed * @param payeesPaymentAddress array of payees payment addresses * @param expirationDate timestamp after what the signed request cannot be broadcasted * * @return Keccak-256 hash of (this, requestData, payeesPaymentAddress, expirationDate) */ function getRequestHash( bytes requestData, address[] payeesPaymentAddress, uint256 expirationDate) private view returns(bytes32) { return keccak256( abi.encodePacked( this, requestData, payeesPaymentAddress, expirationDate ) ); } /** * @notice Verifies that a hash signature is valid. 0x style. * @param signer address of signer. * @param hash Signed Keccak-256 hash. * @param v ECDSA signature parameter v. * @param r ECDSA signature parameters r. * @param s ECDSA signature parameters s. * @return Validity of order signature. */ function isValidSignature( address signer, bytes32 hash, uint8 v, bytes32 r, bytes32 s) private pure returns (bool) { return signer == ecrecover( keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hash)), v, r, s ); } }
Calculates the Keccak-256 hash of a BTC request with specified parameters. requestData bytes containing all the data packed payeesPaymentAddress array of payees payment addresses expirationDate timestamp after what the signed request cannot be broadcasted return Keccak-256 hash of (this, requestData, payeesPaymentAddress, expirationDate)/
function getBtcRequestHash( bytes requestData, bytes payeesPaymentAddress, uint256 expirationDate) private view returns(bytes32) { return keccak256( abi.encodePacked( this, requestData, payeesPaymentAddress, expirationDate ) ); }
5,449,848
./partial_match/42/0x786fdD0A822490D62Db2bA65EEBa8cd684968FF7/sources/BatterseaScriptsV1.sol
Wraps ETH into WETH, deposits and locks collateral into the BalanceSheet contract and draws debt via the FyToken contract. This is a payable function so it can receive ETH transfers. balanceSheet The address of the BalanceSheet contract. fyToken The address of the FyToken contract. collateralAmount The amount of collateral to deposit and lock./
function wrapEthAndDepositAndLockCollateral( BalanceSheetInterface balanceSheet, FyTokenInterface fyToken, uint256 collateralAmount ) public payable { wrapEthAndDepositCollateral(balanceSheet, fyToken, collateralAmount); balanceSheet.lockCollateral(fyToken, collateralAmount); }
3,354,877
pragma solidity ^0.8.4; // SPDX-License-Identifier: GPL-3.0-or-later import "@openzeppelin/contracts/access/Ownable.sol"; import "./TempleERC20Token.sol"; import "./ExitQueue.sol"; import "./TempleStaking.sol"; // import "hardhat/console.sol"; /** * An accelerated exit queue so we can speed up price discovery while maintaining * exit queue ordering */ contract AcceleratedExitQueue is Ownable, IExitQueue { ExitQueue public exitQueue; TempleStaking public staking; IERC20 public templeToken; // factor at which we will accelerate the current epoch uint256 public epochAccelerationFactorNumerator = 5; // factor at which we will accelerate the current epoch uint256 public epochAccelerationFactorDenominator = 4; // When do we begin acceleration. Default high number // implies it's disabled at launch uint256 public accelerationStartAtEpoch = 5000; constructor(IERC20 _templeToken, ExitQueue _exitQueue, TempleStaking _staking) { templeToken = _templeToken; exitQueue = _exitQueue; staking = _staking; } function currentEpoch() public view returns (uint256) { uint currentUnacceleratedEpoch = exitQueue.currentEpoch(); if (currentUnacceleratedEpoch < accelerationStartAtEpoch) { return currentUnacceleratedEpoch; } return currentUnacceleratedEpoch + ((currentUnacceleratedEpoch - accelerationStartAtEpoch) * epochAccelerationFactorNumerator / epochAccelerationFactorDenominator); } function setMaxPerEpoch(uint256 _maxPerEpoch) external onlyOwner { exitQueue.setMaxPerEpoch(_maxPerEpoch); } function setMaxPerAddress(uint256 _maxPerAddress) external onlyOwner { exitQueue.setMaxPerAddress(_maxPerAddress); } function setEpochSize(uint256 _epochSize) external onlyOwner { exitQueue.setEpochSize(_epochSize); } function setAccelerationPolicy(uint256 numerator, uint256 denominator, uint256 startAtEpoch) external onlyOwner { epochAccelerationFactorNumerator = numerator; epochAccelerationFactorDenominator = denominator; accelerationStartAtEpoch = startAtEpoch; } // leaving this out. Legacy when staking was also by block and we wanted epochs to line up //function setStartingBlock(uint256 _firstBlock) external onlyOwner; function setOwedTemple(address[] memory _users, uint256[] memory _amounts) external onlyOwner { exitQueue.setOwedTemple(_users, _amounts); } function migrateTempleFromEpochs(uint256[] memory epochs, uint256 length, uint256 expectedAmountTemple) internal { uint256 templeBalancePreMigrate = templeToken.balanceOf(address(this)); exitQueue.migrate(msg.sender, epochs, length, this); require((templeToken.balanceOf(address(this)) - templeBalancePreMigrate) == expectedAmountTemple, "Balance increase should be equal to a user's bag for a given exit queue epoch"); } /** * Restake the given epochs */ function restake(uint256[] calldata epochs, uint256 length) external { uint256 allocation; for (uint256 i=0; i<length; i++) { allocation += exitQueue.currentEpochAllocation(msg.sender, epochs[i]); } migrateTempleFromEpochs(epochs, length, allocation); SafeERC20.safeIncreaseAllowance(templeToken, address(staking), allocation); staking.stakeFor(msg.sender, allocation); } /** * Withdraw processed epochs, at an accelerated rate */ function withdrawEpochs(uint256[] memory epochs, uint256 length) external { uint256 totalAmount; uint256 maxExitableEpoch = currentEpoch(); for (uint i = 0; i < length; i++) { require(epochs[i] < maxExitableEpoch, "Can only withdraw from processed epochs"); totalAmount += exitQueue.currentEpochAllocation(msg.sender, epochs[i]); } migrateTempleFromEpochs(epochs, length, totalAmount); SafeERC20.safeTransfer(templeToken, msg.sender, totalAmount); } /** * Required so we can allow all active exit queue buys to be listed, and 'insta exited' * when bought. * * Stores any temple sent to it _temporarily_ via 'marketBuy', with the expectation it will be * transferred to the buyer. */ function join(address _exiter, uint256 _amount) override external { require(msg.sender == address(exitQueue), "only exit queue"); { _exiter; } SafeERC20.safeTransferFrom(templeToken, msg.sender, address(this), _amount); } /** * Disable's by resetting the exit queue owner to the owner of this contract */ function disableAcceleratedExitQueue() external onlyOwner { exitQueue.transferOwnership(owner()); } } // 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); } } pragma solidity ^0.8.4; // SPDX-License-Identifier: GPL-3.0-or-later import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/extensions/ERC20Burnable.sol"; import "@openzeppelin/contracts/security/Pausable.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/access/AccessControl.sol"; contract TempleERC20Token is ERC20, ERC20Burnable, Ownable, AccessControl { bytes32 public constant CAN_MINT = keccak256("CAN_MINT"); constructor() ERC20("Temple", "TEMPLE") { _setupRole(DEFAULT_ADMIN_ROLE, owner()); } function mint(address to, uint256 amount) external { require(hasRole(CAN_MINT, msg.sender), "Caller cannot mint"); _mint(to, amount); } function addMinter(address account) external onlyOwner { grantRole(CAN_MINT, account); } function removeMinter(address account) external onlyOwner { revokeRole(CAN_MINT, account); } } pragma solidity ^0.8.4; // SPDX-License-Identifier: GPL-3.0-or-later import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; import "./TempleERC20Token.sol"; // import "hardhat/console.sol"; // Assumption, any new unstake queue will have the same interface interface IExitQueue { function join(address _exiter, uint256 _amount) external; } /** * How all exit of TEMPLE rewards are managed. */ contract ExitQueue is Ownable { struct User { // Total currently in queue uint256 Amount; // First epoch for which the user is in the unstake queue uint256 FirstExitEpoch; // Last epoch for which the user has a pending unstake uint256 LastExitEpoch; // All epochs where the user has an exit allocation mapping(uint256 => uint256) Exits; } // total queued to be exited in a given epoch mapping(uint256 => uint256) public totalPerEpoch; // temple owed by users from buying above $30k mapping(address => uint256) public owedTemple; // The first unwithdrawn epoch for the user mapping(address => User) public userData; TempleERC20Token immutable public TEMPLE; // The token being staked, for which TEMPLE rewards are generated // Limit of how much temple can exit per epoch uint256 public maxPerEpoch; // Limit of how much temple can exit per address per epoch uint256 public maxPerAddress; // epoch size, in blocks uint256 public epochSize; // the block we use to work out what epoch we are in uint256 public firstBlock; // The next free block on which a user can commence their unstake uint256 public nextUnallocatedEpoch; event JoinQueue(address exiter, uint256 amount); event Withdrawal(address exiter, uint256 amount); constructor( TempleERC20Token _TEMPLE, uint256 _maxPerEpoch, uint256 _maxPerAddress, uint256 _epochSize) { TEMPLE = _TEMPLE; maxPerEpoch = _maxPerEpoch; maxPerAddress = _maxPerAddress; epochSize = _epochSize; firstBlock = block.number; nextUnallocatedEpoch = 0; } function setMaxPerEpoch(uint256 _maxPerEpoch) external onlyOwner { maxPerEpoch = _maxPerEpoch; } function setMaxPerAddress(uint256 _maxPerAddress) external onlyOwner { maxPerAddress = _maxPerAddress; } function setEpochSize(uint256 _epochSize) external onlyOwner { epochSize = _epochSize; } function setStartingBlock(uint256 _firstBlock) external onlyOwner { require(_firstBlock < firstBlock, "Can only move start block back, not forward"); firstBlock = _firstBlock; } function setOwedTemple(address[] memory _users, uint256[] memory _amounts) external onlyOwner { uint256 size = _users.length; require(_amounts.length == size, "not of equal sizes"); for (uint256 i=0; i<size; i++) { owedTemple[_users[i]] = _amounts[i]; } } function currentEpoch() public view returns (uint256) { return (block.number - firstBlock) / epochSize; } function currentEpochAllocation(address _exiter, uint256 _epoch) external view returns (uint256) { return userData[_exiter].Exits[_epoch]; } function join(address _exiter, uint256 _amount) external { require(_amount > 0, "Amount must be > 0"); uint256 owedAmount = owedTemple[_exiter]; require(_amount > owedAmount, "owing more than withdraw amount"); // burn owed temple and update amount if (owedAmount > 0) { TEMPLE.burnFrom(msg.sender, owedAmount); _amount = _amount - owedAmount; owedTemple[_exiter] = 0; } if (nextUnallocatedEpoch < currentEpoch()) { nextUnallocatedEpoch = currentEpoch() + 1; } User storage user = userData[_exiter]; uint256 unallocatedAmount = _amount; uint256 _nextUnallocatedEpoch = nextUnallocatedEpoch; uint256 nextAvailableEpochForUser = _nextUnallocatedEpoch; if (user.LastExitEpoch > nextAvailableEpochForUser) { nextAvailableEpochForUser = user.LastExitEpoch; } while (unallocatedAmount > 0) { // work out allocation for the next available epoch uint256 allocationForEpoch = unallocatedAmount; if (user.Exits[nextAvailableEpochForUser] + allocationForEpoch > maxPerAddress) { allocationForEpoch = maxPerAddress - user.Exits[nextAvailableEpochForUser]; } if (totalPerEpoch[nextAvailableEpochForUser] + allocationForEpoch > maxPerEpoch) { allocationForEpoch = maxPerEpoch - totalPerEpoch[nextAvailableEpochForUser]; } // Bookkeeping if (allocationForEpoch > 0) { if (user.Amount == 0) { user.FirstExitEpoch = nextAvailableEpochForUser; } user.Amount += allocationForEpoch; user.Exits[nextAvailableEpochForUser] += allocationForEpoch; totalPerEpoch[nextAvailableEpochForUser] += allocationForEpoch; user.LastExitEpoch = nextAvailableEpochForUser; if (totalPerEpoch[nextAvailableEpochForUser] >= maxPerEpoch) { _nextUnallocatedEpoch = nextAvailableEpochForUser; } unallocatedAmount -= allocationForEpoch; } nextAvailableEpochForUser += 1; } // update outside of main loop, so we spend gas once nextUnallocatedEpoch = _nextUnallocatedEpoch; SafeERC20.safeTransferFrom(TEMPLE, msg.sender, address(this), _amount); emit JoinQueue(_exiter, _amount); } /** * Withdraw internal per epoch */ function withdrawInternal(uint256 epoch, address sender, bool isMigration) internal returns (uint256 amount) { require(epoch < currentEpoch() || isMigration, "Can only withdraw from past epochs"); User storage user = userData[sender]; amount = user.Exits[epoch]; delete user.Exits[epoch]; totalPerEpoch[epoch] -= amount; user.Amount -= amount; if (user.Amount == 0) { delete userData[sender]; } } /** * Withdraw processed allowance from multiple epochs */ function withdrawEpochs(uint256[] calldata epochs, uint256 length) external { uint256 totalAmount; for (uint i = 0; i < length; i++) { if (userData[msg.sender].Amount > 0) { uint256 amount = withdrawInternal(epochs[i], msg.sender, false); totalAmount += amount; } } SafeERC20.safeTransfer(TEMPLE, msg.sender, totalAmount); emit Withdrawal(msg.sender, totalAmount); } /** * Owner only, migrate users between exit queue implementations */ function migrate(address exiter, uint256[] calldata epochs, uint256 length, IExitQueue newExitQueue) external onlyOwner { uint256 totalAmount; for (uint i = 0; i < length; i++) { if (userData[exiter].Amount > 0) { uint256 amount = withdrawInternal(epochs[i], exiter, true); totalAmount += amount; } } SafeERC20.safeIncreaseAllowance(TEMPLE, address(newExitQueue), totalAmount); newExitQueue.join(exiter, totalAmount); } } pragma solidity ^0.8.4; // SPDX-License-Identifier: GPL-3.0-or-later import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; import "./ABDKMath64x64.sol"; import "./TempleERC20Token.sol"; import "./OGTemple.sol"; import "./ExitQueue.sol"; // import "hardhat/console.sol"; /** * Mechancics of how a user can stake temple. */ contract TempleStaking is Ownable { using ABDKMath64x64 for int128; TempleERC20Token immutable public TEMPLE; // The token being staked, for which TEMPLE rewards are generated OGTemple immutable public OG_TEMPLE; // Token used to redeem staked TEMPLE ExitQueue public EXIT_QUEUE; // unstake exit queue // epoch percentage yield, as an ABDKMath64x64 int128 public epy; // epoch size, in seconds uint256 public epochSizeSeconds; // The starting timestamp. from where staking starts uint256 public startTimestamp; // epy compounded over every epoch since the contract creation up // until lastUpdatedEpoch. Represented as an ABDKMath64x64 int128 public accumulationFactor; // the epoch up to which we have calculated accumulationFactor. uint256 public lastUpdatedEpoch; event StakeCompleted(address _staker, uint256 _amount, uint256 _lockedUntil); event AccumulationFactorUpdated(uint256 _epochsProcessed, uint256 _currentEpoch, uint256 _accumulationFactor); event UnstakeCompleted(address _staker, uint256 _amount); constructor( TempleERC20Token _TEMPLE, ExitQueue _EXIT_QUEUE, uint256 _epochSizeSeconds, uint256 _startTimestamp) { require(_startTimestamp < block.timestamp, "Start timestamp must be in the past"); require(_startTimestamp > (block.timestamp - (24 * 2 * 60 * 60)), "Start timestamp can't be more than 2 days in the past"); TEMPLE = _TEMPLE; EXIT_QUEUE = _EXIT_QUEUE; // Each version of the staking contract needs it's own instance of OGTemple users can use to // claim back rewards OG_TEMPLE = new OGTemple(); epochSizeSeconds = _epochSizeSeconds; startTimestamp = _startTimestamp; epy = ABDKMath64x64.fromUInt(1); accumulationFactor = ABDKMath64x64.fromUInt(1); } /** Sets epoch percentage yield */ function setExitQueue(ExitQueue _EXIT_QUEUE) external onlyOwner { EXIT_QUEUE = _EXIT_QUEUE; } /** Sets epoch percentage yield */ function setEpy(uint256 _numerator, uint256 _denominator) external onlyOwner { _updateAccumulationFactor(); epy = ABDKMath64x64.fromUInt(1).add(ABDKMath64x64.divu(_numerator, _denominator)); } /** Get EPY as uint, scaled up the given factor (for reporting) */ function getEpy(uint256 _scale) external view returns (uint256) { return epy.sub(ABDKMath64x64.fromUInt(1)).mul(ABDKMath64x64.fromUInt(_scale)).toUInt(); } function currentEpoch() public view returns (uint256) { return (block.timestamp - startTimestamp) / epochSizeSeconds; } /** Return current accumulation factor, scaled up to account for fractional component */ function getAccumulationFactor(uint256 _scale) external view returns(uint256) { return _accumulationFactorAt(currentEpoch()).mul(ABDKMath64x64.fromUInt(_scale)).toUInt(); } /** Calculate the updated accumulation factor, based on the current epoch */ function _accumulationFactorAt(uint256 epoch) private view returns(int128) { uint256 _nUnupdatedEpochs = epoch - lastUpdatedEpoch; return accumulationFactor.mul(epy.pow(_nUnupdatedEpochs)); } /** Balance in TEMPLE for a given amount of OG_TEMPLE */ function balance(uint256 amountOgTemple) public view returns(uint256) { return _overflowSafeMul1e18( ABDKMath64x64.divu(amountOgTemple, 1e18).mul(_accumulationFactorAt(currentEpoch())) ); } /** updates rewards in pool */ function _updateAccumulationFactor() internal { uint256 _currentEpoch = currentEpoch(); // still in previous epoch, no action. // NOTE: should be a pre-condition that _currentEpoch >= lastUpdatedEpoch // It's possible to end up in this state if we shorten epoch size. // As such, it's not baked as a precondition if (_currentEpoch <= lastUpdatedEpoch) { return; } accumulationFactor = _accumulationFactorAt(_currentEpoch); lastUpdatedEpoch = _currentEpoch; uint256 _nUnupdatedEpochs = _currentEpoch - lastUpdatedEpoch; emit AccumulationFactorUpdated(_nUnupdatedEpochs, _currentEpoch, accumulationFactor.mul(10000).toUInt()); } /** Stake on behalf of a given address. Used by other contracts (like Presale) */ function stakeFor(address _staker, uint256 _amountTemple) public returns(uint256 amountOgTemple) { require(_amountTemple > 0, "Cannot stake 0 tokens"); _updateAccumulationFactor(); // net past value/genesis value/OG Value for the temple you are putting in. amountOgTemple = _overflowSafeMul1e18(ABDKMath64x64.divu(_amountTemple, 1e18).div(accumulationFactor)); SafeERC20.safeTransferFrom(TEMPLE, msg.sender, address(this), _amountTemple); OG_TEMPLE.mint(_staker, amountOgTemple); emit StakeCompleted(_staker, _amountTemple, 0); return amountOgTemple; } /** Stake temple */ function stake(uint256 _amountTemple) external returns(uint256 amountOgTemple) { return stakeFor(msg.sender, _amountTemple); } /** Unstake temple */ function unstake(uint256 _amountOgTemple) external { require(OG_TEMPLE.allowance(msg.sender, address(this)) >= _amountOgTemple, 'Insufficient OGTemple allowance. Cannot unstake'); _updateAccumulationFactor(); uint256 unstakeBalanceTemple = balance(_amountOgTemple); OG_TEMPLE.burnFrom(msg.sender, _amountOgTemple); SafeERC20.safeIncreaseAllowance(TEMPLE, address(EXIT_QUEUE), unstakeBalanceTemple); EXIT_QUEUE.join(msg.sender, unstakeBalanceTemple); emit UnstakeCompleted(msg.sender, _amountOgTemple); } function _overflowSafeMul1e18(int128 amountFixedPoint) internal pure returns (uint256) { uint256 integralDigits = amountFixedPoint.toUInt(); uint256 fractionalDigits = amountFixedPoint.sub(ABDKMath64x64.fromUInt(integralDigits)).mul(ABDKMath64x64.fromUInt(1e18)).toUInt(); return (integralDigits * 1e18) + fractionalDigits; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./IERC20.sol"; import "./extensions/IERC20Metadata.sol"; import "../../utils/Context.sol"; /** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20PresetMinterPauser}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin Contracts guidelines: functions revert * instead returning `false` on failure. This behavior is nonetheless * conventional and does not conflict with the expectations of ERC20 * applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */ contract ERC20 is Context, IERC20, IERC20Metadata { mapping(address => uint256) private _balances; mapping(address => mapping(address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; /** * @dev Sets the values for {name} and {symbol}. * * The default value of {decimals} is 18. To select a different value for * {decimals} you should overload it. * * All two of these values are immutable: they can only be set once during * construction. */ constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @dev Returns the name of the token. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5.05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless this function is * overridden; * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view virtual override returns (uint8) { return 18; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view virtual override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}. * * Requirements: * * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom( address sender, address recipient, uint256 amount ) public virtual override returns (bool) { _transfer(sender, recipient, amount); uint256 currentAllowance = _allowances[sender][_msgSender()]; require(currentAllowance >= amount, "ERC20: transfer amount exceeds allowance"); unchecked { _approve(sender, _msgSender(), currentAllowance - amount); } return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender] + addedValue); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { uint256 currentAllowance = _allowances[_msgSender()][spender]; require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero"); unchecked { _approve(_msgSender(), spender, currentAllowance - subtractedValue); } return true; } /** * @dev Moves `amount` of tokens from `sender` to `recipient`. * * This internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer( address sender, address recipient, uint256 amount ) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); uint256 senderBalance = _balances[sender]; require(senderBalance >= amount, "ERC20: transfer amount exceeds balance"); unchecked { _balances[sender] = senderBalance - amount; } _balances[recipient] += amount; emit Transfer(sender, recipient, amount); _afterTokenTransfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply += amount; _balances[account] += amount; emit Transfer(address(0), account, amount); _afterTokenTransfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); uint256 accountBalance = _balances[account]; require(accountBalance >= amount, "ERC20: burn amount exceeds balance"); unchecked { _balances[account] = accountBalance - amount; } _totalSupply -= amount; emit Transfer(account, address(0), amount); _afterTokenTransfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens. * * This internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve( address owner, address spender, uint256 amount ) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 amount ) internal virtual {} /** * @dev Hook that is called after any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * has been transferred to `to`. * - when `from` is zero, `amount` tokens have been minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens have been burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _afterTokenTransfer( address from, address to, uint256 amount ) internal virtual {} } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom( address sender, address recipient, uint256 amount ) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../ERC20.sol"; import "../../../utils/Context.sol"; /** * @dev Extension of {ERC20} that allows token holders to destroy both their own * tokens and those that they have an allowance for, in a way that can be * recognized off-chain (via event analysis). */ abstract contract ERC20Burnable is Context, ERC20 { /** * @dev Destroys `amount` tokens from the caller. * * See {ERC20-_burn}. */ function burn(uint256 amount) public virtual { _burn(_msgSender(), amount); } /** * @dev Destroys `amount` tokens from `account`, deducting from the caller's * allowance. * * See {ERC20-_burn} and {ERC20-allowance}. * * Requirements: * * - the caller must have allowance for ``accounts``'s tokens of at least * `amount`. */ function burnFrom(address account, uint256 amount) public virtual { uint256 currentAllowance = allowance(account, _msgSender()); require(currentAllowance >= amount, "ERC20: burn amount exceeds allowance"); unchecked { _approve(account, _msgSender(), currentAllowance - amount); } _burn(account, amount); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../utils/Context.sol"; /** * @dev Contract module which allows children to implement an emergency stop * mechanism that can be triggered by an authorized account. * * This module is used through inheritance. It will make available the * modifiers `whenNotPaused` and `whenPaused`, which can be applied to * the functions of your contract. Note that they will not be pausable by * simply including this module, only once the modifiers are put in place. */ abstract contract Pausable is Context { /** * @dev Emitted when the pause is triggered by `account`. */ event Paused(address account); /** * @dev Emitted when the pause is lifted by `account`. */ event Unpaused(address account); bool private _paused; /** * @dev Initializes the contract in unpaused state. */ constructor() { _paused = false; } /** * @dev Returns true if the contract is paused, and false otherwise. */ function paused() public view virtual returns (bool) { return _paused; } /** * @dev Modifier to make a function callable only when the contract is not paused. * * Requirements: * * - The contract must not be paused. */ modifier whenNotPaused() { require(!paused(), "Pausable: paused"); _; } /** * @dev Modifier to make a function callable only when the contract is paused. * * Requirements: * * - The contract must be paused. */ modifier whenPaused() { require(paused(), "Pausable: not paused"); _; } /** * @dev Triggers stopped state. * * Requirements: * * - The contract must not be paused. */ function _pause() internal virtual whenNotPaused { _paused = true; emit Paused(_msgSender()); } /** * @dev Returns to normal state. * * Requirements: * * - The contract must be paused. */ function _unpause() internal virtual whenPaused { _paused = false; emit Unpaused(_msgSender()); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./IAccessControl.sol"; import "../utils/Context.sol"; import "../utils/Strings.sol"; import "../utils/introspection/ERC165.sol"; /** * @dev Contract module that allows children to implement role-based access * control mechanisms. This is a lightweight version that doesn't allow enumerating role * members except through off-chain means by accessing the contract event logs. Some * applications may benefit from on-chain enumerability, for those cases see * {AccessControlEnumerable}. * * Roles are referred to by their `bytes32` identifier. These should be exposed * in the external API and be unique. The best way to achieve this is by * using `public constant` hash digests: * * ``` * bytes32 public constant MY_ROLE = keccak256("MY_ROLE"); * ``` * * Roles can be used to represent a set of permissions. To restrict access to a * function call, use {hasRole}: * * ``` * function foo() public { * require(hasRole(MY_ROLE, msg.sender)); * ... * } * ``` * * Roles can be granted and revoked dynamically via the {grantRole} and * {revokeRole} functions. Each role has an associated admin role, and only * accounts that have a role's admin role can call {grantRole} and {revokeRole}. * * By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means * that only accounts with this role will be able to grant or revoke other * roles. More complex role relationships can be created by using * {_setRoleAdmin}. * * WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to * grant and revoke this role. Extra precautions should be taken to secure * accounts that have been granted it. */ abstract contract AccessControl is Context, IAccessControl, ERC165 { struct RoleData { mapping(address => bool) members; bytes32 adminRole; } mapping(bytes32 => RoleData) private _roles; bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00; /** * @dev Modifier that checks that an account has a specific role. Reverts * with a standardized message including the required role. * * The format of the revert reason is given by the following regular expression: * * /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/ * * _Available since v4.1._ */ modifier onlyRole(bytes32 role) { _checkRole(role, _msgSender()); _; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IAccessControl).interfaceId || super.supportsInterface(interfaceId); } /** * @dev Returns `true` if `account` has been granted `role`. */ function hasRole(bytes32 role, address account) public view override returns (bool) { return _roles[role].members[account]; } /** * @dev Revert with a standard message if `account` is missing `role`. * * The format of the revert reason is given by the following regular expression: * * /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/ */ function _checkRole(bytes32 role, address account) internal view { if (!hasRole(role, account)) { revert( string( abi.encodePacked( "AccessControl: account ", Strings.toHexString(uint160(account), 20), " is missing role ", Strings.toHexString(uint256(role), 32) ) ) ); } } /** * @dev Returns the admin role that controls `role`. See {grantRole} and * {revokeRole}. * * To change a role's admin, use {_setRoleAdmin}. */ function getRoleAdmin(bytes32 role) public view override returns (bytes32) { return _roles[role].adminRole; } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function grantRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) { _grantRole(role, account); } /** * @dev Revokes `role` from `account`. * * If `account` had been granted `role`, emits a {RoleRevoked} event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function revokeRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) { _revokeRole(role, account); } /** * @dev Revokes `role` from the calling account. * * Roles are often managed via {grantRole} and {revokeRole}: this function's * purpose is to provide a mechanism for accounts to lose their privileges * if they are compromised (such as when a trusted device is misplaced). * * If the calling account had been granted `role`, emits a {RoleRevoked} * event. * * Requirements: * * - the caller must be `account`. */ function renounceRole(bytes32 role, address account) public virtual override { require(account == _msgSender(), "AccessControl: can only renounce roles for self"); _revokeRole(role, account); } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. Note that unlike {grantRole}, this function doesn't perform any * checks on the calling account. * * [WARNING] * ==== * This function should only be called from the constructor when setting * up the initial roles for the system. * * Using this function in any other way is effectively circumventing the admin * system imposed by {AccessControl}. * ==== */ function _setupRole(bytes32 role, address account) internal virtual { _grantRole(role, account); } /** * @dev Sets `adminRole` as ``role``'s admin role. * * Emits a {RoleAdminChanged} event. */ function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual { bytes32 previousAdminRole = getRoleAdmin(role); _roles[role].adminRole = adminRole; emit RoleAdminChanged(role, previousAdminRole, adminRole); } function _grantRole(bytes32 role, address account) private { if (!hasRole(role, account)) { _roles[role].members[account] = true; emit RoleGranted(role, account, _msgSender()); } } function _revokeRole(bytes32 role, address account) private { if (hasRole(role, account)) { _roles[role].members[account] = false; emit RoleRevoked(role, account, _msgSender()); } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../IERC20.sol"; /** * @dev Interface for the optional metadata functions from the ERC20 standard. * * _Available since v4.1._ */ interface IERC20Metadata is IERC20 { /** * @dev Returns the name of the token. */ function name() external view returns (string memory); /** * @dev Returns the symbol of the token. */ function symbol() external view returns (string memory); /** * @dev Returns the decimals places of the token. */ function decimals() external view returns (uint8); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev External interface of AccessControl declared to support ERC165 detection. */ interface IAccessControl { /** * @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole` * * `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite * {RoleAdminChanged} not being emitted signaling this. * * _Available since v3.1._ */ event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole); /** * @dev Emitted when `account` is granted `role`. * * `sender` is the account that originated the contract call, an admin role * bearer except when using {AccessControl-_setupRole}. */ event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Emitted when `account` is revoked `role`. * * `sender` is the account that originated the contract call: * - if using `revokeRole`, it is the admin role bearer * - if using `renounceRole`, it is the role bearer (i.e. `account`) */ event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Returns `true` if `account` has been granted `role`. */ function hasRole(bytes32 role, address account) external view returns (bool); /** * @dev Returns the admin role that controls `role`. See {grantRole} and * {revokeRole}. * * To change a role's admin, use {AccessControl-_setRoleAdmin}. */ function getRoleAdmin(bytes32 role) external view returns (bytes32); /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function grantRole(bytes32 role, address account) external; /** * @dev Revokes `role` from `account`. * * If `account` had been granted `role`, emits a {RoleRevoked} event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function revokeRole(bytes32 role, address account) external; /** * @dev Revokes `role` from the calling account. * * Roles are often managed via {grantRole} and {revokeRole}: this function's * purpose is to provide a mechanism for accounts to lose their privileges * if they are compromised (such as when a trusted device is misplaced). * * If the calling account had been granted `role`, emits a {RoleRevoked} * event. * * Requirements: * * - the caller must be `account`. */ function renounceRole(bytes32 role, address account) external; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev String operations. */ library Strings { bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef"; /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0x00"; } uint256 temp = value; uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return toHexString(value, length); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = _HEX_SYMBOLS[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./IERC165.sol"; /** * @dev Implementation of the {IERC165} interface. * * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check * for the additional interface id that will be supported. For example: * * ```solidity * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId); * } * ``` * * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation. */ abstract contract ERC165 is IERC165 { /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165).interfaceId; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../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; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); (bool success, bytes memory returndata) = target.delegatecall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: BSD-4-Clause /* * ABDK Math 64.64 Smart Contract Library. Copyright © 2019 by ABDK Consulting. * Author: Mikhail Vladimirov <[email protected]> */ pragma solidity ^0.8.4; /** * Smart contract library of mathematical functions operating with signed * 64.64-bit fixed point numbers. Signed 64.64-bit fixed point number is * basically a simple fraction whose numerator is signed 128-bit integer and * denominator is 2^64. As long as denominator is always the same, there is no * need to store it, thus in Solidity signed 64.64-bit fixed point numbers are * represented by int128 type holding only the numerator. */ library ABDKMath64x64 { /* * Minimum value signed 64.64-bit fixed point number may have. */ int128 private constant MIN_64x64 = -0x80000000000000000000000000000000; /* * Maximum value signed 64.64-bit fixed point number may have. */ int128 private constant MAX_64x64 = 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF; /** * Convert signed 256-bit integer number into signed 64.64-bit fixed point * number. Revert on overflow. * * @param x signed 256-bit integer number * @return signed 64.64-bit fixed point number */ function fromInt (int256 x) internal pure returns (int128) { unchecked { require (x >= -0x8000000000000000 && x <= 0x7FFFFFFFFFFFFFFF); return int128 (x << 64); } } /** * Convert signed 64.64 fixed point number into signed 64-bit integer number * rounding down. * * @param x signed 64.64-bit fixed point number * @return signed 64-bit integer number */ function toInt (int128 x) internal pure returns (int64) { unchecked { return int64 (x >> 64); } } /** * Convert unsigned 256-bit integer number into signed 64.64-bit fixed point * number. Revert on overflow. * * @param x unsigned 256-bit integer number * @return signed 64.64-bit fixed point number */ function fromUInt (uint256 x) internal pure returns (int128) { unchecked { require (x <= 0x7FFFFFFFFFFFFFFF); return int128 (int256 (x << 64)); } } /** * Convert signed 64.64 fixed point number into unsigned 64-bit integer * number rounding down. Revert on underflow. * * @param x signed 64.64-bit fixed point number * @return unsigned 64-bit integer number */ function toUInt (int128 x) internal pure returns (uint64) { unchecked { require (x >= 0); return uint64 (uint128 (x >> 64)); } } /** * Convert signed 128.128 fixed point number into signed 64.64-bit fixed point * number rounding down. Revert on overflow. * * @param x signed 128.128-bin fixed point number * @return signed 64.64-bit fixed point number */ function from128x128 (int256 x) internal pure returns (int128) { unchecked { int256 result = x >> 64; require (result >= MIN_64x64 && result <= MAX_64x64); return int128 (result); } } /** * Convert signed 64.64 fixed point number into signed 128.128 fixed point * number. * * @param x signed 64.64-bit fixed point number * @return signed 128.128 fixed point number */ function to128x128 (int128 x) internal pure returns (int256) { unchecked { return int256 (x) << 64; } } /** * Calculate x + y. Revert on overflow. * * @param x signed 64.64-bit fixed point number * @param y signed 64.64-bit fixed point number * @return signed 64.64-bit fixed point number */ function add (int128 x, int128 y) internal pure returns (int128) { unchecked { int256 result = int256(x) + y; require (result >= MIN_64x64 && result <= MAX_64x64); return int128 (result); } } /** * Calculate x - y. Revert on overflow. * * @param x signed 64.64-bit fixed point number * @param y signed 64.64-bit fixed point number * @return signed 64.64-bit fixed point number */ function sub (int128 x, int128 y) internal pure returns (int128) { unchecked { int256 result = int256(x) - y; require (result >= MIN_64x64 && result <= MAX_64x64); return int128 (result); } } /** * Calculate x * y rounding down. Revert on overflow. * * @param x signed 64.64-bit fixed point number * @param y signed 64.64-bit fixed point number * @return signed 64.64-bit fixed point number */ function mul (int128 x, int128 y) internal pure returns (int128) { unchecked { int256 result = int256(x) * y >> 64; require (result >= MIN_64x64 && result <= MAX_64x64); return int128 (result); } } /** * Calculate x * y rounding towards zero, where x is signed 64.64 fixed point * number and y is signed 256-bit integer number. Revert on overflow. * * @param x signed 64.64 fixed point number * @param y signed 256-bit integer number * @return signed 256-bit integer number */ function muli (int128 x, int256 y) internal pure returns (int256) { unchecked { if (x == MIN_64x64) { require (y >= -0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF && y <= 0x1000000000000000000000000000000000000000000000000); return -y << 63; } else { bool negativeResult = false; if (x < 0) { x = -x; negativeResult = true; } if (y < 0) { y = -y; // We rely on overflow behavior here negativeResult = !negativeResult; } uint256 absoluteResult = mulu (x, uint256 (y)); if (negativeResult) { require (absoluteResult <= 0x8000000000000000000000000000000000000000000000000000000000000000); return -int256 (absoluteResult); // We rely on overflow behavior here } else { require (absoluteResult <= 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF); return int256 (absoluteResult); } } } } /** * Calculate x * y rounding down, where x is signed 64.64 fixed point number * and y is unsigned 256-bit integer number. Revert on overflow. * * @param x signed 64.64 fixed point number * @param y unsigned 256-bit integer number * @return unsigned 256-bit integer number */ function mulu (int128 x, uint256 y) internal pure returns (uint256) { unchecked { if (y == 0) return 0; require (x >= 0); uint256 lo = (uint256 (int256 (x)) * (y & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF)) >> 64; uint256 hi = uint256 (int256 (x)) * (y >> 128); require (hi <= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF); hi <<= 64; require (hi <= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF - lo); return hi + lo; } } /** * Calculate x / y rounding towards zero. Revert on overflow or when y is * zero. * * @param x signed 64.64-bit fixed point number * @param y signed 64.64-bit fixed point number * @return signed 64.64-bit fixed point number */ function div (int128 x, int128 y) internal pure returns (int128) { unchecked { require (y != 0); int256 result = (int256 (x) << 64) / y; require (result >= MIN_64x64 && result <= MAX_64x64); return int128 (result); } } /** * Calculate x / y rounding towards zero, where x and y are signed 256-bit * integer numbers. Revert on overflow or when y is zero. * * @param x signed 256-bit integer number * @param y signed 256-bit integer number * @return signed 64.64-bit fixed point number */ function divi (int256 x, int256 y) internal pure returns (int128) { unchecked { require (y != 0); bool negativeResult = false; if (x < 0) { x = -x; // We rely on overflow behavior here negativeResult = true; } if (y < 0) { y = -y; // We rely on overflow behavior here negativeResult = !negativeResult; } uint128 absoluteResult = divuu (uint256 (x), uint256 (y)); if (negativeResult) { require (absoluteResult <= 0x80000000000000000000000000000000); return -int128 (absoluteResult); // We rely on overflow behavior here } else { require (absoluteResult <= 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF); return int128 (absoluteResult); // We rely on overflow behavior here } } } /** * Calculate x / y rounding towards zero, where x and y are unsigned 256-bit * integer numbers. Revert on overflow or when y is zero. * * @param x unsigned 256-bit integer number * @param y unsigned 256-bit integer number * @return signed 64.64-bit fixed point number */ function divu (uint256 x, uint256 y) internal pure returns (int128) { unchecked { require (y != 0); uint128 result = divuu (x, y); require (result <= uint128 (MAX_64x64)); return int128 (result); } } /** * Calculate -x. Revert on overflow. * * @param x signed 64.64-bit fixed point number * @return signed 64.64-bit fixed point number */ function neg (int128 x) internal pure returns (int128) { unchecked { require (x != MIN_64x64); return -x; } } /** * Calculate |x|. Revert on overflow. * * @param x signed 64.64-bit fixed point number * @return signed 64.64-bit fixed point number */ function abs (int128 x) internal pure returns (int128) { unchecked { require (x != MIN_64x64); return x < 0 ? -x : x; } } /** * Calculate 1 / x rounding towards zero. Revert on overflow or when x is * zero. * * @param x signed 64.64-bit fixed point number * @return signed 64.64-bit fixed point number */ function inv (int128 x) internal pure returns (int128) { unchecked { require (x != 0); int256 result = int256 (0x100000000000000000000000000000000) / x; require (result >= MIN_64x64 && result <= MAX_64x64); return int128 (result); } } /** * Calculate arithmetics average of x and y, i.e. (x + y) / 2 rounding down. * * @param x signed 64.64-bit fixed point number * @param y signed 64.64-bit fixed point number * @return signed 64.64-bit fixed point number */ function avg (int128 x, int128 y) internal pure returns (int128) { unchecked { return int128 ((int256 (x) + int256 (y)) >> 1); } } /** * Calculate geometric average of x and y, i.e. sqrt (x * y) rounding down. * Revert on overflow or in case x * y is negative. * * @param x signed 64.64-bit fixed point number * @param y signed 64.64-bit fixed point number * @return signed 64.64-bit fixed point number */ function gavg (int128 x, int128 y) internal pure returns (int128) { unchecked { int256 m = int256 (x) * int256 (y); require (m >= 0); require (m < 0x4000000000000000000000000000000000000000000000000000000000000000); return int128 (sqrtu (uint256 (m))); } } /** * Calculate x^y assuming 0^0 is 1, where x is signed 64.64 fixed point number * and y is unsigned 256-bit integer number. Revert on overflow. * * @param x signed 64.64-bit fixed point number * @param y uint256 value * @return signed 64.64-bit fixed point number */ function pow (int128 x, uint256 y) internal pure returns (int128) { unchecked { bool negative = x < 0 && y & 1 == 1; uint256 absX = uint128 (x < 0 ? -x : x); uint256 absResult; absResult = 0x100000000000000000000000000000000; if (absX <= 0x10000000000000000) { absX <<= 63; while (y != 0) { if (y & 0x1 != 0) { absResult = absResult * absX >> 127; } absX = absX * absX >> 127; if (y & 0x2 != 0) { absResult = absResult * absX >> 127; } absX = absX * absX >> 127; if (y & 0x4 != 0) { absResult = absResult * absX >> 127; } absX = absX * absX >> 127; if (y & 0x8 != 0) { absResult = absResult * absX >> 127; } absX = absX * absX >> 127; y >>= 4; } absResult >>= 64; } else { uint256 absXShift = 63; if (absX < 0x1000000000000000000000000) { absX <<= 32; absXShift -= 32; } if (absX < 0x10000000000000000000000000000) { absX <<= 16; absXShift -= 16; } if (absX < 0x1000000000000000000000000000000) { absX <<= 8; absXShift -= 8; } if (absX < 0x10000000000000000000000000000000) { absX <<= 4; absXShift -= 4; } if (absX < 0x40000000000000000000000000000000) { absX <<= 2; absXShift -= 2; } if (absX < 0x80000000000000000000000000000000) { absX <<= 1; absXShift -= 1; } uint256 resultShift = 0; while (y != 0) { require (absXShift < 64); if (y & 0x1 != 0) { absResult = absResult * absX >> 127; resultShift += absXShift; if (absResult > 0x100000000000000000000000000000000) { absResult >>= 1; resultShift += 1; } } absX = absX * absX >> 127; absXShift <<= 1; if (absX >= 0x100000000000000000000000000000000) { absX >>= 1; absXShift += 1; } y >>= 1; } require (resultShift < 64); absResult >>= 64 - resultShift; } int256 result = negative ? -int256 (absResult) : int256 (absResult); require (result >= MIN_64x64 && result <= MAX_64x64); return int128 (result); } } /** * Calculate sqrt (x) rounding down. Revert if x < 0. * * @param x signed 64.64-bit fixed point number * @return signed 64.64-bit fixed point number */ function sqrt (int128 x) internal pure returns (int128) { unchecked { require (x >= 0); return int128 (sqrtu (uint256 (int256 (x)) << 64)); } } /** * Calculate binary logarithm of x. Revert if x <= 0. * * @param x signed 64.64-bit fixed point number * @return signed 64.64-bit fixed point number */ function log_2 (int128 x) internal pure returns (int128) { unchecked { require (x > 0); int256 msb = 0; int256 xc = x; if (xc >= 0x10000000000000000) { xc >>= 64; msb += 64; } if (xc >= 0x100000000) { xc >>= 32; msb += 32; } if (xc >= 0x10000) { xc >>= 16; msb += 16; } if (xc >= 0x100) { xc >>= 8; msb += 8; } if (xc >= 0x10) { xc >>= 4; msb += 4; } if (xc >= 0x4) { xc >>= 2; msb += 2; } if (xc >= 0x2) msb += 1; // No need to shift xc anymore int256 result = msb - 64 << 64; uint256 ux = uint256 (int256 (x)) << uint256 (127 - msb); for (int256 bit = 0x8000000000000000; bit > 0; bit >>= 1) { ux *= ux; uint256 b = ux >> 255; ux >>= 127 + b; result += bit * int256 (b); } return int128 (result); } } /** * Calculate natural logarithm of x. Revert if x <= 0. * * @param x signed 64.64-bit fixed point number * @return signed 64.64-bit fixed point number */ function ln (int128 x) internal pure returns (int128) { unchecked { require (x > 0); return int128 (int256 ( uint256 (int256 (log_2 (x))) * 0xB17217F7D1CF79ABC9E3B39803F2F6AF >> 128)); } } /** * Calculate binary exponent of x. Revert on overflow. * * @param x signed 64.64-bit fixed point number * @return signed 64.64-bit fixed point number */ function exp_2 (int128 x) internal pure returns (int128) { unchecked { require (x < 0x400000000000000000); // Overflow if (x < -0x400000000000000000) return 0; // Underflow uint256 result = 0x80000000000000000000000000000000; if (x & 0x8000000000000000 > 0) result = result * 0x16A09E667F3BCC908B2FB1366EA957D3E >> 128; if (x & 0x4000000000000000 > 0) result = result * 0x1306FE0A31B7152DE8D5A46305C85EDEC >> 128; if (x & 0x2000000000000000 > 0) result = result * 0x1172B83C7D517ADCDF7C8C50EB14A791F >> 128; if (x & 0x1000000000000000 > 0) result = result * 0x10B5586CF9890F6298B92B71842A98363 >> 128; if (x & 0x800000000000000 > 0) result = result * 0x1059B0D31585743AE7C548EB68CA417FD >> 128; if (x & 0x400000000000000 > 0) result = result * 0x102C9A3E778060EE6F7CACA4F7A29BDE8 >> 128; if (x & 0x200000000000000 > 0) result = result * 0x10163DA9FB33356D84A66AE336DCDFA3F >> 128; if (x & 0x100000000000000 > 0) result = result * 0x100B1AFA5ABCBED6129AB13EC11DC9543 >> 128; if (x & 0x80000000000000 > 0) result = result * 0x10058C86DA1C09EA1FF19D294CF2F679B >> 128; if (x & 0x40000000000000 > 0) result = result * 0x1002C605E2E8CEC506D21BFC89A23A00F >> 128; if (x & 0x20000000000000 > 0) result = result * 0x100162F3904051FA128BCA9C55C31E5DF >> 128; if (x & 0x10000000000000 > 0) result = result * 0x1000B175EFFDC76BA38E31671CA939725 >> 128; if (x & 0x8000000000000 > 0) result = result * 0x100058BA01FB9F96D6CACD4B180917C3D >> 128; if (x & 0x4000000000000 > 0) result = result * 0x10002C5CC37DA9491D0985C348C68E7B3 >> 128; if (x & 0x2000000000000 > 0) result = result * 0x1000162E525EE054754457D5995292026 >> 128; if (x & 0x1000000000000 > 0) result = result * 0x10000B17255775C040618BF4A4ADE83FC >> 128; if (x & 0x800000000000 > 0) result = result * 0x1000058B91B5BC9AE2EED81E9B7D4CFAB >> 128; if (x & 0x400000000000 > 0) result = result * 0x100002C5C89D5EC6CA4D7C8ACC017B7C9 >> 128; if (x & 0x200000000000 > 0) result = result * 0x10000162E43F4F831060E02D839A9D16D >> 128; if (x & 0x100000000000 > 0) result = result * 0x100000B1721BCFC99D9F890EA06911763 >> 128; if (x & 0x80000000000 > 0) result = result * 0x10000058B90CF1E6D97F9CA14DBCC1628 >> 128; if (x & 0x40000000000 > 0) result = result * 0x1000002C5C863B73F016468F6BAC5CA2B >> 128; if (x & 0x20000000000 > 0) result = result * 0x100000162E430E5A18F6119E3C02282A5 >> 128; if (x & 0x10000000000 > 0) result = result * 0x1000000B1721835514B86E6D96EFD1BFE >> 128; if (x & 0x8000000000 > 0) result = result * 0x100000058B90C0B48C6BE5DF846C5B2EF >> 128; if (x & 0x4000000000 > 0) result = result * 0x10000002C5C8601CC6B9E94213C72737A >> 128; if (x & 0x2000000000 > 0) result = result * 0x1000000162E42FFF037DF38AA2B219F06 >> 128; if (x & 0x1000000000 > 0) result = result * 0x10000000B17217FBA9C739AA5819F44F9 >> 128; if (x & 0x800000000 > 0) result = result * 0x1000000058B90BFCDEE5ACD3C1CEDC823 >> 128; if (x & 0x400000000 > 0) result = result * 0x100000002C5C85FE31F35A6A30DA1BE50 >> 128; if (x & 0x200000000 > 0) result = result * 0x10000000162E42FF0999CE3541B9FFFCF >> 128; if (x & 0x100000000 > 0) result = result * 0x100000000B17217F80F4EF5AADDA45554 >> 128; if (x & 0x80000000 > 0) result = result * 0x10000000058B90BFBF8479BD5A81B51AD >> 128; if (x & 0x40000000 > 0) result = result * 0x1000000002C5C85FDF84BD62AE30A74CC >> 128; if (x & 0x20000000 > 0) result = result * 0x100000000162E42FEFB2FED257559BDAA >> 128; if (x & 0x10000000 > 0) result = result * 0x1000000000B17217F7D5A7716BBA4A9AE >> 128; if (x & 0x8000000 > 0) result = result * 0x100000000058B90BFBE9DDBAC5E109CCE >> 128; if (x & 0x4000000 > 0) result = result * 0x10000000002C5C85FDF4B15DE6F17EB0D >> 128; if (x & 0x2000000 > 0) result = result * 0x1000000000162E42FEFA494F1478FDE05 >> 128; if (x & 0x1000000 > 0) result = result * 0x10000000000B17217F7D20CF927C8E94C >> 128; if (x & 0x800000 > 0) result = result * 0x1000000000058B90BFBE8F71CB4E4B33D >> 128; if (x & 0x400000 > 0) result = result * 0x100000000002C5C85FDF477B662B26945 >> 128; if (x & 0x200000 > 0) result = result * 0x10000000000162E42FEFA3AE53369388C >> 128; if (x & 0x100000 > 0) result = result * 0x100000000000B17217F7D1D351A389D40 >> 128; if (x & 0x80000 > 0) result = result * 0x10000000000058B90BFBE8E8B2D3D4EDE >> 128; if (x & 0x40000 > 0) result = result * 0x1000000000002C5C85FDF4741BEA6E77E >> 128; if (x & 0x20000 > 0) result = result * 0x100000000000162E42FEFA39FE95583C2 >> 128; if (x & 0x10000 > 0) result = result * 0x1000000000000B17217F7D1CFB72B45E1 >> 128; if (x & 0x8000 > 0) result = result * 0x100000000000058B90BFBE8E7CC35C3F0 >> 128; if (x & 0x4000 > 0) result = result * 0x10000000000002C5C85FDF473E242EA38 >> 128; if (x & 0x2000 > 0) result = result * 0x1000000000000162E42FEFA39F02B772C >> 128; if (x & 0x1000 > 0) result = result * 0x10000000000000B17217F7D1CF7D83C1A >> 128; if (x & 0x800 > 0) result = result * 0x1000000000000058B90BFBE8E7BDCBE2E >> 128; if (x & 0x400 > 0) result = result * 0x100000000000002C5C85FDF473DEA871F >> 128; if (x & 0x200 > 0) result = result * 0x10000000000000162E42FEFA39EF44D91 >> 128; if (x & 0x100 > 0) result = result * 0x100000000000000B17217F7D1CF79E949 >> 128; if (x & 0x80 > 0) result = result * 0x10000000000000058B90BFBE8E7BCE544 >> 128; if (x & 0x40 > 0) result = result * 0x1000000000000002C5C85FDF473DE6ECA >> 128; if (x & 0x20 > 0) result = result * 0x100000000000000162E42FEFA39EF366F >> 128; if (x & 0x10 > 0) result = result * 0x1000000000000000B17217F7D1CF79AFA >> 128; if (x & 0x8 > 0) result = result * 0x100000000000000058B90BFBE8E7BCD6D >> 128; if (x & 0x4 > 0) result = result * 0x10000000000000002C5C85FDF473DE6B2 >> 128; if (x & 0x2 > 0) result = result * 0x1000000000000000162E42FEFA39EF358 >> 128; if (x & 0x1 > 0) result = result * 0x10000000000000000B17217F7D1CF79AB >> 128; result >>= uint256 (int256 (63 - (x >> 64))); require (result <= uint256 (int256 (MAX_64x64))); return int128 (int256 (result)); } } /** * Calculate natural exponent of x. Revert on overflow. * * @param x signed 64.64-bit fixed point number * @return signed 64.64-bit fixed point number */ function exp (int128 x) internal pure returns (int128) { unchecked { require (x < 0x400000000000000000); // Overflow if (x < -0x400000000000000000) return 0; // Underflow return exp_2 ( int128 (int256 (x) * 0x171547652B82FE1777D0FFDA0D23A7D12 >> 128)); } } /** * Calculate x / y rounding towards zero, where x and y are unsigned 256-bit * integer numbers. Revert on overflow or when y is zero. * * @param x unsigned 256-bit integer number * @param y unsigned 256-bit integer number * @return unsigned 64.64-bit fixed point number */ function divuu (uint256 x, uint256 y) private pure returns (uint128) { unchecked { require (y != 0); uint256 result; if (x <= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF) result = (x << 64) / y; else { uint256 msb = 192; uint256 xc = x >> 192; if (xc >= 0x100000000) { xc >>= 32; msb += 32; } if (xc >= 0x10000) { xc >>= 16; msb += 16; } if (xc >= 0x100) { xc >>= 8; msb += 8; } if (xc >= 0x10) { xc >>= 4; msb += 4; } if (xc >= 0x4) { xc >>= 2; msb += 2; } if (xc >= 0x2) msb += 1; // No need to shift xc anymore result = (x << 255 - msb) / ((y - 1 >> msb - 191) + 1); require (result <= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF); uint256 hi = result * (y >> 128); uint256 lo = result * (y & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF); uint256 xh = x >> 192; uint256 xl = x << 64; if (xl < lo) xh -= 1; xl -= lo; // We rely on overflow behavior here lo = hi << 128; if (xl < lo) xh -= 1; xl -= lo; // We rely on overflow behavior here assert (xh == hi >> 128); result += xl / y; } require (result <= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF); return uint128 (result); } } /** * Calculate sqrt (x) rounding down, where x is unsigned 256-bit integer * number. * * @param x unsigned 256-bit integer number * @return unsigned 128-bit integer number */ function sqrtu (uint256 x) private pure returns (uint128) { unchecked { if (x == 0) return 0; else { 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 uint128 (r < r1 ? r : r1); } } } } pragma solidity ^0.8.4; // SPDX-License-Identifier: GPL-3.0-or-later import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/extensions/ERC20Burnable.sol"; import "@openzeppelin/contracts/security/Pausable.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/access/AccessControl.sol"; /** * Created and owned by the staking contract. * * It mints and burns OGTemple as users stake/unstake */ contract OGTemple is ERC20, ERC20Burnable, Ownable { constructor() ERC20("OGTemple", "OG_TEMPLE") {} function mint(address to, uint256 amount) external onlyOwner { _mint(to, amount); } }
Disable's by resetting the exit queue owner to the owner of this contract/
function disableAcceleratedExitQueue() external onlyOwner { exitQueue.transferOwnership(owner()); }
6,165,797
./full_match/137/0x3E1AF9Ea975cb30aA622E478D96aDB642c2cdf8E/sources/contracts/vault/MultiVault.sol
in case a token is duplicated, only one transfer is required, hence the check
function unlock(bytes memory data) external onlyKeyHolder onlyUnlockable { require(!isUnlocked, "MultiVault:unlock:ALREADY_OPEN: Vault has already been unlocked"); for (uint256 i = 0; i < fungibleTokenDeposits.length; i++) { IERC20 token = IERC20(fungibleTokenDeposits[i].tokenAddress); uint256 balance = token.balanceOf(address(this)); if (balance > 0) { token.safeTransfer(msg.sender, balance); } } for (uint256 i = 0; i < nonFungibleTokenDeposits.length; i++) { IERC721(nonFungibleTokenDeposits[i].tokenAddress).safeTransferFrom( address(this), msg.sender, nonFungibleTokenDeposits[i].tokenId ); } for (uint256 i = 0; i < multiTokenDeposits.length; i++) { IERC1155(multiTokenDeposits[i].tokenAddress).safeTransferFrom( address(this), msg.sender, multiTokenDeposits[i].tokenId, multiTokenDeposits[i].amount, data ); } isUnlocked = true; vaultFactoryContract.notifyUnlock(true); }
4,718,237
pragma solidity ^0.8.4; //SPDX-License-Identifier: MIT import {ERC721, ERC721TokenReceiver} from "@rari-capital/solmate/src/tokens/ERC721.sol"; import {ERC1155, ERC1155TokenReceiver} from "@rari-capital/solmate/src/tokens/ERC1155.sol"; import {SafeTransferLib, ERC20} from "@rari-capital/solmate/src/utils/SafeTransferLib.sol"; import {Strings} from "@openzeppelin/contracts/utils/Strings.sol"; import {IERC2981, IERC165} from "@openzeppelin/contracts/interfaces/IERC2981.sol"; import {Math} from "@openzeppelin/contracts/utils/math/Math.sol"; import {Base64} from 'base64-sol/base64.sol'; import {CloneList} from "./CloneList.sol"; import {TimeCurve} from "./TimeCurve.sol"; /** * @title NFT derivative exchange inspired by the SALSA concept. * @author calvbore * @notice A user may self assess the price of an NFT and purchase a token representing * the right to ownership when it is sold via this contract. Anybody may buy the * token for a higher price and force a transfer from the previous owner to the new buyer. */ contract DittoMachine is ERC721, ERC721TokenReceiver, ERC1155TokenReceiver, CloneList { /** * @notice Insufficient bid for purchasing a clone. * @dev thrown when the number of erc20 tokens sent is lower than * the number of tokens required to purchase a clone. */ error AmountInvalid(); error AmountInvalidMin(); error InvalidFloorId(); error CloneNotFound(); error FromInvalid(); error IndexInvalid(); error NFTNotReceived(); error NotAuthorized(); ////////////// CONSTANT VARIABLES ////////////// bytes4 private constant _INTERFACE_ID_ERC2981 = 0x2a55205a; bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef"; uint256 public constant FLOOR_ID = uint256(0xfddc260aecba8a66725ee58da4ea3cbfcf4ab6c6ad656c48345a575ca18c45c9); // ensure that CloneShape can always be casted to int128. // change the type to ensure this? uint256 public constant BASE_TERM = 2**18; uint256 public constant MIN_FEE = 32; uint256 public constant DNOM = 2**16 - 1; uint256 public constant MIN_AMOUNT_FOR_NEW_CLONE = BASE_TERM + (BASE_TERM * MIN_FEE / DNOM); ////////////// STATE VARIABLES ////////////// // variables essential to calculating auction/price information for each cloneId struct CloneShape { uint256 tokenId; uint256 worth; address ERC721Contract; address ERC20Contract; uint8 heat; bool floor; uint256 term; } // tracks balance of subsidy for a specific cloneId mapping(uint256 => uint256) public cloneIdToSubsidy; // protoId cumulative price for TWAP mapping(uint256 => uint256) public protoIdToCumulativePrice; // lat timestamp recorded for protoId TWAP mapping(uint256 => uint256) public protoIdToTimestampLast; // hash protoId with the index placement to get cloneId mapping(uint256 => CloneShape) public cloneIdToShape; constructor() ERC721("Ditto", "DTO") { } /////////////////////////////////////////// ////////////// URI FUNCTIONS ////////////// /////////////////////////////////////////// function tokenURI(uint256 id) public view override returns (string memory) { CloneShape memory cloneShape = cloneIdToShape[id]; if (!cloneShape.floor) { // if clone is not a floor return underlying token uri try ERC721(cloneShape.ERC721Contract).tokenURI(cloneShape.tokenId) returns (string memory uri) { return uri; } catch { return ERC1155(cloneShape.ERC721Contract).uri(cloneShape.tokenId); } } else { string memory _name = string(abi.encodePacked('Ditto Floor #', Strings.toString(id))); string memory description = string(abi.encodePacked( 'This Ditto represents the floor price of tokens at ', Strings.toHexString(uint160(cloneIdToShape[id].ERC721Contract), 20) )); string memory image = Base64.encode(bytes(generateSVGofTokenById(id))); return string(abi.encodePacked( 'data:application/json;base64,', Base64.encode( bytes( abi.encodePacked( '{"name":"', _name, '", "description":"', description, '", "attributes": [{"trait_type": "Underlying NFT", "value": "', Strings.toHexString(uint160(cloneIdToShape[id].ERC721Contract), 20), '"},{"trait_type": "tokenId", "value": ', Strings.toString(cloneShape.tokenId), '}], "owner":"', Strings.toHexString(uint160(ownerOf[id]), 20), '", "image": "', 'data:image/svg+xml;base64,', image, '"}' ) ) ) )); } } function generateSVGofTokenById(uint256 _tokenId) internal pure returns (string memory) { string memory svg = string(abi.encodePacked( '<svg viewBox="0 0 100 100" xmlns="http://www.w3.org/2000/svg">', renderTokenById(_tokenId), '</svg>' )); return svg; } // Visibility is `public` to enable it being called by other contracts for composition. function renderTokenById(uint256 _tokenId) public pure returns (string memory) { string memory hexColor = toHexString(uint24(_tokenId), 3); return string(abi.encodePacked( '<rect width="100" height="100" rx="15" style="fill:#', hexColor, '" />', '<g id="face" transform="matrix(0.531033,0,0,0.531033,-279.283,-398.06)">', '<g transform="matrix(0.673529,0,0,0.673529,201.831,282.644)">', '<circle cx="568.403" cy="815.132" r="3.15"/>', '</g>', '<g transform="matrix(0.673529,0,0,0.673529,272.214,282.644)">', '<circle cx="568.403" cy="815.132" r="3.15"/>', '</g>', '<g transform="matrix(1,0,0,1,0.0641825,0)">', '<path d="M572.927,854.4C604.319,859.15 635.71,859.166 667.102,854.4" style="fill:none;stroke:black;stroke-width:0.98px;"/>', '</g>', '</g>' )); } // same as inspired from @openzeppelin/contracts/utils/Strings.sol except that it doesn't add "0x" as prefix. function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length); for (uint256 i = 2 * length; i > 0; --i) { buffer[i - 1] = _HEX_SYMBOLS[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } ///////////////////////////////////////////////// //////////////// CLONE FUNCTIONS //////////////// ///////////////////////////////////////////////// /** * @notice open or buy out a future on a particular NFT or floor perp. * @notice fees will be taken from purchases and set aside as a subsidy to encourage sellers. * @param _ERC721Contract address of selected NFT smart contract. * @param _tokenId selected NFT token id. * @param _ERC20Contract address of the ERC20 contract used for purchase. * @param _amount address of ERC20 tokens used for purchase. * @param floor selector determining if the purchase is for a floor perp. * @dev creates an ERC721 representing the specified future or floor perp, reffered to as clone. * @dev a clone id is calculated by hashing ERC721Contract, _tokenId, _ERC20Contract, and floor params. * @dev if floor == true, FLOOR_ID will replace _tokenId in cloneId calculation. */ function duplicate( address _ERC721Contract, uint256 _tokenId, address _ERC20Contract, uint256 _amount, bool floor, uint256 index // index at which to mint the clone ) external returns ( uint256, // cloneId uint256 // protoId ) { // ensure enough funds to do some math on if (_amount < MIN_AMOUNT_FOR_NEW_CLONE) { revert AmountInvalidMin(); } if (floor && _tokenId != FLOOR_ID) { revert InvalidFloorId(); } // calculate protoId by hashing identifiying information, precursor to cloneId uint256 protoId = uint256(keccak256(abi.encodePacked( _ERC721Contract, _tokenId, _ERC20Contract, floor ))); // hash protoId and index to get cloneId uint256 cloneId = uint256(keccak256(abi.encodePacked(protoId, index))); _updatePrice(protoId); if (ownerOf[cloneId] == address(0)) { // check that index references have been set if (!validIndex(protoId, index)) { // if references have not been set by a previous clone this clone cannot be minted revert IndexInvalid(); } uint256 floorId = uint256(keccak256(abi.encodePacked( _ERC721Contract, FLOOR_ID, _ERC20Contract, true ))); floorId = uint256(keccak256(abi.encodePacked(floorId, index))); uint256 subsidy = _amount * MIN_FEE / DNOM; // with current constants subsidy <= _amount uint256 value = _amount - subsidy; if (cloneId != floorId && ownerOf[floorId] != address(0)) { // check price of floor clone to get price floor uint256 minAmount = cloneIdToShape[floorId].worth; if (value < minAmount) { revert AmountInvalid(); } } if (index != protoIdToIndexHead[protoId]) { // check cloneId at prior index // prev <- index uint256 elderId = uint256(keccak256(abi.encodePacked(protoId, protoIdToIndexToPrior[protoId][index]))); if (value > cloneIdToShape[elderId].worth) { revert AmountInvalid(); // check value is less than clone closer to the index head } } _mint(msg.sender, cloneId); cloneIdToShape[cloneId] = CloneShape( _tokenId, value, _ERC721Contract, _ERC20Contract, 1, floor, block.timestamp + BASE_TERM ); pushListTail(protoId, index); cloneIdToSubsidy[cloneId] += subsidy; SafeTransferLib.safeTransferFrom( // EXTERNAL CALL ERC20(_ERC20Contract), msg.sender, address(this), _amount ); } else { CloneShape memory cloneShape = cloneIdToShape[cloneId]; uint256 heat = cloneShape.heat; uint256 minAmount = _getMinAmount(cloneShape); // calculate subsidy and worth values uint256 subsidy = minAmount * (MIN_FEE * (1 + heat)) / DNOM; // scoping to prevent "stack too deep" errors { uint256 value = _amount - subsidy; // will be applied to cloneShape.worth if (index != protoIdToIndexHead[protoId]) { // check cloneId at prior index // prev <- index uint256 elderId = uint256(keccak256(abi.encodePacked(protoId, protoIdToIndexToPrior[protoId][index]))); if (value > cloneIdToShape[elderId].worth) { revert AmountInvalid(); } } if (value < minAmount) { revert AmountInvalid(); } // reduce heat relative to amount of time elapsed by auction if (cloneShape.term > block.timestamp) { uint256 termLength = BASE_TERM + TimeCurve.calc(heat); uint256 elapsed = block.timestamp - (cloneShape.term - termLength); // current time - time when the current term started // add 1 to current heat so heat is not stuck at low value with anything but extreme demand for a clone uint256 cool = (heat+1) * elapsed / termLength; heat = (cool > heat) ? 1 : Math.min(heat - cool + 1, type(uint8).max); } else { heat = 1; } // calculate new clone term values cloneIdToShape[cloneId].worth = value; cloneIdToShape[cloneId].heat = uint8(heat); // does not inherit heat of floor id cloneIdToShape[cloneId].term = block.timestamp + BASE_TERM + TimeCurve.calc(heat); } // paying required funds to this contract SafeTransferLib.safeTransferFrom( // EXTERNAL CALL ERC20(_ERC20Contract), msg.sender, address(this), _amount ); // buying out the previous clone owner address curOwner = ownerOf[cloneId]; uint256 subsidyDiv2 = subsidy >> 1; // half of fee goes into subsidy pool, half to previous clone owner cloneIdToSubsidy[cloneId] += subsidyDiv2; SafeTransferLib.safeTransfer( // EXTERNAL CALL ERC20(_ERC20Contract), curOwner, (cloneShape.worth + subsidyDiv2 + (subsidy & 1)) // previous clone value + half of subsidy sent to prior clone owner ); // force transfer from current owner to new highest bidder forceTransferFrom(curOwner, msg.sender, cloneId); // EXTERNAL CALL } return (cloneId, protoId); } /** * @notice unwind a position in a clone. * @param protoId specifies the clone to be burned. * @dev will refund funds held in a position, subsidy will remain for sellers in the future. */ function dissolve(uint256 protoId, uint256 index) external { uint256 cloneId = uint256(keccak256(abi.encodePacked(protoId, index))); if (!(msg.sender == ownerOf[cloneId] || msg.sender == getApproved[cloneId] || isApprovedForAll[ownerOf[cloneId]][msg.sender])) { revert NotAuthorized(); } // move its subsidy to the next clone in the linked list even if it's not minted yet. uint256 nextCloneId = uint256(keccak256(abi.encodePacked(protoId, protoIdToIndexToAfter[protoId][index]))); // invariant: cloneId != nextCloneId cloneIdToSubsidy[nextCloneId] += cloneIdToSubsidy[cloneId]; delete cloneIdToSubsidy[cloneId]; CloneShape memory cloneShape = cloneIdToShape[cloneId]; _updatePrice(protoId); popListIndex(protoId, index); address owner = ownerOf[cloneId]; delete cloneIdToShape[cloneId]; _burn(cloneId); SafeTransferLib.safeTransfer( // EXTERNAL CALL ERC20(cloneShape.ERC20Contract), owner, cloneShape.worth ); } function getMinAmountForCloneTransfer(uint256 cloneId) external view returns (uint256) { if(ownerOf[cloneId] == address(0)) { return MIN_AMOUNT_FOR_NEW_CLONE; } CloneShape memory cloneShape = cloneIdToShape[cloneId]; uint256 _minAmount = _getMinAmount(cloneShape); return _minAmount + (_minAmount * MIN_FEE * (1 + cloneShape.heat) / DNOM); } /** * @notice computes the minimum amount required to buy a clone. * @notice it does not take into account the protocol fee or the subsidy. * @param cloneShape clone for which to compute the minimum amount. * @dev only use it for a minted clone. */ function _getMinAmount(CloneShape memory cloneShape) internal view returns (uint256) { uint256 floorId = uint256(keccak256(abi.encodePacked( cloneShape.ERC721Contract, FLOOR_ID, cloneShape.ERC20Contract, true ))); floorId = uint256(keccak256(abi.encodePacked(floorId, protoIdToIndexHead[floorId]))); uint256 floorPrice = cloneIdToShape[floorId].worth; uint256 timeLeft = 0; unchecked { if (cloneShape.term > block.timestamp) { timeLeft = cloneShape.term - block.timestamp; } } uint256 termLength = BASE_TERM + TimeCurve.calc(cloneShape.heat); uint256 clonePrice = cloneShape.worth + (cloneShape.worth * timeLeft / termLength); // return floor price if greater than clone auction price return floorPrice > clonePrice ? floorPrice : clonePrice; } //////////////////////////////////////////////// ////////////// RECEIVER FUNCTIONS ////////////// //////////////////////////////////////////////// function onTokenReceived( address from, address tokenContract, uint256 id, address ERC20Contract, bool floor, bool isERC1155 ) private { uint256 protoId = uint256(keccak256(abi.encodePacked( tokenContract, // ERC721 or ERC1155 Contract address id, ERC20Contract, false ))); uint256 cloneId = uint256(keccak256(abi.encodePacked(protoId, protoIdToIndexHead[protoId]))); uint256 flotoId = uint256(keccak256(abi.encodePacked( // floorId + protoId = flotoId tokenContract, FLOOR_ID, ERC20Contract, true ))); uint256 floorId = uint256(keccak256(abi.encodePacked(flotoId, protoIdToIndexHead[flotoId]))); if ( floor || ownerOf[cloneId] == address(0) || cloneIdToShape[floorId].worth > cloneIdToShape[cloneId].worth ) { // if cloneId is not active, check floor clone cloneId = floorId; protoId = flotoId; } // if no cloneId is active, revert if (ownerOf[cloneId] == address(0)) { revert CloneNotFound(); } _updatePrice(protoId); CloneShape memory cloneShape = cloneIdToShape[cloneId]; uint256 subsidy = cloneIdToSubsidy[cloneId]; address owner = ownerOf[cloneId]; delete cloneIdToShape[cloneId]; delete cloneIdToSubsidy[cloneId]; _burn(cloneId); // token can only be sold to the clone at the index head popListHead(protoId); if (isERC1155) { if (ERC1155(tokenContract).balanceOf(address(this), id) < 1) { revert NFTNotReceived(); } ERC1155(tokenContract).safeTransferFrom(address(this), owner, id, 1, ""); } else { if (ERC721(tokenContract).ownerOf(id) != address(this)) { revert NFTNotReceived(); } ERC721(tokenContract).safeTransferFrom(address(this), owner, id); } if (IERC165(tokenContract).supportsInterface(_INTERFACE_ID_ERC2981)) { (address receiver, uint256 royaltyAmount) = IERC2981(tokenContract).royaltyInfo( cloneShape.tokenId, cloneShape.worth ); if (royaltyAmount > 0) { cloneShape.worth -= royaltyAmount; SafeTransferLib.safeTransfer( ERC20(ERC20Contract), receiver, royaltyAmount ); } } SafeTransferLib.safeTransfer( ERC20(ERC20Contract), from, cloneShape.worth + subsidy ); } /** * @dev will allow NFT sellers to sell by safeTransferFrom-ing directly to this contract. * @param data will contain ERC20 address that the seller wishes to sell for * allows specifying selling for the floor price * @return returns received selector */ function onERC721Received( address, address from, uint256 id, bytes calldata data ) external returns (bytes4) { (address ERC20Contract, bool floor) = abi.decode(data, (address, bool)); onTokenReceived(from, msg.sender /*ERC721 contract address*/, id, ERC20Contract, floor, false); return this.onERC721Received.selector; } function onERC1155Received( address, address from, uint256 id, uint256 amount, bytes calldata data ) external returns (bytes4) { if (amount != 1) { revert AmountInvalid(); } // address ERC1155Contract = msg.sender; (address ERC20Contract, bool floor) = abi.decode(data, (address, bool)); onTokenReceived(from, msg.sender /*ERC1155 contract address*/, id, ERC20Contract, floor, true); return this.onERC1155Received.selector; } function onERC1155BatchReceived( address, address from, uint256[] calldata ids, uint256[] calldata amounts, bytes calldata data ) external returns (bytes4) { for (uint256 i=0; i < amounts.length; i++) { if (amounts[i] != 1) { revert AmountInvalid(); } } // address[] memory ERC20Contracts = new address[](ids.length); // bool[] memory floors = new bool[](ids.length); (address[] memory ERC20Contracts, bool[] memory floors) = abi.decode(data, (address[], bool[])); for (uint256 i=0; i < ids.length; i++) { onTokenReceived(from, msg.sender /*ERC1155 contract address*/, ids[i], ERC20Contracts[i], floors[i], true); } return this.onERC1155BatchReceived.selector; } /////////////////////////////////////////////// ////////////// PRIVATE FUNCTIONS ////////////// /////////////////////////////////////////////// /** * @notice transfer clone without owner/approval checks. * @param from current clone owner. * @param to transfer recipient. * @param id clone id. * @dev if the current clone owner implements ERC721Ejected, we call it. * we will still transfer the clone if that call reverts. * only to be called from `duplicate()` function to transfer to the next bidder. * `to` != address(0) is assumed and is not explicitly check. * `onERC721Received` is not called on the receiver, the bidder is responsible for accounting. */ function forceTransferFrom( address from, address to, uint256 id ) private { // no ownership or approval checks cause we're forcing a change of ownership if (from != ownerOf[id]) { revert FromInvalid(); } unchecked { balanceOf[from]--; balanceOf[to]++; } ownerOf[id] = to; delete getApproved[id]; emit Transfer(from, to, id); // give contracts the option to account for a forced transfer. // if they don't implement the ejector we're stll going to move the token. if (from.code.length != 0) { // not sure if this is exploitable yet? try IERC721TokenEjector(from).onERC721Ejected{gas: 30000}(address(this), to, id, "") {} // EXTERNAL CALL catch {} } } // @dev: this function is not prod ready function _updatePrice(uint256 protoId) internal { uint256 cloneId = uint256(keccak256(abi.encodePacked(protoId, protoIdToIndexHead[protoId]))); uint256 timeElapsed = block.timestamp - protoIdToTimestampLast[protoId]; if (timeElapsed > 0) { unchecked { protoIdToCumulativePrice[protoId] += cloneIdToShape[cloneId].worth * timeElapsed; } } protoIdToTimestampLast[protoId] = block.timestamp; } } /** * @title A funtion to support token ejection * @notice function is called if a contract must do accounting on a forced transfer */ interface IERC721TokenEjector { function onERC721Ejected( address operator, address to, uint256 id, bytes calldata data ) external returns (bytes4); }
same as inspired from @openzeppelin/contracts/utils/Strings.sol except that it doesn't add "0x" as prefix.
function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length); for (uint256 i = 2 * length; i > 0; --i) { buffer[i - 1] = _HEX_SYMBOLS[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); }
1,065,495
/** *Submitted for verification at Etherscan.io on 2021-04-03 */ // SPDX-License-Identifier: BUSL-1.1 // File: @openzeppelin/contracts/utils/EnumerableSet.sol pragma solidity >=0.6.0 <0.8.0; /** * @dev Library for managing * https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive * types. * * Sets have the following properties: * * - Elements are added, removed, and checked for existence in constant time * (O(1)). * - Elements are enumerated in O(n). No guarantees are made on the ordering. * * ``` * contract Example { * // Add the library methods * using EnumerableSet for EnumerableSet.AddressSet; * * // Declare a set state variable * EnumerableSet.AddressSet private mySet; * } * ``` * * As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`) * and `uint256` (`UintSet`) are supported. */ library EnumerableSet { // To implement this library for multiple types with as little code // repetition as possible, we write it in terms of a generic Set type with // bytes32 values. // The Set implementation uses private functions, and user-facing // implementations (such as AddressSet) are just wrappers around the // underlying Set. // This means that we can only create new EnumerableSets for types that fit // in bytes32. struct Set { // Storage of set values bytes32[] _values; // Position of the value in the `values` array, plus 1 because index 0 // means a value is not in the set. mapping (bytes32 => uint256) _indexes; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function _add(Set storage set, bytes32 value) private returns (bool) { if (!_contains(set, value)) { set._values.push(value); // The value is stored at length-1, but we add 1 to all indexes // and use 0 as a sentinel value set._indexes[value] = set._values.length; return true; } else { return false; } } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function _remove(Set storage set, bytes32 value) private returns (bool) { // We read and store the value's index to prevent multiple reads from the same storage slot uint256 valueIndex = set._indexes[value]; if (valueIndex != 0) { // Equivalent to contains(set, value) // To delete an element from the _values array in O(1), we swap the element to delete with the last one in // the array, and then remove the last element (sometimes called as 'swap and pop'). // This modifies the order of the array, as noted in {at}. uint256 toDeleteIndex = valueIndex - 1; uint256 lastIndex = set._values.length - 1; // When the value to delete is the last one, the swap operation is unnecessary. However, since this occurs // so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement. bytes32 lastvalue = set._values[lastIndex]; // Move the last value to the index where the value to delete is set._values[toDeleteIndex] = lastvalue; // Update the index for the moved value set._indexes[lastvalue] = toDeleteIndex + 1; // All indexes are 1-based // Delete the slot where the moved value was stored set._values.pop(); // Delete the index for the deleted slot delete set._indexes[value]; return true; } else { return false; } } /** * @dev Returns true if the value is in the set. O(1). */ function _contains(Set storage set, bytes32 value) private view returns (bool) { return set._indexes[value] != 0; } /** * @dev Returns the number of values on the set. O(1). */ function _length(Set storage set) private view returns (uint256) { return set._values.length; } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function _at(Set storage set, uint256 index) private view returns (bytes32) { require(set._values.length > index, "EnumerableSet: index out of bounds"); return set._values[index]; } // Bytes32Set struct Bytes32Set { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _add(set._inner, value); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _remove(set._inner, value); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) { return _contains(set._inner, value); } /** * @dev Returns the number of values in the set. O(1). */ function length(Bytes32Set storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) { return _at(set._inner, index); } // AddressSet struct AddressSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(AddressSet storage set, address value) internal returns (bool) { return _add(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(AddressSet storage set, address value) internal returns (bool) { return _remove(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(AddressSet storage set, address value) internal view returns (bool) { return _contains(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Returns the number of values in the set. O(1). */ function length(AddressSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(AddressSet storage set, uint256 index) internal view returns (address) { return address(uint160(uint256(_at(set._inner, index)))); } // UintSet struct UintSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(UintSet storage set, uint256 value) internal returns (bool) { return _add(set._inner, bytes32(value)); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(UintSet storage set, uint256 value) internal returns (bool) { return _remove(set._inner, bytes32(value)); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(UintSet storage set, uint256 value) internal view returns (bool) { return _contains(set._inner, bytes32(value)); } /** * @dev Returns the number of values on the set. O(1). */ function length(UintSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(UintSet storage set, uint256 index) internal view returns (uint256) { return uint256(_at(set._inner, index)); } } // File: @openzeppelin/contracts/token/ERC20/IERC20.sol pragma solidity >=0.6.0 <0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // File: contracts/interfaces/IDMMFactory.sol pragma solidity 0.6.12; interface IDMMFactory { function createPool( IERC20 tokenA, IERC20 tokenB, uint32 ampBps ) external returns (address pool); function setFeeConfiguration(address feeTo, uint16 governmentFeeBps) external; function setFeeToSetter(address) external; function getFeeConfiguration() external view returns (address feeTo, uint16 governmentFeeBps); function feeToSetter() external view returns (address); function allPools(uint256) external view returns (address pool); function allPoolsLength() external view returns (uint256); function getUnamplifiedPool(IERC20 token0, IERC20 token1) external view returns (address); function getPools(IERC20 token0, IERC20 token1) external view returns (address[] memory _tokenPools); function isPool( IERC20 token0, IERC20 token1, address pool ) external view returns (bool); } // File: @openzeppelin/contracts/math/SafeMath.sol pragma solidity >=0.6.0 <0.8.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b > a) return (false, 0); return (true, a - b); } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a / b); } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a % b); } /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a, "SafeMath: subtraction overflow"); return a - b; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) return 0; uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers, reverting on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: division by zero"); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: modulo by zero"); return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); return a - b; } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryDiv}. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a % b; } } // File: @openzeppelin/contracts/math/Math.sol pragma solidity >=0.6.0 <0.8.0; /** * @dev Standard math utilities missing in the Solidity language. */ library Math { /** * @dev Returns the largest of two numbers. */ function max(uint256 a, uint256 b) internal pure returns (uint256) { return a >= b ? a : b; } /** * @dev Returns the smallest of two numbers. */ function min(uint256 a, uint256 b) internal pure returns (uint256) { return a < b ? a : b; } /** * @dev Returns the average of two numbers. The result is rounded towards * zero. */ function average(uint256 a, uint256 b) internal pure returns (uint256) { // (a + b) / 2 can overflow, so we distribute return (a / 2) + (b / 2) + ((a % 2 + b % 2) / 2); } } // File: @openzeppelin/contracts/utils/ReentrancyGuard.sol pragma solidity >=0.6.0 <0.8.0; /** * @dev Contract module that helps prevent reentrant calls to a function. * * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier * available, which can be applied to functions to make sure there are no nested * (reentrant) calls to them. * * Note that because there is a single `nonReentrant` guard, functions marked as * `nonReentrant` may not call one another. This can be worked around by making * those functions `private`, and then adding `external` `nonReentrant` entry * points to them. * * TIP: If you would like to learn more about reentrancy and alternative ways * to protect against it, check out our blog post * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul]. */ abstract contract ReentrancyGuard { // Booleans are more expensive than uint256 or any type that takes up a full // word because each write operation emits an extra SLOAD to first read the // slot's contents, replace the bits taken up by the boolean, and then write // back. This is the compiler's defense against contract upgrades and // pointer aliasing, and it cannot be disabled. // The values being non-zero value makes deployment a bit more expensive, // but in exchange the refund on every call to nonReentrant will be lower in // amount. Since refunds are capped to a percentage of the total // transaction's gas, it is best to keep them low in cases like this one, to // increase the likelihood of the full refund coming into effect. uint256 private constant _NOT_ENTERED = 1; uint256 private constant _ENTERED = 2; uint256 private _status; constructor () internal { _status = _NOT_ENTERED; } /** * @dev Prevents a contract from calling itself, directly or indirectly. * Calling a `nonReentrant` function from another `nonReentrant` * function is not supported. It is possible to prevent this from happening * by making the `nonReentrant` function external, and make it call a * `private` function that does the actual work. */ modifier nonReentrant() { // On the first call to nonReentrant, _notEntered will be true require(_status != _ENTERED, "ReentrancyGuard: reentrant call"); // Any calls to nonReentrant after this point will fail _status = _ENTERED; _; // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) _status = _NOT_ENTERED; } } // File: @openzeppelin/contracts/utils/Address.sol pragma solidity >=0.6.2 <0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: value }(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.delegatecall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // File: @openzeppelin/contracts/token/ERC20/SafeERC20.sol pragma solidity >=0.6.0 <0.8.0; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using SafeMath for uint256; using Address for address; function safeTransfer(IERC20 token, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove(IERC20 token, address spender, uint256 value) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' // solhint-disable-next-line max-line-length require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).add(value); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero"); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // File: contracts/libraries/MathExt.sol pragma solidity 0.6.12; library MathExt { using SafeMath for uint256; uint256 public constant PRECISION = (10**18); /// @dev Returns x*y in precision function mulInPrecision(uint256 x, uint256 y) internal pure returns (uint256) { return x.mul(y) / PRECISION; } /// @dev source: dsMath /// @param xInPrecision should be < PRECISION, so this can not overflow /// @return zInPrecision = (x/PRECISION) ^k * PRECISION function unsafePowInPrecision(uint256 xInPrecision, uint256 k) internal pure returns (uint256 zInPrecision) { require(xInPrecision <= PRECISION, "MathExt: x > PRECISION"); zInPrecision = k % 2 != 0 ? xInPrecision : PRECISION; for (k /= 2; k != 0; k /= 2) { xInPrecision = (xInPrecision * xInPrecision) / PRECISION; if (k % 2 != 0) { zInPrecision = (zInPrecision * xInPrecision) / PRECISION; } } } // babylonian method (https://en.wikipedia.org/wiki/Methods_of_computing_square_roots#Babylonian_method) function sqrt(uint256 y) internal pure returns (uint256 z) { if (y > 3) { z = y; uint256 x = y / 2 + 1; while (x < z) { z = x; x = (y / x + x) / 2; } } else if (y != 0) { z = 1; } } } // File: contracts/libraries/FeeFomula.sol pragma solidity 0.6.12; library FeeFomula { using SafeMath for uint256; using MathExt for uint256; uint256 private constant PRECISION = 10**18; uint256 private constant R0 = 1477405064814996100; // 1.4774050648149961 uint256 private constant C0 = (60 * PRECISION) / 10000; uint256 private constant A = uint256(PRECISION * 20000) / 27; uint256 private constant B = uint256(PRECISION * 250) / 9; uint256 private constant C1 = uint256(PRECISION * 985) / 27; uint256 private constant U = (120 * PRECISION) / 100; uint256 private constant G = (836 * PRECISION) / 1000; uint256 private constant F = 5 * PRECISION; uint256 private constant L = (2 * PRECISION) / 10000; // C2 = 25 * PRECISION - (F * (PRECISION - G)**2) / ((PRECISION - G)**2 + L * PRECISION) uint256 private constant C2 = 20036905816356657810; /// @dev calculate fee from rFactorInPrecision, see section 3.2 in dmmSwap white paper /// @dev fee in [15, 60] bps /// @return fee percentage in Precision function getFee(uint256 rFactorInPrecision) internal pure returns (uint256) { if (rFactorInPrecision >= R0) { return C0; } else if (rFactorInPrecision >= PRECISION) { // C1 + A * (r-U)^3 + b * (r -U) if (rFactorInPrecision > U) { uint256 tmp = rFactorInPrecision - U; uint256 tmp3 = tmp.unsafePowInPrecision(3); return (C1.add(A.mulInPrecision(tmp3)).add(B.mulInPrecision(tmp))) / 10000; } else { uint256 tmp = U - rFactorInPrecision; uint256 tmp3 = tmp.unsafePowInPrecision(3); return C1.sub(A.mulInPrecision(tmp3)).sub(B.mulInPrecision(tmp)) / 10000; } } else { // [ C2 + sign(r - G) * F * (r-G) ^2 / (L + (r-G) ^2) ] / 10000 uint256 tmp = ( rFactorInPrecision > G ? (rFactorInPrecision - G) : (G - rFactorInPrecision) ); tmp = tmp.unsafePowInPrecision(2); uint256 tmp2 = F.mul(tmp).div(tmp.add(L)); if (rFactorInPrecision > G) { return C2.add(tmp2) / 10000; } else { return C2.sub(tmp2) / 10000; } } } } // File: @openzeppelin/contracts/utils/Context.sol pragma solidity >=0.6.0 <0.8.0; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } // File: @openzeppelin/contracts/token/ERC20/ERC20.sol pragma solidity >=0.6.0 <0.8.0; /** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20PresetMinterPauser}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin guidelines: functions revert instead * of returning `false` on failure. This behavior is nonetheless conventional * and does not conflict with the expectations of ERC20 applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */ contract 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 virtual returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view virtual returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless {_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 virtual 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); _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 virtual { _decimals = decimals_; } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be to transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { } } // File: contracts/interfaces/IERC20Permit.sol pragma solidity 0.6.12; interface IERC20Permit is IERC20 { function permit( address owner, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) external; } // File: contracts/libraries/ERC20Permit.sol pragma solidity 0.6.12; /// @dev https://eips.ethereum.org/EIPS/eip-2612 contract ERC20Permit is ERC20, IERC20Permit { /// @dev To make etherscan auto-verify new pool, this variable is not immutable bytes32 public domainSeparator; // keccak256("Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)"); bytes32 public constant PERMIT_TYPEHASH = 0x6e71edae12b1b97f4d1f60370fef10105fa2faae0126114a169c64845d6126c9; mapping(address => uint256) public nonces; constructor( string memory name, string memory symbol, string memory version ) public ERC20(name, symbol) { uint256 chainId; assembly { chainId := chainid() } domainSeparator = keccak256( abi.encode( keccak256( "EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)" ), keccak256(bytes(name)), keccak256(bytes(version)), chainId, address(this) ) ); } function permit( address owner, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) external override { require(deadline >= block.timestamp, "ERC20Permit: EXPIRED"); bytes32 digest = keccak256( abi.encodePacked( "\x19\x01", domainSeparator, keccak256( abi.encode(PERMIT_TYPEHASH, owner, spender, value, nonces[owner]++, deadline) ) ) ); address recoveredAddress = ecrecover(digest, v, r, s); require( recoveredAddress != address(0) && recoveredAddress == owner, "ERC20Permit: INVALID_SIGNATURE" ); _approve(owner, spender, value); } } // File: contracts/interfaces/IDMMCallee.sol pragma solidity 0.6.12; interface IDMMCallee { function dmmSwapCall( address sender, uint256 amount0, uint256 amount1, bytes calldata data ) external; } // File: contracts/interfaces/IDMMPool.sol pragma solidity 0.6.12; interface IDMMPool { function mint(address to) external returns (uint256 liquidity); function burn(address to) external returns (uint256 amount0, uint256 amount1); function swap( uint256 amount0Out, uint256 amount1Out, address to, bytes calldata data ) external; function sync() external; function getReserves() external view returns (uint112 reserve0, uint112 reserve1); function getTradeInfo() external view returns ( uint112 _vReserve0, uint112 _vReserve1, uint112 reserve0, uint112 reserve1, uint256 feeInPrecision ); function token0() external view returns (IERC20); function token1() external view returns (IERC20); function ampBps() external view returns (uint32); function factory() external view returns (IDMMFactory); function kLast() external view returns (uint256); } // File: contracts/interfaces/IERC20Metadata.sol pragma solidity 0.6.12; /** * @dev Interface for the optional metadata functions from the ERC20 standard. */ 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: contracts/VolumeTrendRecorder.sol pragma solidity 0.6.12; /// @dev contract to calculate volume trend. See secion 3.1 in the white paper /// @dev EMA stands for Exponential moving average /// @dev https://en.wikipedia.org/wiki/Moving_average contract VolumeTrendRecorder { using MathExt for uint256; using SafeMath for uint256; uint256 private constant MAX_UINT128 = 2**128 - 1; uint256 internal constant PRECISION = 10**18; uint256 private constant SHORT_ALPHA = (2 * PRECISION) / 5401; uint256 private constant LONG_ALPHA = (2 * PRECISION) / 10801; uint128 internal shortEMA; uint128 internal longEMA; // total volume in current block uint128 internal currentBlockVolume; uint128 internal lastTradeBlock; event UpdateEMA(uint256 shortEMA, uint256 longEMA, uint128 lastBlockVolume, uint256 skipBlock); constructor(uint128 _emaInit) public { shortEMA = _emaInit; longEMA = _emaInit; lastTradeBlock = safeUint128(block.number); } function getVolumeTrendData() external view returns ( uint128 _shortEMA, uint128 _longEMA, uint128 _currentBlockVolume, uint128 _lastTradeBlock ) { _shortEMA = shortEMA; _longEMA = longEMA; _currentBlockVolume = currentBlockVolume; _lastTradeBlock = lastTradeBlock; } /// @dev records a new trade, update ema and returns current rFactor for this trade /// @return rFactor in Precision for this trade function recordNewUpdatedVolume(uint256 blockNumber, uint256 value) internal returns (uint256) { // this can not be underflow because block.number always increases uint256 skipBlock = blockNumber - lastTradeBlock; if (skipBlock == 0) { currentBlockVolume = safeUint128( uint256(currentBlockVolume).add(value), "volume exceeds valid range" ); return calculateRFactor(uint256(shortEMA), uint256(longEMA)); } uint128 _currentBlockVolume = currentBlockVolume; uint256 _shortEMA = newEMA(shortEMA, SHORT_ALPHA, currentBlockVolume); uint256 _longEMA = newEMA(longEMA, LONG_ALPHA, currentBlockVolume); // ema = ema * (1-aplha) ^(skipBlock -1) _shortEMA = _shortEMA.mulInPrecision( (PRECISION - SHORT_ALPHA).unsafePowInPrecision(skipBlock - 1) ); _longEMA = _longEMA.mulInPrecision( (PRECISION - LONG_ALPHA).unsafePowInPrecision(skipBlock - 1) ); shortEMA = safeUint128(_shortEMA); longEMA = safeUint128(_longEMA); currentBlockVolume = safeUint128(value); lastTradeBlock = safeUint128(blockNumber); emit UpdateEMA(_shortEMA, _longEMA, _currentBlockVolume, skipBlock); return calculateRFactor(_shortEMA, _longEMA); } /// @return rFactor in Precision for this trade function getRFactor(uint256 blockNumber) internal view returns (uint256) { // this can not be underflow because block.number always increases uint256 skipBlock = blockNumber - lastTradeBlock; if (skipBlock == 0) { return calculateRFactor(shortEMA, longEMA); } uint256 _shortEMA = newEMA(shortEMA, SHORT_ALPHA, currentBlockVolume); uint256 _longEMA = newEMA(longEMA, LONG_ALPHA, currentBlockVolume); _shortEMA = _shortEMA.mulInPrecision( (PRECISION - SHORT_ALPHA).unsafePowInPrecision(skipBlock - 1) ); _longEMA = _longEMA.mulInPrecision( (PRECISION - LONG_ALPHA).unsafePowInPrecision(skipBlock - 1) ); return calculateRFactor(_shortEMA, _longEMA); } function calculateRFactor(uint256 _shortEMA, uint256 _longEMA) internal pure returns (uint256) { if (_longEMA == 0) { return 0; } return (_shortEMA * MathExt.PRECISION) / _longEMA; } /// @dev return newEMA value /// @param ema previous ema value in wei /// @param alpha in Precicion (required < Precision) /// @param value current value to update ema /// @dev ema and value is uint128 and alpha < Percison /// @dev so this function can not overflow and returned ema is not overflow uint128 function newEMA( uint128 ema, uint256 alpha, uint128 value ) internal pure returns (uint256) { assert(alpha < PRECISION); return ((PRECISION - alpha) * uint256(ema) + alpha * uint256(value)) / PRECISION; } function safeUint128(uint256 v) internal pure returns (uint128) { require(v <= MAX_UINT128, "overflow uint128"); return uint128(v); } function safeUint128(uint256 v, string memory errorMessage) internal pure returns (uint128) { require(v <= MAX_UINT128, errorMessage); return uint128(v); } } // File: contracts/DMMPool.sol pragma solidity 0.6.12; contract DMMPool is IDMMPool, ERC20Permit, ReentrancyGuard, VolumeTrendRecorder { using SafeMath for uint256; using SafeERC20 for IERC20; uint256 internal constant MAX_UINT112 = 2**112 - 1; uint256 internal constant BPS = 10000; struct ReserveData { uint256 reserve0; uint256 reserve1; uint256 vReserve0; uint256 vReserve1; // only used when isAmpPool = true } uint256 public constant MINIMUM_LIQUIDITY = 10**3; /// @dev To make etherscan auto-verify new pool, these variables are not immutable IDMMFactory public override factory; IERC20 public override token0; IERC20 public override token1; /// @dev uses single storage slot, accessible via getReservesData uint112 internal reserve0; uint112 internal reserve1; uint32 public override ampBps; /// @dev addition param only when amplification factor > 1 uint112 internal vReserve0; uint112 internal vReserve1; /// @dev vReserve0 * vReserve1, as of immediately after the most recent liquidity event uint256 public override kLast; event Mint(address indexed sender, uint256 amount0, uint256 amount1); event Burn(address indexed sender, uint256 amount0, uint256 amount1, address indexed to); event Swap( address indexed sender, uint256 amount0In, uint256 amount1In, uint256 amount0Out, uint256 amount1Out, address indexed to, uint256 feeInPrecision ); event Sync(uint256 vReserve0, uint256 vReserve1, uint256 reserve0, uint256 reserve1); constructor() public ERC20Permit("KyberDMM LP", "DMM-LP", "1") VolumeTrendRecorder(0) { factory = IDMMFactory(msg.sender); } // called once by the factory at time of deployment function initialize( IERC20 _token0, IERC20 _token1, uint32 _ampBps ) external { require(msg.sender == address(factory), "DMM: FORBIDDEN"); token0 = _token0; token1 = _token1; ampBps = _ampBps; } /// @dev this low-level function should be called from a contract /// which performs important safety checks function mint(address to) external override nonReentrant returns (uint256 liquidity) { (bool isAmpPool, ReserveData memory data) = getReservesData(); ReserveData memory _data; _data.reserve0 = token0.balanceOf(address(this)); _data.reserve1 = token1.balanceOf(address(this)); uint256 amount0 = _data.reserve0.sub(data.reserve0); uint256 amount1 = _data.reserve1.sub(data.reserve1); bool feeOn = _mintFee(isAmpPool, data); uint256 _totalSupply = totalSupply(); // gas savings, must be defined here since totalSupply can update in _mintFee if (_totalSupply == 0) { if (isAmpPool) { uint32 _ampBps = ampBps; _data.vReserve0 = _data.reserve0.mul(_ampBps) / BPS; _data.vReserve1 = _data.reserve1.mul(_ampBps) / BPS; } liquidity = MathExt.sqrt(amount0.mul(amount1)).sub(MINIMUM_LIQUIDITY); _mint(address(-1), MINIMUM_LIQUIDITY); // permanently lock the first MINIMUM_LIQUIDITY tokens } else { liquidity = Math.min( amount0.mul(_totalSupply) / data.reserve0, amount1.mul(_totalSupply) / data.reserve1 ); if (isAmpPool) { uint256 b = liquidity.add(_totalSupply); _data.vReserve0 = Math.max(data.vReserve0.mul(b) / _totalSupply, _data.reserve0); _data.vReserve1 = Math.max(data.vReserve1.mul(b) / _totalSupply, _data.reserve1); } } require(liquidity > 0, "DMM: INSUFFICIENT_LIQUIDITY_MINTED"); _mint(to, liquidity); _update(isAmpPool, _data); if (feeOn) kLast = getK(isAmpPool, _data); emit Mint(msg.sender, amount0, amount1); } /// @dev this low-level function should be called from a contract /// @dev which performs important safety checks /// @dev user must transfer LP token to this contract before call burn function burn(address to) external override nonReentrant returns (uint256 amount0, uint256 amount1) { (bool isAmpPool, ReserveData memory data) = getReservesData(); // gas savings IERC20 _token0 = token0; // gas savings IERC20 _token1 = token1; // gas savings uint256 balance0 = _token0.balanceOf(address(this)); uint256 balance1 = _token1.balanceOf(address(this)); require(balance0 >= data.reserve0 && balance1 >= data.reserve1, "DMM: UNSYNC_RESERVES"); uint256 liquidity = balanceOf(address(this)); bool feeOn = _mintFee(isAmpPool, data); uint256 _totalSupply = totalSupply(); // gas savings, must be defined here since totalSupply can update in _mintFee amount0 = liquidity.mul(balance0) / _totalSupply; // using balances ensures pro-rata distribution amount1 = liquidity.mul(balance1) / _totalSupply; // using balances ensures pro-rata distribution require(amount0 > 0 && amount1 > 0, "DMM: INSUFFICIENT_LIQUIDITY_BURNED"); _burn(address(this), liquidity); _token0.safeTransfer(to, amount0); _token1.safeTransfer(to, amount1); ReserveData memory _data; _data.reserve0 = _token0.balanceOf(address(this)); _data.reserve1 = _token1.balanceOf(address(this)); if (isAmpPool) { uint256 b = Math.min( _data.reserve0.mul(_totalSupply) / data.reserve0, _data.reserve1.mul(_totalSupply) / data.reserve1 ); _data.vReserve0 = Math.max(data.vReserve0.mul(b) / _totalSupply, _data.reserve0); _data.vReserve1 = Math.max(data.vReserve1.mul(b) / _totalSupply, _data.reserve1); } _update(isAmpPool, _data); if (feeOn) kLast = getK(isAmpPool, _data); // data are up-to-date emit Burn(msg.sender, amount0, amount1, to); } /// @dev this low-level function should be called from a contract /// @dev which performs important safety checks function swap( uint256 amount0Out, uint256 amount1Out, address to, bytes calldata callbackData ) external override nonReentrant { require(amount0Out > 0 || amount1Out > 0, "DMM: INSUFFICIENT_OUTPUT_AMOUNT"); (bool isAmpPool, ReserveData memory data) = getReservesData(); // gas savings require( amount0Out < data.reserve0 && amount1Out < data.reserve1, "DMM: INSUFFICIENT_LIQUIDITY" ); ReserveData memory newData; { // scope for _token{0,1}, avoids stack too deep errors IERC20 _token0 = token0; IERC20 _token1 = token1; require(to != address(_token0) && to != address(_token1), "DMM: INVALID_TO"); if (amount0Out > 0) _token0.safeTransfer(to, amount0Out); // optimistically transfer tokens if (amount1Out > 0) _token1.safeTransfer(to, amount1Out); // optimistically transfer tokens if (callbackData.length > 0) IDMMCallee(to).dmmSwapCall(msg.sender, amount0Out, amount1Out, callbackData); newData.reserve0 = _token0.balanceOf(address(this)); newData.reserve1 = _token1.balanceOf(address(this)); if (isAmpPool) { newData.vReserve0 = data.vReserve0.add(newData.reserve0).sub(data.reserve0); newData.vReserve1 = data.vReserve1.add(newData.reserve1).sub(data.reserve1); } } uint256 amount0In = newData.reserve0 > data.reserve0 - amount0Out ? newData.reserve0 - (data.reserve0 - amount0Out) : 0; uint256 amount1In = newData.reserve1 > data.reserve1 - amount1Out ? newData.reserve1 - (data.reserve1 - amount1Out) : 0; require(amount0In > 0 || amount1In > 0, "DMM: INSUFFICIENT_INPUT_AMOUNT"); uint256 feeInPrecision = verifyBalanceAndUpdateEma( amount0In, amount1In, isAmpPool ? data.vReserve0 : data.reserve0, isAmpPool ? data.vReserve1 : data.reserve1, isAmpPool ? newData.vReserve0 : newData.reserve0, isAmpPool ? newData.vReserve1 : newData.reserve1 ); _update(isAmpPool, newData); emit Swap(msg.sender, amount0In, amount1In, amount0Out, amount1Out, to, feeInPrecision); } /// @dev force balances to match reserves function skim(address to) external nonReentrant { token0.safeTransfer(to, token0.balanceOf(address(this)).sub(reserve0)); token1.safeTransfer(to, token1.balanceOf(address(this)).sub(reserve1)); } /// @dev force reserves to match balances function sync() external override nonReentrant { (bool isAmpPool, ReserveData memory data) = getReservesData(); bool feeOn = _mintFee(isAmpPool, data); ReserveData memory newData; newData.reserve0 = IERC20(token0).balanceOf(address(this)); newData.reserve1 = IERC20(token1).balanceOf(address(this)); // update virtual reserves if this is amp pool if (isAmpPool) { uint256 _totalSupply = totalSupply(); uint256 b = Math.min( newData.reserve0.mul(_totalSupply) / data.reserve0, newData.reserve1.mul(_totalSupply) / data.reserve1 ); newData.vReserve0 = Math.max(data.vReserve0.mul(b) / _totalSupply, newData.reserve0); newData.vReserve1 = Math.max(data.vReserve1.mul(b) / _totalSupply, newData.reserve1); } _update(isAmpPool, newData); if (feeOn) kLast = getK(isAmpPool, newData); } /// @dev returns data to calculate amountIn, amountOut function getTradeInfo() external virtual override view returns ( uint112 _reserve0, uint112 _reserve1, uint112 _vReserve0, uint112 _vReserve1, uint256 feeInPrecision ) { // gas saving to read reserve data _reserve0 = reserve0; _reserve1 = reserve1; uint32 _ampBps = ampBps; _vReserve0 = vReserve0; _vReserve1 = vReserve1; if (_ampBps == BPS) { _vReserve0 = _reserve0; _vReserve1 = _reserve1; } uint256 rFactorInPrecision = getRFactor(block.number); feeInPrecision = getFinalFee(FeeFomula.getFee(rFactorInPrecision), _ampBps); } /// @dev returns reserve data to calculate amount to add liquidity function getReserves() external override view returns (uint112 _reserve0, uint112 _reserve1) { _reserve0 = reserve0; _reserve1 = reserve1; } function name() public override view returns (string memory) { IERC20Metadata _token0 = IERC20Metadata(address(token0)); IERC20Metadata _token1 = IERC20Metadata(address(token1)); return string(abi.encodePacked("KyberDMM LP ", _token0.symbol(), "-", _token1.symbol())); } function symbol() public override view returns (string memory) { IERC20Metadata _token0 = IERC20Metadata(address(token0)); IERC20Metadata _token1 = IERC20Metadata(address(token1)); return string(abi.encodePacked("DMM-LP ", _token0.symbol(), "-", _token1.symbol())); } function verifyBalanceAndUpdateEma( uint256 amount0In, uint256 amount1In, uint256 beforeReserve0, uint256 beforeReserve1, uint256 afterReserve0, uint256 afterReserve1 ) internal virtual returns (uint256 feeInPrecision) { // volume = beforeReserve0 * amount1In / beforeReserve1 + amount0In (normalized into amount in token 0) uint256 volume = beforeReserve0.mul(amount1In).div(beforeReserve1).add(amount0In); uint256 rFactorInPrecision = recordNewUpdatedVolume(block.number, volume); feeInPrecision = getFinalFee(FeeFomula.getFee(rFactorInPrecision), ampBps); // verify balance update matches with fomula uint256 balance0Adjusted = afterReserve0.mul(PRECISION); balance0Adjusted = balance0Adjusted.sub(amount0In.mul(feeInPrecision)); balance0Adjusted = balance0Adjusted / PRECISION; uint256 balance1Adjusted = afterReserve1.mul(PRECISION); balance1Adjusted = balance1Adjusted.sub(amount1In.mul(feeInPrecision)); balance1Adjusted = balance1Adjusted / PRECISION; require( balance0Adjusted.mul(balance1Adjusted) >= beforeReserve0.mul(beforeReserve1), "DMM: K" ); } /// @dev update reserves function _update(bool isAmpPool, ReserveData memory data) internal { reserve0 = safeUint112(data.reserve0); reserve1 = safeUint112(data.reserve1); if (isAmpPool) { assert(data.vReserve0 >= data.reserve0 && data.vReserve1 >= data.reserve1); // never happen vReserve0 = safeUint112(data.vReserve0); vReserve1 = safeUint112(data.vReserve1); } emit Sync(data.vReserve0, data.vReserve1, data.reserve0, data.reserve1); } /// @dev if fee is on, mint liquidity equivalent to configured fee of the growth in sqrt(k) function _mintFee(bool isAmpPool, ReserveData memory data) internal returns (bool feeOn) { (address feeTo, uint16 governmentFeeBps) = factory.getFeeConfiguration(); feeOn = feeTo != address(0); uint256 _kLast = kLast; // gas savings if (feeOn) { if (_kLast != 0) { uint256 rootK = MathExt.sqrt(getK(isAmpPool, data)); uint256 rootKLast = MathExt.sqrt(_kLast); if (rootK > rootKLast) { uint256 numerator = totalSupply().mul(rootK.sub(rootKLast)).mul( governmentFeeBps ); uint256 denominator = rootK.add(rootKLast).mul(5000); uint256 liquidity = numerator / denominator; if (liquidity > 0) _mint(feeTo, liquidity); } } } else if (_kLast != 0) { kLast = 0; } } /// @dev gas saving to read reserve data function getReservesData() internal view returns (bool isAmpPool, ReserveData memory data) { data.reserve0 = reserve0; data.reserve1 = reserve1; isAmpPool = ampBps != BPS; if (isAmpPool) { data.vReserve0 = vReserve0; data.vReserve1 = vReserve1; } } function getFinalFee(uint256 feeInPrecision, uint32 _ampBps) internal pure returns (uint256) { if (_ampBps <= 20000) { return feeInPrecision; } else if (_ampBps <= 50000) { return (feeInPrecision * 20) / 30; } else if (_ampBps <= 200000) { return (feeInPrecision * 10) / 30; } else { return (feeInPrecision * 4) / 30; } } function getK(bool isAmpPool, ReserveData memory data) internal pure returns (uint256) { return isAmpPool ? data.vReserve0 * data.vReserve1 : data.reserve0 * data.reserve1; } function safeUint112(uint256 x) internal pure returns (uint112) { require(x <= MAX_UINT112, "DMM: OVERFLOW"); return uint112(x); } } // File: contracts/DMMFactory.sol pragma solidity 0.6.12; contract DMMFactory is IDMMFactory { using EnumerableSet for EnumerableSet.AddressSet; uint256 internal constant BPS = 10000; address private feeTo; uint16 private governmentFeeBps; address public override feeToSetter; mapping(IERC20 => mapping(IERC20 => EnumerableSet.AddressSet)) internal tokenPools; mapping(IERC20 => mapping(IERC20 => address)) public override getUnamplifiedPool; address[] public override allPools; event PoolCreated( IERC20 indexed token0, IERC20 indexed token1, address pool, uint32 ampBps, uint256 totalPool ); event SetFeeConfiguration(address feeTo, uint16 governmentFeeBps); event SetFeeToSetter(address feeToSetter); constructor(address _feeToSetter) public { feeToSetter = _feeToSetter; } function createPool( IERC20 tokenA, IERC20 tokenB, uint32 ampBps ) external override returns (address pool) { require(tokenA != tokenB, "DMM: IDENTICAL_ADDRESSES"); (IERC20 token0, IERC20 token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA); require(address(token0) != address(0), "DMM: ZERO_ADDRESS"); require(ampBps >= BPS, "DMM: INVALID_BPS"); // only exist 1 unamplified pool of a pool. require( ampBps != BPS || getUnamplifiedPool[token0][token1] == address(0), "DMM: UNAMPLIFIED_POOL_EXISTS" ); pool = address(new DMMPool()); DMMPool(pool).initialize(token0, token1, ampBps); // populate mapping in the reverse direction tokenPools[token0][token1].add(pool); tokenPools[token1][token0].add(pool); if (ampBps == BPS) { getUnamplifiedPool[token0][token1] = pool; getUnamplifiedPool[token1][token0] = pool; } allPools.push(pool); emit PoolCreated(token0, token1, pool, ampBps, allPools.length); } function setFeeConfiguration(address _feeTo, uint16 _governmentFeeBps) external override { require(msg.sender == feeToSetter, "DMM: FORBIDDEN"); require(_governmentFeeBps > 0 && _governmentFeeBps < 2000, "DMM: INVALID FEE"); feeTo = _feeTo; governmentFeeBps = _governmentFeeBps; emit SetFeeConfiguration(_feeTo, _governmentFeeBps); } function setFeeToSetter(address _feeToSetter) external override { require(msg.sender == feeToSetter, "DMM: FORBIDDEN"); feeToSetter = _feeToSetter; emit SetFeeToSetter(_feeToSetter); } function getFeeConfiguration() external override view returns (address _feeTo, uint16 _governmentFeeBps) { _feeTo = feeTo; _governmentFeeBps = governmentFeeBps; } function allPoolsLength() external override view returns (uint256) { return allPools.length; } function getPools(IERC20 token0, IERC20 token1) external override view returns (address[] memory _tokenPools) { uint256 length = tokenPools[token0][token1].length(); _tokenPools = new address[](length); for (uint256 i = 0; i < length; i++) { _tokenPools[i] = tokenPools[token0][token1].at(i); } } function getPoolsLength(IERC20 token0, IERC20 token1) external view returns (uint256) { return tokenPools[token0][token1].length(); } function getPoolAtIndex( IERC20 token0, IERC20 token1, uint256 index ) external view returns (address pool) { return tokenPools[token0][token1].at(index); } function isPool( IERC20 token0, IERC20 token1, address pool ) external override view returns (bool) { return tokenPools[token0][token1].contains(pool); } }
calculate fee from rFactorInPrecision, see section 3.2 in dmmSwap white paper fee in [15, 60] bps return fee percentage in Precision C1 + A (r-U)^3 + b (r -U)
function getFee(uint256 rFactorInPrecision) internal pure returns (uint256) { if (rFactorInPrecision >= R0) { return C0; if (rFactorInPrecision > U) { uint256 tmp = rFactorInPrecision - U; uint256 tmp3 = tmp.unsafePowInPrecision(3); return (C1.add(A.mulInPrecision(tmp3)).add(B.mulInPrecision(tmp))) / 10000; uint256 tmp = U - rFactorInPrecision; uint256 tmp3 = tmp.unsafePowInPrecision(3); return C1.sub(A.mulInPrecision(tmp3)).sub(B.mulInPrecision(tmp)) / 10000; } rFactorInPrecision > G ? (rFactorInPrecision - G) : (G - rFactorInPrecision) ); tmp = tmp.unsafePowInPrecision(2); uint256 tmp2 = F.mul(tmp).div(tmp.add(L)); if (rFactorInPrecision > G) { return C2.add(tmp2) / 10000; return C2.sub(tmp2) / 10000; } } }
2,135,851
./partial_match/40/0xc61A42a16C3FCB89bA5fdCC92BF2FB377D00719d/sources/contracts/TelosNFT.sol
toggles the state of mint
function setMintingState(MintState state) external onlyOwner { mintingState = state; }
8,827,663
pragma solidity ^0.4.23; import "./Authentication.sol"; /// @title A decentralized organization with members, tasks, and voting. /// @author Dennis Liu contract DAO is Authentication { using SafeMath for uint256; // type for a single task struct Task { uint taskId; address proposer; // address who proposed the task string name; // member name who proposed the task string title; // task name string content; // task detail uint256 voteCount; // number of accumulated votes bool nonconsensus; // bool to signal that someone voted no bool finished; // bool to signal voting has finished } // A dynamically-sized array of `Task` structs. Task[] public tasks; // Lists each task's voted members // Use a uint to represent 3 states, 0: unvoted; 1: yes; 2: no mapping(uint => mapping (address => uint)) public votedMap; mapping(uint => address[]) private votedList; modifier taskVotable(uint taskId) { // Check if the task can be voted on require(!tasks[taskId].finished, "Voting on this task has finished"); require(votedMap[taskId][msg.sender] == 0, "Member has already voted on this task"); _; } modifier taskExists(uint taskId) { // Check if the task exists require(bytes(tasks[taskId].title).length != 0, "Task does not exist"); _; } modifier onlyProposer(uint taskId) { // Check if member is the proposer of the task require(tasks[taskId].proposer == msg.sender, "Member is not the proposer of the task"); _; } event taskUpdated(); // event newTask(uint taskId, address proposer, string name, string title, string content); // event newVote(uint taskId, uint voteCount); // event voteFinished(uint taskId, bool approved); // event taskRemoved(uint taskId); /// @notice Propose a new task /// @notice Only existing user addresses can propose a task. proposer doesn't have to vote yes for their tasks /// @param title title of the proposed task /// @param content content of the proposed task function propose(string title, string content) public onlyExistingMember { // push returns new length, hence the new task's ID is length - 1 uint taskId = tasks.push(Task(0, msg.sender, members[msg.sender].name, title, content, 0, false, false)) - 1; tasks[taskId].taskId = taskId; emit taskUpdated(); // emit newTask(taskId, msg.sender, members[msg.sender].name, title, content); } /// @notice Vote on a task by its id /// @notice If anyone votes no, the task will be disapproved when voting is finished /// @param taskId index of the task in tasks array /// @param agree boolean of true or false signifying yes or no vote function vote(uint taskId, bool agree) public onlyExistingMember taskExists(taskId) taskVotable(taskId) { // if anyone votes no, there will be no consensus in the end if (!agree) { tasks[taskId].nonconsensus = true; votedMap[taskId][msg.sender] = 2; // 2 maps to no } else { votedMap[taskId][msg.sender] = 1; // 1 maps to yes } tasks[taskId].voteCount++; votedList[taskId].push(msg.sender); emit taskUpdated(); // emit newVote(taskId, tasks[taskId].voteCount); // set task as finished emit voteFinished event when all members have voted if (tasks[taskId].voteCount >= memberCount) { tasks[taskId].finished = true; emit taskUpdated(); // emit voteFinished(taskId, !tasks[taskId].nonconsensus); } } /// @notice Remove a disapproved task /// @notice Only the owner of the task /// @param taskId index of the task in tasks array function remove(uint taskId) public onlyExistingMember taskExists(taskId) onlyProposer(taskId) { delete tasks[taskId]; delete votedList[taskId]; emit taskUpdated(); // emit taskRemoved(taskId); } /// @notice Return voted members for a task after its voting is finished /// @notice This prevents member's votes being influenced by existing votes /// @param taskId index of the task in tasks array /// @return voted member addresses in an array function getVoted(uint taskId) public view taskExists(taskId) onlyExistingMember returns (address[]) { require(tasks[taskId].finished, "Voting on this task has not finished"); return votedList[taskId]; } function getTaskCount() public view onlyExistingMember returns (uint) { return tasks.length; } }
Return voted members for a task after its voting is finished This prevents member's votes being influenced by existing votes taskId index of the task in tasks array return voted member addresses in an array
function getVoted(uint taskId) public view taskExists(taskId) onlyExistingMember returns (address[]) { require(tasks[taskId].finished, "Voting on this task has not finished"); return votedList[taskId]; }
5,433,986
pragma solidity 0.6.8; // This file is MIT Licensed. // // Copyright 2017 Christian Reitwiessner // 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. // More information at https://gist.github.com/chriseth/f9be9d9391efc5beb9704255a8e2989d library Pairing { struct G1Point { uint256 x; uint256 y; } struct G2Point { uint256[2] x; uint256[2] y; } /** * @return the generator of G1 */ function g1() internal pure returns (G1Point memory) { return G1Point(1, 2); } /** * @return the generator of G2 */ function g2() internal pure returns (G2Point memory) { return G2Point( [ 11559732032986387107991004021392285783925812861821192530917403151452391805634, 10857046999023057135944570762232829481370756359578518086990519993285655852781 ], [ 4082367875863433681332203403145435568316851327593401208105741076214120093531, 8495653923123431417604973247489272438418190587263600148770280649306958101930 ] ); } /** * @return the sum of two points on G1 */ function addPoints(G1Point memory a, G1Point memory b) internal view returns (G1Point memory) { uint256[4] memory input = [a.x, a.y, b.x, b.y]; uint256[2] memory result; bool success; assembly { success := staticcall(not(0), 0x06, input, 0x80, result, 0x40) } require(success, "elliptic curve addition failed"); return G1Point(result[0], result[1]); } /** * @return the product of a point on G1 and a scalar */ function scalarMult(G1Point memory p, uint256 s) internal view returns (G1Point memory) { uint256[3] memory input; input[0] = p.x; input[1] = p.y; input[2] = s; bool success; G1Point memory result; assembly { // 0x07 id of precompiled bn256ScalarMul contract // 0 since we have an array of fixed length, our input starts in 0 // 96 size of call parameters, i.e. 96 bytes total (256 bit for x, 256 bit for y, 256 bit for scalar) // 64 size of call return value, i.e. 64 bytes / 512 bit for a BN256 curve point success := staticcall(not(0), 0x07, input, 96, result, 64) } require(success, "elliptic curve multiplication failed"); return result; } /** * @return the negation of point p */ function negate(G1Point memory p) internal pure returns (G1Point memory) { uint256 P = 21888242871839275222246405745257275088696311157297823662689037894645226208583; if (p.x == 0 && p.y == 0) { return G1Point(0, 0); } return G1Point(p.x, P - (p.y % P)); } function modExp( uint256 base, uint256 exponent, uint256 modulus ) internal view returns (uint256) { uint256[6] memory input = [32, 32, 32, base, exponent, modulus]; uint256[1] memory result; bool success; assembly { success := staticcall(not(0), 0x05, input, 0xc0, result, 0x20) } require(success, "call modExp failed"); return result[0]; } /** * @dev Checks if e(p1[0], p2[0]) * .... * e(p1[n], p2[n]) == 1 * * @return the result of computing the pairing check */ function check(G1Point[] memory p1, G2Point[] memory p2) internal view returns (bool) { uint256 P = 21888242871839275222246405745257275088696311157297823662689037894645226208583; require(p1.length == p2.length, "EC pairing p1 length != p2 length"); uint256 elements = p1.length; uint256 inputSize = elements * 6; uint256[] memory input = new uint256[](inputSize); for (uint256 i = 0; i < elements; i++) { input[i * 6 + 0] = p1[i].x; input[i * 6 + 1] = p1[i].y; input[i * 6 + 2] = p2[i].x[0]; input[i * 6 + 3] = p2[i].x[1]; input[i * 6 + 4] = p2[i].y[0]; input[i * 6 + 5] = p2[i].y[1]; } // negative p1[0].y input[1] = P - (input[1] % P); uint256[1] memory result; bool success; assembly { // 0x08 id of precompiled bn256Pairing contract (checking the elliptic curve pairings) // add(input, 0x20) since we have an unbounded array, the first 256 bits refer to its length // mul(inputSize, 0x20) size of call parameters, each word is 0x20 bytes // 0x20 size of result (one 32 byte boolean!) success := staticcall(not(0), 0x08, add(input, 0x20), mul(inputSize, 0x20), result, 0x20) } // require(success, "elliptic curve pairing failed"); return result[0] == 1; } /** * @dev Convenience method for a pairing check for two pairs. */ function check2( G1Point memory a1, G2Point memory a2, G1Point memory b1, G2Point memory b2 ) internal view returns (bool) { G1Point[] memory p1 = new G1Point[](2); G2Point[] memory p2 = new G2Point[](2); p1[0] = a1; p1[1] = b1; p2[0] = a2; p2[1] = b2; return check(p1, p2); } /** * @dev Hash data to G1 point */ function hashToG1(bytes memory m) internal view returns (G1Point memory) { uint256 P = 21888242871839275222246405745257275088696311157297823662689037894645226208583; uint256 Pminus = 21888242871839275222246405745257275088696311157297823662689037894645226208582; uint256 Pplus = 21888242871839275222246405745257275088696311157297823662689037894645226208584; G1Point memory p; bytes memory bf = abi.encodePacked(uint8(0), keccak256(m)); while (true) { uint256 hx = uint256(keccak256(bf)) % P; uint256 px = modExp(hx, 3, P) + 3; if (modExp(px, Pminus / 2, P) == 1) { uint256 py = modExp(px, Pplus / 4, P); bf[0] = bytes1(uint8(255)); if (uint256(keccak256(bf)) % 2 == 0) { p = G1Point(hx, py); } else { p = G1Point(hx, P - py); } break; } bf[0] = bytes1(uint8(bf[0]) + 1); } return p; } }
return the product of a point on G1 and a scalar/ 0x07 id of precompiled bn256ScalarMul contract 0 since we have an array of fixed length, our input starts in 0 96 size of call parameters, i.e. 96 bytes total (256 bit for x, 256 bit for y, 256 bit for scalar) 64 size of call return value, i.e. 64 bytes / 512 bit for a BN256 curve point
function scalarMult(G1Point memory p, uint256 s) internal view returns (G1Point memory) { uint256[3] memory input; input[0] = p.x; input[1] = p.y; input[2] = s; bool success; G1Point memory result; assembly { success := staticcall(not(0), 0x07, input, 96, result, 64) } require(success, "elliptic curve multiplication failed"); return result; }
15,814,033
/** *Submitted for verification at Etherscan.io on 2020-10-21 */ // SPDX-License-Identifier: MIT pragma solidity ^0.6.6; // From https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/math/Math.sol // Subject to the MIT license. /** * @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(uint a, uint b) internal pure returns (uint) { uint c = a + b; require(c >= a, "Keep3r::SafeMath: addition overflow"); return c; } /** * @dev Returns the addition of two unsigned integers, reverting with custom message on overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * - Addition cannot overflow. */ function add(uint a, uint b, string memory errorMessage) internal pure returns (uint) { uint c = a + b; require(c >= a, errorMessage); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on underflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot underflow. */ function sub(uint a, uint b) internal pure returns (uint) { return sub(a, b, "Keep3r::SafeMath: subtraction underflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on underflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot underflow. */ function sub(uint a, uint b, string memory errorMessage) internal pure returns (uint) { require(b <= a, errorMessage); uint 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(uint a, uint b) internal pure returns (uint) { // 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; } uint c = a * b; require(c / a == b, "Keep3r::SafeMath: multiplication overflow"); return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * - Multiplication cannot overflow. */ function mul(uint a, uint b, string memory errorMessage) internal pure returns (uint) { // 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; } uint c = a * b; require(c / a == b, errorMessage); 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(uint a, uint b) internal pure returns (uint) { return div(a, b, "Keep3r::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(uint a, uint b, string memory errorMessage) internal pure returns (uint) { // Solidity only automatically asserts when dividing by 0 require(b > 0, errorMessage); uint c = a / b; // 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(uint a, uint b) internal pure returns (uint) { return mod(a, b, "Keep3r::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(uint a, uint b, string memory errorMessage) internal pure returns (uint) { require(b != 0, errorMessage); return a % b; } } interface Governance { function proposeJob(address job) external returns (uint); } interface WETH9 { function deposit() external payable; function balanceOf(address account) external view returns (uint); function approve(address spender, uint amount) external returns (bool); } interface Uniswap { function factory() external pure returns (address); function addLiquidity( address tokenA, address tokenB, uint amountADesired, uint amountBDesired, uint amountAMin, uint amountBMin, address to, uint deadline ) external returns (uint amountA, uint amountB, uint liquidity); } interface UniswapPair { function transfer(address to, uint value) external returns (bool); function transferFrom(address from, address to, uint value) external returns (bool); function balanceOf(address account) external view returns (uint); function approve(address spender, uint amount) external returns (bool); function totalSupply() external view returns (uint); } interface Factory { function getPair(address tokenA, address tokenB) external view returns (address pair); } interface Keep3rHelper { function getQuoteLimit(uint gasUsed) external view returns (uint); } contract Keep3r { using SafeMath for uint; /// @notice Keep3r Helper to set max prices for the ecosystem Keep3rHelper public KPRH; /// @notice WETH address to liquidity into UNI WETH9 public constant WETH = WETH9(0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2); /// @notice UniswapV2Router address Uniswap public constant UNI = Uniswap(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D); /// @notice EIP-20 token name for this token string public constant name = "Keep3r"; /// @notice EIP-20 token symbol for this token string public constant symbol = "KPR"; /// @notice EIP-20 token decimals for this token uint8 public constant decimals = 18; /// @notice Total number of tokens in circulation uint public totalSupply = 0; // Initial 0 /// @notice A record of each accounts delegate mapping (address => address) public delegates; /// @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; mapping (address => mapping (address => uint)) internal allowances; mapping (address => uint) internal balances; /// @notice The EIP-712 typehash for the contract's domain bytes32 public constant DOMAIN_TYPEHASH = keccak256("EIP712Domain(string name,uint 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,uint nonce,uint expiry)"); /// @notice The EIP-712 typehash for the permit struct used by the contract bytes32 public constant PERMIT_TYPEHASH = keccak256("Permit(address owner,address spender,uint value,uint nonce,uint deadline)"); /// @notice A record of states for signing / validating signatures mapping (address => uint) public nonces; /// @notice An event thats emitted when an account changes its delegate event DelegateChanged(address indexed delegator, address indexed fromDelegate, address indexed toDelegate); /// @notice An event thats emitted when a delegate account's vote balance changes event DelegateVotesChanged(address indexed delegate, uint previousBalance, uint newBalance); /// @notice A checkpoint for marking number of votes from a given block struct Checkpoint { uint32 fromBlock; uint votes; } /** * @notice Delegate votes from `msg.sender` to `delegatee` * @param delegatee The address to delegate votes to */ function delegate(address delegatee) public { return _delegate(msg.sender, delegatee); } /** * @notice Delegates votes from signatory to `delegatee` * @param delegatee The address to delegate votes to * @param nonce The contract state required to match the signature * @param expiry The time at which to expire the signature * @param v The recovery byte of the signature * @param r Half of the ECDSA signature pair * @param s Half of the ECDSA signature pair */ function delegateBySig(address delegatee, uint nonce, uint expiry, uint8 v, bytes32 r, bytes32 s) public { bytes32 domainSeparator = keccak256(abi.encode(DOMAIN_TYPEHASH, keccak256(bytes(name)), getChainId(), address(this))); bytes32 structHash = keccak256(abi.encode(DELEGATION_TYPEHASH, delegatee, nonce, expiry)); bytes32 digest = keccak256(abi.encodePacked("\x19\x01", domainSeparator, structHash)); address signatory = ecrecover(digest, v, r, s); require(signatory != address(0), "::delegateBySig: invalid signature"); require(nonce == nonces[signatory]++, "::delegateBySig: invalid nonce"); require(now <= expiry, "::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 (uint) { uint32 nCheckpoints = numCheckpoints[account]; return nCheckpoints > 0 ? checkpoints[account][nCheckpoints - 1].votes : 0; } /** * @notice Determine the prior number of votes for an account as of a block number * @dev Block number must be a finalized block or else this function will revert to prevent misinformation. * @param account The address of the account to check * @param blockNumber The block number to get the vote balance at * @return The number of votes the account had as of the given block */ function getPriorVotes(address account, uint blockNumber) public view returns (uint) { require(blockNumber < block.number, "::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]; uint delegatorBalance = bonds[delegator]; delegates[delegator] = delegatee; emit DelegateChanged(delegator, currentDelegate, delegatee); _moveDelegates(currentDelegate, delegatee, delegatorBalance); } function _moveDelegates(address srcRep, address dstRep, uint amount) internal { if (srcRep != dstRep && amount > 0) { if (srcRep != address(0)) { uint32 srcRepNum = numCheckpoints[srcRep]; uint srcRepOld = srcRepNum > 0 ? checkpoints[srcRep][srcRepNum - 1].votes : 0; uint srcRepNew = srcRepOld.sub(amount, "::_moveVotes: vote amount underflows"); _writeCheckpoint(srcRep, srcRepNum, srcRepOld, srcRepNew); } if (dstRep != address(0)) { uint32 dstRepNum = numCheckpoints[dstRep]; uint dstRepOld = dstRepNum > 0 ? checkpoints[dstRep][dstRepNum - 1].votes : 0; uint dstRepNew = dstRepOld.add(amount); _writeCheckpoint(dstRep, dstRepNum, dstRepOld, dstRepNew); } } } function _writeCheckpoint(address delegatee, uint32 nCheckpoints, uint oldVotes, uint newVotes) internal { uint32 blockNumber = safe32(block.number, "::_writeCheckpoint: block number exceeds 32 bits"); if (nCheckpoints > 0 && checkpoints[delegatee][nCheckpoints - 1].fromBlock == blockNumber) { checkpoints[delegatee][nCheckpoints - 1].votes = newVotes; } else { checkpoints[delegatee][nCheckpoints] = Checkpoint(blockNumber, newVotes); numCheckpoints[delegatee] = nCheckpoints + 1; } emit DelegateVotesChanged(delegatee, oldVotes, newVotes); } function safe32(uint n, string memory errorMessage) internal pure returns (uint32) { require(n < 2**32, errorMessage); return uint32(n); } /// @notice The standard EIP-20 transfer event event Transfer(address indexed from, address indexed to, uint amount); /// @notice The standard EIP-20 approval event event Approval(address indexed owner, address indexed spender, uint amount); /// @notice Submit a job event SubmitJob(address indexed job, address indexed provider, uint block, uint credit); /// @notice Apply credit to a job event ApplyCredit(address indexed job, address indexed provider, uint block, uint credit); /// @notice Remove credit for a job event RemoveJob(address indexed job, address indexed provider, uint block, uint credit); /// @notice Unbond credit for a job event UnbondJob(address indexed job, address indexed provider, uint block, uint credit); /// @notice Added a Job event JobAdded(address indexed job, uint block, address governance); /// @notice Removed a job event JobRemoved(address indexed job, uint block, address governance); /// @notice Worked a job event KeeperWorked(address indexed job, address indexed keeper, uint block); /// @notice Keeper bonding event KeeperBonding(address indexed keeper, uint block, uint active, uint bond); /// @notice Keeper bonded event KeeperBonded(address indexed keeper, uint block, uint activated, uint bond); /// @notice Keeper unbonding event KeeperUnbonding(address indexed keeper, uint block, uint deactive, uint bond); /// @notice Keeper unbound event KeeperUnbound(address indexed keeper, uint block, uint deactivated, uint bond); /// @notice Keeper slashed event KeeperSlashed(address indexed keeper, address indexed slasher, uint block, uint slash); /// @notice Keeper disputed event KeeperDispute(address indexed keeper, uint block); /// @notice Keeper resolved event KeeperResolved(address indexed keeper, uint block); /// @notice 1 day to bond to become a keeper uint constant public BOND = 3 days; /// @notice 14 days to unbond to remove funds from being a keeper uint constant public UNBOND = 14 days; /// @notice 7 days maximum downtime before being slashed uint constant public DOWNTIME = 7 days; /// @notice 3 days till liquidity can be bound uint constant public LIQUIDITYBOND = 3 days; /// @notice 5% of funds slashed for downtime uint constant public DOWNTIMESLASH = 500; uint constant public BASE = 10000; /// @notice tracks all current bondings (time) mapping(address => uint) public bondings; /// @notice tracks all current unbondings (time) mapping(address => uint) public unbondings; /// @notice allows for partial unbonding mapping(address => uint) public partialUnbonding; /// @notice tracks all current pending bonds (amount) mapping(address => uint) public pendingbonds; /// @notice tracks how much a keeper has bonded mapping(address => uint) public bonds; /// @notice total bonded (totalSupply for bonds) uint public totalBonded = 0; /// @notice tracks when a keeper was first registered mapping(address => uint) public firstSeen; /// @notice tracks if a keeper has a pending dispute mapping(address => bool) public disputes; /// @notice tracks last job performed for a keeper mapping(address => uint) public lastJob; /// @notice tracks the amount of job executions for a keeper mapping(address => uint) public work; /// @notice tracks the total job executions for a keeper mapping(address => uint) public workCompleted; /// @notice list of all jobs registered for the keeper system mapping(address => bool) public jobs; /// @notice the current credit available for a job mapping(address => uint) public credits; /// @notice the balances for the liquidity providers mapping(address => mapping(address => mapping(address => uint))) public liquidityProvided; /// @notice liquidity unbonding days mapping(address => mapping(address => mapping(address => uint))) public liquidityUnbonding; /// @notice liquidity unbonding amounts mapping(address => mapping(address => mapping(address => uint))) public liquidityAmountsUnbonding; /// @notice job proposal delay mapping(address => uint) public jobProposalDelay; /// @notice liquidity apply date mapping(address => mapping(address => mapping(address => uint))) public liquidityApplied; /// @notice liquidity amount to apply mapping(address => mapping(address => mapping(address => uint))) public liquidityAmount; /// @notice list of all current keepers mapping(address => bool) public keepers; /// @notice blacklist of keepers not allowed to participate mapping(address => bool) public blacklist; /// @notice traversable array of keepers to make external management easier address[] public keeperList; /// @notice traversable array of jobs to make external management easier address[] public jobList; /// @notice governance address for the governance contract address public governance; address public pendingGovernance; /// @notice the liquidity token supplied by users paying for jobs mapping(address => bool) public liquidityAccepted; address[] public liquidityPairs; uint internal gasUsed; constructor() public { // Set governance for this token governance = msg.sender; _mint(msg.sender, 10000e18); } /** * @notice Approve a liquidity pair for being accepted in future * @param liquidity the liquidity no longer accepted */ function approveLiquidity(address liquidity) external { require(msg.sender == governance, "Keep3r::approveLiquidity: governance only"); require(!liquidityAccepted[liquidity], "Keep3r::approveLiquidity: existing liquidity pair"); liquidityAccepted[liquidity] = true; liquidityPairs.push(liquidity); } /** * @notice Revoke a liquidity pair from being accepted in future * @param liquidity the liquidity no longer accepted */ function revokeLiquidity(address liquidity) external { require(msg.sender == governance, "Keep3r::revokeLiquidity: governance only"); liquidityAccepted[liquidity] = false; } /** * @notice Displays all accepted liquidity pairs */ function pairs() external view returns (address[] memory) { return liquidityPairs; } /** * @notice Allows liquidity providers to submit jobs * @param amount the amount of tokens to mint to treasury * @param job the job to assign credit to * @param amount the amount of liquidity tokens to use */ function addLiquidityToJob(address liquidity, address job, uint amount) external { require(liquidityAccepted[liquidity], "Keep3r::addLiquidityToJob: asset not accepted as liquidity"); UniswapPair(liquidity).transferFrom(msg.sender, address(this), amount); liquidityProvided[msg.sender][liquidity][job] = liquidityProvided[msg.sender][liquidity][job].add(amount); liquidityApplied[msg.sender][liquidity][job] = now.add(LIQUIDITYBOND); liquidityAmount[msg.sender][liquidity][job] = liquidityAmount[msg.sender][liquidity][job].add(amount); if (!jobs[job] && jobProposalDelay[job] < now) { Governance(governance).proposeJob(job); jobProposalDelay[job] = now.add(UNBOND); } emit SubmitJob(job, msg.sender, block.number, amount); } /** * @notice Applies the credit provided in addLiquidityToJob to the job * @param provider the liquidity provider * @param liquidity the pair being added as liquidity * @param job the job that is receiving the credit */ function applyCreditToJob(address provider, address liquidity, address job) external { require(liquidityAccepted[liquidity], "Keep3r::addLiquidityToJob: asset not accepted as liquidity"); require(liquidityApplied[provider][liquidity][job] != 0, "Keep3r::credit: submitJob first"); require(liquidityApplied[provider][liquidity][job] < now, "Keep3r::credit: still bonding"); uint _liquidity = balances[address(liquidity)]; uint _credit = _liquidity.mul(liquidityAmount[msg.sender][liquidity][job]).div(UniswapPair(liquidity).totalSupply()); credits[job] = credits[job].add(_credit); liquidityAmount[msg.sender][liquidity][job] = 0; emit ApplyCredit(job, msg.sender, block.number, _credit); } /** * @notice Unbond liquidity for a pending keeper job * @param liquidity the pair being unbound * @param job the job being unbound from * @param amount the amount of liquidity being removed */ function unbondLiquidityFromJob(address liquidity, address job, uint amount) external { require(liquidityAmount[msg.sender][liquidity][job] == 0, "Keep3r::credit: pending credit, settle first"); liquidityUnbonding[msg.sender][liquidity][job] = now.add(UNBOND); liquidityAmountsUnbonding[msg.sender][liquidity][job] = liquidityAmountsUnbonding[msg.sender][liquidity][job].add(amount); require(liquidityAmountsUnbonding[msg.sender][liquidity][job] <= liquidityProvided[msg.sender][liquidity][job], "Keep3r::unbondLiquidityFromJob: insufficient funds"); uint _liquidity = balances[address(liquidity)]; uint _credit = _liquidity.mul(amount).div(UniswapPair(liquidity).totalSupply()); if (_credit > credits[job]) { credits[job] = 0; } else { credits[job].sub(_credit); } emit UnbondJob(job, msg.sender, block.number, liquidityProvided[msg.sender][liquidity][job]); } /** * @notice Allows liquidity providers to remove liquidity * @param liquidity the pair being unbound * @param job the job being unbound from */ function removeLiquidityFromJob(address liquidity, address job) external { require(liquidityUnbonding[msg.sender][liquidity][job] != 0, "Keep3r::removeJob: unbond first"); require(liquidityUnbonding[msg.sender][liquidity][job] < now, "Keep3r::removeJob: still unbonding"); uint _amount = liquidityAmountsUnbonding[msg.sender][liquidity][job]; liquidityProvided[msg.sender][liquidity][job] = liquidityProvided[msg.sender][liquidity][job].sub(_amount); liquidityAmountsUnbonding[msg.sender][liquidity][job] = 0; UniswapPair(liquidity).transfer(msg.sender, _amount); emit RemoveJob(job, msg.sender, block.number, _amount); } /** * @notice Allows governance to mint new tokens to treasury * @param amount the amount of tokens to mint to treasury */ function mint(uint amount) external { require(msg.sender == governance, "Keep3r::mint: governance only"); _mint(governance, amount); } /** * @notice burn owned tokens * @param amount the amount of tokens to burn */ function burn(uint amount) external { _burn(msg.sender, amount); } function _mint(address dst, uint amount) internal { // mint the amount totalSupply = totalSupply.add(amount); // transfer the amount to the recipient balances[dst] = balances[dst].add(amount); emit Transfer(address(0), dst, amount); } function _burn(address dst, uint amount) internal { require(dst != address(0), "::_burn: burn from the zero address"); balances[dst] = balances[dst].sub(amount, "::_burn: burn amount exceeds balance"); totalSupply = totalSupply.sub(amount); emit Transfer(dst, address(0), amount); } /** * @notice Implemented by jobs to show that a keeper performend work * @param keeper address of the keeper that performed the work * @param amount the reward that should be allocated */ function workReceipt(address keeper, uint amount) external { require(jobs[msg.sender], "Keep3r::workReceipt: only jobs can approve work"); gasUsed = gasUsed.sub(gasleft()); require(amount < KPRH.getQuoteLimit(gasUsed), "Keep3r::workReceipt: spending over max limit"); credits[msg.sender] = credits[msg.sender].sub(amount, "Keep3r::workReceipt: insuffient funds to pay keeper"); lastJob[keeper] = now; _mint(address(this), amount); _bond(keeper, amount); workCompleted[keeper] = workCompleted[keeper].add(amount); emit KeeperWorked(msg.sender, keeper, block.number); } function _bond(address _from, uint _amount) internal { bonds[_from] = bonds[_from].add(_amount); totalBonded = totalBonded.add(_amount); _moveDelegates(address(0), delegates[_from], _amount); } function _unbond(address _from, uint _amount) internal { bonds[_from] = bonds[_from].sub(_amount); totalBonded = totalBonded.sub(_amount); _moveDelegates(delegates[_from], address(0), _amount); } /** * @notice Allows governance to add new job systems * @param job address of the contract for which work should be performed */ function addJob(address job) external { require(msg.sender == governance, "Keep3r::addJob: only governance can add jobs"); require(!jobs[job], "Keep3r::addJob: job already known"); jobs[job] = true; jobList.push(job); emit JobAdded(job, block.number, msg.sender); } /** * @notice Full listing of all jobs ever added * @return array blob */ function getJobs() external view returns (address[] memory) { return jobList; } /** * @notice Allows governance to remove a job from the systems * @param job address of the contract for which work should be performed */ function removeJob(address job) external { require(msg.sender == governance, "Keep3r::removeJob: only governance can remove jobs"); jobs[job] = false; emit JobRemoved(job, block.number, msg.sender); } /** * @notice Allows governance to change the Keep3rHelper for max spend * @param _kprh new helper address to set */ function setKeep3rHelper(Keep3rHelper _kprh) external { require(msg.sender == governance, "Keep3r::setKeep3rHelper: only governance can set"); KPRH = _kprh; } /** * @notice Allows governance to change governance (for future upgradability) * @param _governance new governance address to set */ function setGovernance(address _governance) external { require(msg.sender == governance, "Keep3r::setGovernance: only governance can set"); pendingGovernance = _governance; } /** * @notice Allows pendingGovernance to accept their role as governance (protection pattern) */ function acceptGovernance() external { require(msg.sender == pendingGovernance, "Keep3r::acceptGovernance: only pendingGovernance can accept"); governance = pendingGovernance; } /** * @notice confirms if the current keeper is registered, can be used for general (non critical) functions * @return true/false if the address is a keeper */ function isKeeper(address keeper) external returns (bool) { gasUsed = gasleft(); return keepers[keeper]; } /** * @notice confirms if the current keeper is registered and has a minimum bond, should be used for protected functions * @return true/false if the address is a keeper and has more than the bond */ function isMinKeeper(address keeper, uint minBond, uint earned, uint age) external returns (bool) { gasUsed = gasleft(); return keepers[keeper] && bonds[keeper] >= minBond && workCompleted[keeper] >= earned && now.sub(firstSeen[keeper]) >= age; } /** * @notice begin the bonding process for a new keeper */ function bond(uint amount) external { require(pendingbonds[msg.sender] == 0, "Keep3r::bond: current pending bond"); require(!blacklist[msg.sender], "Keep3r::bond: keeper is blacklisted"); bondings[msg.sender] = now.add(BOND); _transferTokens(msg.sender, address(this), amount); pendingbonds[msg.sender] = pendingbonds[msg.sender].add(amount); emit KeeperBonding(msg.sender, block.number, bondings[msg.sender], amount); } function getKeepers() external view returns (address[] memory) { return keeperList; } /** * @notice allows a keeper to activate/register themselves after bonding */ function activate() external { require(!blacklist[msg.sender], "Keep3r::activate: keeper is blacklisted"); require(bondings[msg.sender] != 0 && bondings[msg.sender] < now, "Keep3r::activate: still bonding"); if (firstSeen[msg.sender] == 0) { firstSeen[msg.sender] = now; keeperList.push(msg.sender); lastJob[msg.sender] = now; } keepers[msg.sender] = true; _bond(msg.sender, pendingbonds[msg.sender]); pendingbonds[msg.sender] = 0; emit KeeperBonded(msg.sender, block.number, block.timestamp, bonds[msg.sender]); } /** * @notice begin the unbonding process to stop being a keeper * @param amount allows for partial unbonding */ function unbond(uint amount) external { unbondings[msg.sender] = now.add(UNBOND); _unbond(msg.sender, amount); partialUnbonding[msg.sender] = partialUnbonding[msg.sender].add(amount); emit KeeperUnbonding(msg.sender, block.number, unbondings[msg.sender], amount); } /** * @notice withdraw funds after unbonding has finished */ function withdraw() external { require(unbondings[msg.sender] != 0 && unbondings[msg.sender] < now, "Keep3r::withdraw: still unbonding"); require(!disputes[msg.sender], "Keep3r::withdraw: pending disputes"); _transferTokens(address(this), msg.sender, partialUnbonding[msg.sender]); emit KeeperUnbound(msg.sender, block.number, block.timestamp, partialUnbonding[msg.sender]); partialUnbonding[msg.sender] = 0; } /** * @notice slash a keeper for downtime * @param keeper the address being slashed */ function down(address keeper) external { require(keepers[msg.sender], "Keep3r::down: not a keeper"); require(keepers[keeper], "Keep3r::down: keeper not registered"); require(lastJob[keeper].add(DOWNTIME) < now, "Keep3r::down: keeper safe"); uint _slash = bonds[keeper].mul(DOWNTIMESLASH).div(BASE); _unbond(keeper, _slash); _bond(msg.sender, _slash); lastJob[keeper] = now; lastJob[msg.sender] = now; emit KeeperSlashed(keeper, msg.sender, block.number, _slash); } /** * @notice allows governance to create a dispute for a given keeper * @param keeper the address in dispute */ function dispute(address keeper) external returns (uint) { require(msg.sender == governance, "Keep3r::dispute: only governance can dispute"); disputes[keeper] = true; emit KeeperDispute(keeper, block.number); } /** * @notice allows governance to slash a keeper based on a dispute * @param keeper the address being slashed * @param amount the amount being slashed */ function slash(address keeper, uint amount) public { require(msg.sender == governance, "Keep3r::slash: only governance can resolve"); _transferTokens(address(this), governance, amount); _unbond(keeper, amount); disputes[keeper] = false; emit KeeperSlashed(keeper, msg.sender, block.number, amount); } /** * @notice blacklists a keeper from participating in the network * @param keeper the address being slashed */ function revoke(address keeper) external { require(msg.sender == governance, "Keep3r::slash: only governance can resolve"); keepers[keeper] = false; blacklist[keeper] = true; slash(keeper, bonds[keeper]); } /** * @notice allows governance to resolve a dispute on a keeper * @param keeper the address cleared */ function resolve(address keeper) external { require(msg.sender == governance, "Keep3r::resolve: only governance can resolve"); disputes[keeper] = false; emit KeeperResolved(keeper, block.number); } /** * @notice Get the number of tokens `spender` is approved to spend on behalf of `account` * @param account The address of the account holding the funds * @param spender The address of the account spending the funds * @return The number of tokens approved */ function allowance(address account, address spender) external view returns (uint) { return allowances[account][spender]; } /** * @notice Approve `spender` to transfer up to `amount` from `src` * @dev This will overwrite the approval amount for `spender` * and is subject to issues noted [here](https://eips.ethereum.org/EIPS/eip-20#approve) * @param spender The address of the account which may transfer tokens * @param amount The number of tokens that are approved (2^256-1 means infinite) * @return Whether or not the approval succeeded */ function approve(address spender, uint amount) public returns (bool) { allowances[msg.sender][spender] = amount; emit Approval(msg.sender, spender, amount); return true; } /** * @notice Triggers an approval from owner to spends * @param owner The address to approve from * @param spender The address to be approved * @param amount The number of tokens that are approved (2^256-1 means infinite) * @param deadline 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 permit(address owner, address spender, uint amount, uint deadline, uint8 v, bytes32 r, bytes32 s) external { bytes32 domainSeparator = keccak256(abi.encode(DOMAIN_TYPEHASH, keccak256(bytes(name)), getChainId(), address(this))); bytes32 structHash = keccak256(abi.encode(PERMIT_TYPEHASH, owner, spender, amount, nonces[owner]++, deadline)); bytes32 digest = keccak256(abi.encodePacked("\x19\x01", domainSeparator, structHash)); address signatory = ecrecover(digest, v, r, s); require(signatory != address(0), "::permit: invalid signature"); require(signatory == owner, "::permit: unauthorized"); require(now <= deadline, "::permit: signature expired"); allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @notice Get the number of tokens held by the `account` * @param account The address of the account to get the balance of * @return The number of tokens held */ function balanceOf(address account) external view returns (uint) { return balances[account]; } /** * @notice Transfer `amount` tokens from `msg.sender` to `dst` * @param dst The address of the destination account * @param amount The number of tokens to transfer * @return Whether or not the transfer succeeded */ function transfer(address dst, uint amount) public returns (bool) { _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 amount The number of tokens to transfer * @return Whether or not the transfer succeeded */ function transferFrom(address src, address dst, uint amount) external returns (bool) { address spender = msg.sender; uint spenderAllowance = allowances[src][spender]; if (spender != src && spenderAllowance != uint(-1)) { uint newAllowance = spenderAllowance.sub(amount, "::transferFrom: transfer amount exceeds spender allowance"); allowances[src][spender] = newAllowance; emit Approval(src, spender, newAllowance); } _transferTokens(src, dst, amount); return true; } function _transferTokens(address src, address dst, uint amount) internal { require(src != address(0), "::_transferTokens: cannot transfer from the zero address"); require(dst != address(0), "::_transferTokens: cannot transfer to the zero address"); balances[src] = balances[src].sub(amount, "::_transferTokens: transfer amount exceeds balance"); balances[dst] = balances[dst].add(amount, "::_transferTokens: transfer amount overflows"); emit Transfer(src, dst, amount); } function getChainId() internal pure returns (uint) { uint chainId; assembly { chainId := chainid() } return chainId; } }
Unbond liquidity for a pending keeper job liquidity the pair being unbound job the job being unbound from amount the amount of liquidity being removed/
function unbondLiquidityFromJob(address liquidity, address job, uint amount) external { require(liquidityAmount[msg.sender][liquidity][job] == 0, "Keep3r::credit: pending credit, settle first"); liquidityUnbonding[msg.sender][liquidity][job] = now.add(UNBOND); liquidityAmountsUnbonding[msg.sender][liquidity][job] = liquidityAmountsUnbonding[msg.sender][liquidity][job].add(amount); require(liquidityAmountsUnbonding[msg.sender][liquidity][job] <= liquidityProvided[msg.sender][liquidity][job], "Keep3r::unbondLiquidityFromJob: insufficient funds"); uint _liquidity = balances[address(liquidity)]; uint _credit = _liquidity.mul(amount).div(UniswapPair(liquidity).totalSupply()); if (_credit > credits[job]) { credits[job] = 0; credits[job].sub(_credit); } emit UnbondJob(job, msg.sender, block.number, liquidityProvided[msg.sender][liquidity][job]); }
603,480
/** *Submitted for verification at Etherscan.io on 2021-10-08 */ /** *Submitted for verification at Etherscan.io on 2020-05-26 */ pragma solidity ^0.4.24; // <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. */ contract OraclizeI { address public cbAddress; function query(uint _timestamp, string _datasource, string _arg) payable returns (bytes32 _id); function query_withGasLimit(uint _timestamp, string _datasource, string _arg, uint _gaslimit) payable returns (bytes32 _id); function query2(uint _timestamp, string _datasource, string _arg1, string _arg2) payable returns (bytes32 _id); function query2_withGasLimit(uint _timestamp, string _datasource, string _arg1, string _arg2, uint _gaslimit) payable returns (bytes32 _id); function queryN(uint _timestamp, string _datasource, bytes _argN) payable returns (bytes32 _id); function queryN_withGasLimit(uint _timestamp, string _datasource, bytes _argN, uint _gaslimit) payable returns (bytes32 _id); function getPrice(string _datasource) returns (uint _dsprice); function getPrice(string _datasource, uint gaslimit) returns (uint _dsprice); function useCoupon(string _coupon); function setProofType(byte _proofType); function setConfig(bytes32 _config); function setCustomGasPrice(uint _gasPrice); function randomDS_getSessionPubKeyHash() returns(bytes32); } contract OraclizeAddrResolverI { function getAddress() returns (address _addr); } 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()); oraclize.useCoupon(code); _; } function oraclize_setNetwork(uint8 networkID) 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) { __callback(myid, result, new bytes(0)); } function __callback(bytes32 myid, string result, bytes proof) { } function oraclize_useCoupon(string code) oraclizeAPI internal { oraclize.useCoupon(code); } 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_setConfig(bytes32 config) oraclizeAPI internal { return oraclize.setConfig(config); } function oraclize_randomDS_getSessionPubKeyHash() oraclizeAPI internal returns (bytes32){ return oraclize.randomDS_getSessionPubKeyHash(); } function getCodeSize(address _addr) constant internal returns(uint _size) { assembly { _size := extcodesize(_addr) } } function parseAddr(string _a) internal 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 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 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 returns (string) { bytes memory _ba = bytes(_a); bytes memory _bb = bytes(_b); bytes memory _bc = bytes(_c); bytes memory _bd = bytes(_d); bytes memory _be = bytes(_e); string memory abcde = new string(_ba.length + _bb.length + _bc.length + _bd.length + _be.length); bytes memory babcde = bytes(abcde); uint k = 0; for (uint i = 0; i < _ba.length; i++) babcde[k++] = _ba[i]; for (i = 0; i < _bb.length; i++) babcde[k++] = _bb[i]; for (i = 0; i < _bc.length; i++) babcde[k++] = _bc[i]; for (i = 0; i < _bd.length; i++) babcde[k++] = _bd[i]; for (i = 0; i < _be.length; i++) babcde[k++] = _be[i]; return string(babcde); } function strConcat(string _a, string _b, string _c, string _d) internal returns (string) { return strConcat(_a, _b, _c, _d, ""); } function strConcat(string _a, string _b, string _c) internal returns (string) { return strConcat(_a, _b, _c, "", ""); } function strConcat(string _a, string _b) internal returns (string) { return strConcat(_a, _b, "", "", ""); } // parseInt function parseInt(string _a) internal returns (uint) { return parseInt(_a, 0); } // parseInt(parseFloat*10^_b) function parseInt(string _a, uint _b) internal 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 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); } function stra2cbor(string[] arr) internal returns (bytes) { uint arrlen = arr.length; // get correct cbor output length uint outputlen = 0; bytes[] memory elemArray = new bytes[](arrlen); for (uint i = 0; i < arrlen; i++) { elemArray[i] = (bytes(arr[i])); outputlen += elemArray[i].length + (elemArray[i].length - 1)/23 + 3; //+3 accounts for paired identifier types } uint ctr = 0; uint cborlen = arrlen + 0x80; outputlen += byte(cborlen).length; bytes memory res = new bytes(outputlen); while (byte(cborlen).length > ctr) { res[ctr] = byte(cborlen)[ctr]; ctr++; } for (i = 0; i < arrlen; i++) { res[ctr] = 0x5F; ctr++; for (uint x = 0; x < elemArray[i].length; x++) { // if there's a bug with larger strings, this may be the culprit if (x % 23 == 0) { uint elemcborlen = elemArray[i].length - x >= 24 ? 23 : elemArray[i].length - x; elemcborlen += 0x40; uint lctr = ctr; while (byte(elemcborlen).length > ctr - lctr) { res[ctr] = byte(elemcborlen)[ctr - lctr]; ctr++; } } res[ctr] = elemArray[i][x]; ctr++; } res[ctr] = 0xFF; ctr++; } return res; } function ba2cbor(bytes[] arr) internal returns (bytes) { uint arrlen = arr.length; // get correct cbor output length uint outputlen = 0; bytes[] memory elemArray = new bytes[](arrlen); for (uint i = 0; i < arrlen; i++) { elemArray[i] = (bytes(arr[i])); outputlen += elemArray[i].length + (elemArray[i].length - 1)/23 + 3; //+3 accounts for paired identifier types } uint ctr = 0; uint cborlen = arrlen + 0x80; outputlen += byte(cborlen).length; bytes memory res = new bytes(outputlen); while (byte(cborlen).length > ctr) { res[ctr] = byte(cborlen)[ctr]; ctr++; } for (i = 0; i < arrlen; i++) { res[ctr] = 0x5F; ctr++; for (uint x = 0; x < elemArray[i].length; x++) { // if there's a bug with larger strings, this may be the culprit if (x % 23 == 0) { uint elemcborlen = elemArray[i].length - x >= 24 ? 23 : elemArray[i].length - x; elemcborlen += 0x40; uint lctr = ctr; while (byte(elemcborlen).length > ctr - lctr) { res[ctr] = byte(elemcborlen)[ctr - lctr]; ctr++; } } res[ctr] = elemArray[i][x]; ctr++; } res[ctr] = 0xFF; ctr++; } return res; } string oraclize_network_name; function oraclize_setNetworkName(string _network_name) internal { oraclize_network_name = _network_name; } function oraclize_getNetworkName() internal returns (string) { return oraclize_network_name; } function oraclize_newRandomDSQuery(uint _delay, uint _nbytes, uint _customGasLimit) internal returns (bytes32){ if ((_nbytes == 0)||(_nbytes > 32)) throw; 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) mstore(add(unonce, 0x20), xor(blockhash(sub(number, 1)), xor(coinbase, timestamp))) mstore(sessionKeyHash, 0x20) mstore(add(sessionKeyHash, 0x20), sessionKeyHash_bytes32) } bytes[3] memory args = [unonce, nbytes, sessionKeyHash]; bytes32 queryId = oraclize_query(_delay, "random", args, _customGasLimit); oraclize_randomDS_setCommitment(queryId, sha3(bytes8(_delay), 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(sha3(pubkey)) == signer) return true; else { (sigok, signer) = safer_ecrecover(tosignh, 28, sigr, sigs); return (address(sha3(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] = 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) if ((_proof[0] != "L")||(_proof[1] != "P")||(_proof[2] != 1)) throw; bool proofVerified = oraclize_randomDS_proofVerify__main(_proof, _queryId, bytes(_result), oraclize_getNetworkName()); if (proofVerified == false) throw; _; } 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) internal returns (bool){ bool match_ = true; for (var i=0; i<prefix.length; 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){ bool checkok; // Step 2: the unique keyhash has to match with the sha256 of (context name + queryId) uint ledgerProofLength = 3+65+(uint(proof[3+65+1])+2)+32; bytes memory keyhash = new bytes(32); copyBytes(proof, ledgerProofLength, 32, keyhash, 0); checkok = (sha3(keyhash) == sha3(sha256(context_name, queryId))); if (checkok == false) return false; bytes memory sig1 = new bytes(uint(proof[ledgerProofLength+(32+8+1+32)+1])+2); copyBytes(proof, ledgerProofLength+(32+8+1+32), sig1.length, sig1, 0); // Step 3: we assume sig1 is valid (it will be verified during step 5) and we verify if 'result' is the prefix of sha256(sig1) checkok = matchBytes32Prefix(sha256(sig1), result); if (checkok == false) return false; // Step 4: commitment match verification, sha3(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] == sha3(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); checkok = verifySig(sha256(tosign1), sig1, sessionPubkey); if (checkok == false) 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 returns (bytes) { uint minLength = length + toOffset; if (to.length < minLength) { // Buffer too small throw; // 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> /* * @title String & slice utility library for Solidity contracts. * @author Nick Johnson <[email protected]> * * @dev Functionality in this library is largely implemented using an * abstraction called a 'slice'. A slice represents a part of a string - * anything from the entire string to a single character, or even no * characters at all (a 0-length slice). Since a slice only has to specify * an offset and a length, copying and manipulating slices is a lot less * expensive than copying and manipulating the strings they reference. * * To further reduce gas costs, most functions on slice that need to return * a slice modify the original one instead of allocating a new one; for * instance, `s.split(".")` will return the text up to the first '.', * modifying s to only contain the remainder of the string after the '.'. * In situations where you do not want to modify the original slice, you * can make a copy first with `.copy()`, for example: * `s.copy().split(".")`. Try and avoid using this idiom in loops; since * Solidity has no memory management, it will result in allocating many * short-lived slices that are later discarded. * * Functions that return two slices come in two versions: a non-allocating * version that takes the second slice as an argument, modifying it in * place, and an allocating version that allocates and returns the second * slice; see `nextRune` for example. * * Functions that have to copy string data will return strings rather than * slices; these can be cast back to slices for further processing if * required. * * For convenience, some functions are provided with non-modifying * variants that create a new slice and return both; for instance, * `s.splitNew('.')` leaves s unmodified, and returns two values * corresponding to the left and right parts of the string. */ library strings { struct slice { uint _len; uint _ptr; } function memcpy(uint dest, uint src, uint len) private { // 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)) } } /* * @dev Returns a slice containing the entire string. * @param self The string to make a slice from. * @return A newly allocated slice containing the entire string. */ function toSlice(string self) internal returns (slice) { uint ptr; assembly { ptr := add(self, 0x20) } return slice(bytes(self).length, ptr); } /* * @dev Returns the length of a null-terminated bytes32 string. * @param self The value to find the length of. * @return The length of the string, from 0 to 32. */ function len(bytes32 self) internal returns (uint) { uint ret; if (self == 0) return 0; if (self & 0xffffffffffffffffffffffffffffffff == 0) { ret += 16; self = bytes32(uint(self) / 0x100000000000000000000000000000000); } if (self & 0xffffffffffffffff == 0) { ret += 8; self = bytes32(uint(self) / 0x10000000000000000); } if (self & 0xffffffff == 0) { ret += 4; self = bytes32(uint(self) / 0x100000000); } if (self & 0xffff == 0) { ret += 2; self = bytes32(uint(self) / 0x10000); } if (self & 0xff == 0) { ret += 1; } return 32 - ret; } /* * @dev Returns a slice containing the entire bytes32, interpreted as a * null-termintaed utf-8 string. * @param self The bytes32 value to convert to a slice. * @return A new slice containing the value of the input argument up to the * first null. */ function toSliceB32(bytes32 self) internal returns (slice ret) { // Allocate space for `self` in memory, copy it there, and point ret at it assembly { let ptr := mload(0x40) mstore(0x40, add(ptr, 0x20)) mstore(ptr, self) mstore(add(ret, 0x20), ptr) } ret._len = len(self); } /* * @dev Returns a new slice containing the same data as the current slice. * @param self The slice to copy. * @return A new slice containing the same data as `self`. */ function copy(slice self) internal returns (slice) { return slice(self._len, self._ptr); } /* * @dev Copies a slice to a new string. * @param self The slice to copy. * @return A newly allocated string containing the slice's text. */ function toString(slice self) internal returns (string) { var ret = new string(self._len); uint retptr; assembly { retptr := add(ret, 32) } memcpy(retptr, self._ptr, self._len); return ret; } /* * @dev Returns the length in runes of the slice. Note that this operation * takes time proportional to the length of the slice; avoid using it * in loops, and call `slice.empty()` if you only need to know whether * the slice is empty or not. * @param self The slice to operate on. * @return The length of the slice in runes. */ function len(slice self) internal returns (uint) { // Starting at ptr-31 means the LSB will be the byte we care about var ptr = self._ptr - 31; var end = ptr + self._len; for (uint len = 0; ptr < end; len++) { uint8 b; assembly { b := and(mload(ptr), 0xFF) } if (b < 0x80) { ptr += 1; } else if(b < 0xE0) { ptr += 2; } else if(b < 0xF0) { ptr += 3; } else if(b < 0xF8) { ptr += 4; } else if(b < 0xFC) { ptr += 5; } else { ptr += 6; } } return len; } /* * @dev Returns true if the slice is empty (has a length of 0). * @param self The slice to operate on. * @return True if the slice is empty, False otherwise. */ function empty(slice self) internal returns (bool) { return self._len == 0; } /* * @dev Returns a positive number if `other` comes lexicographically after * `self`, a negative number if it comes before, or zero if the * contents of the two slices are equal. Comparison is done per-rune, * on unicode codepoints. * @param self The first slice to compare. * @param other The second slice to compare. * @return The result of the comparison. */ function compare(slice self, slice other) internal returns (int) { uint shortest = self._len; if (other._len < self._len) shortest = other._len; var selfptr = self._ptr; var otherptr = other._ptr; for (uint idx = 0; idx < shortest; idx += 32) { uint a; uint b; assembly { a := mload(selfptr) b := mload(otherptr) } if (a != b) { // Mask out irrelevant bytes and check again uint mask = ~(2 ** (8 * (32 - shortest + idx)) - 1); var diff = (a & mask) - (b & mask); if (diff != 0) return int(diff); } selfptr += 32; otherptr += 32; } return int(self._len) - int(other._len); } /* * @dev Returns true if the two slices contain the same text. * @param self The first slice to compare. * @param self The second slice to compare. * @return True if the slices are equal, false otherwise. */ function equals(slice self, slice other) internal returns (bool) { return compare(self, other) == 0; } /* * @dev Extracts the first rune in the slice into `rune`, advancing the * slice to point to the next rune and returning `self`. * @param self The slice to operate on. * @param rune The slice that will contain the first rune. * @return `rune`. */ function nextRune(slice self, slice rune) internal returns (slice) { rune._ptr = self._ptr; if (self._len == 0) { rune._len = 0; return rune; } uint len; uint b; // Load the first byte of the rune into the LSBs of b assembly { b := and(mload(sub(mload(add(self, 32)), 31)), 0xFF) } if (b < 0x80) { len = 1; } else if(b < 0xE0) { len = 2; } else if(b < 0xF0) { len = 3; } else { len = 4; } // Check for truncated codepoints if (len > self._len) { rune._len = self._len; self._ptr += self._len; self._len = 0; return rune; } self._ptr += len; self._len -= len; rune._len = len; return rune; } /* * @dev Returns the first rune in the slice, advancing the slice to point * to the next rune. * @param self The slice to operate on. * @return A slice containing only the first rune from `self`. */ function nextRune(slice self) internal returns (slice ret) { nextRune(self, ret); } /* * @dev Returns the number of the first codepoint in the slice. * @param self The slice to operate on. * @return The number of the first codepoint in the slice. */ function ord(slice self) internal returns (uint ret) { if (self._len == 0) { return 0; } uint word; uint len; uint div = 2 ** 248; // Load the rune into the MSBs of b assembly { word:= mload(mload(add(self, 32))) } var b = word / div; if (b < 0x80) { ret = b; len = 1; } else if(b < 0xE0) { ret = b & 0x1F; len = 2; } else if(b < 0xF0) { ret = b & 0x0F; len = 3; } else { ret = b & 0x07; len = 4; } // Check for truncated codepoints if (len > self._len) { return 0; } for (uint i = 1; i < len; i++) { div = div / 256; b = (word / div) & 0xFF; if (b & 0xC0 != 0x80) { // Invalid UTF-8 sequence return 0; } ret = (ret * 64) | (b & 0x3F); } return ret; } /* * @dev Returns the keccak-256 hash of the slice. * @param self The slice to hash. * @return The hash of the slice. */ function keccak(slice self) internal returns (bytes32 ret) { assembly { ret := sha3(mload(add(self, 32)), mload(self)) } } /* * @dev Returns true if `self` starts with `needle`. * @param self The slice to operate on. * @param needle The slice to search for. * @return True if the slice starts with the provided text, false otherwise. */ function startsWith(slice self, slice needle) internal returns (bool) { if (self._len < needle._len) { return false; } if (self._ptr == needle._ptr) { return true; } bool equal; assembly { let len := mload(needle) let selfptr := mload(add(self, 0x20)) let needleptr := mload(add(needle, 0x20)) equal := eq(sha3(selfptr, len), sha3(needleptr, len)) } return equal; } /* * @dev If `self` starts with `needle`, `needle` is removed from the * beginning of `self`. Otherwise, `self` is unmodified. * @param self The slice to operate on. * @param needle The slice to search for. * @return `self` */ function beyond(slice self, slice needle) internal returns (slice) { if (self._len < needle._len) { return self; } bool equal = true; if (self._ptr != needle._ptr) { assembly { let len := mload(needle) let selfptr := mload(add(self, 0x20)) let needleptr := mload(add(needle, 0x20)) equal := eq(sha3(selfptr, len), sha3(needleptr, len)) } } if (equal) { self._len -= needle._len; self._ptr += needle._len; } return self; } /* * @dev Returns true if the slice ends with `needle`. * @param self The slice to operate on. * @param needle The slice to search for. * @return True if the slice starts with the provided text, false otherwise. */ function endsWith(slice self, slice needle) internal returns (bool) { if (self._len < needle._len) { return false; } var selfptr = self._ptr + self._len - needle._len; if (selfptr == needle._ptr) { return true; } bool equal; assembly { let len := mload(needle) let needleptr := mload(add(needle, 0x20)) equal := eq(sha3(selfptr, len), sha3(needleptr, len)) } return equal; } /* * @dev If `self` ends with `needle`, `needle` is removed from the * end of `self`. Otherwise, `self` is unmodified. * @param self The slice to operate on. * @param needle The slice to search for. * @return `self` */ function until(slice self, slice needle) internal returns (slice) { if (self._len < needle._len) { return self; } var selfptr = self._ptr + self._len - needle._len; bool equal = true; if (selfptr != needle._ptr) { assembly { let len := mload(needle) let needleptr := mload(add(needle, 0x20)) equal := eq(sha3(selfptr, len), sha3(needleptr, len)) } } if (equal) { self._len -= needle._len; } return self; } // Returns the memory address of the first byte of the first occurrence of // `needle` in `self`, or the first byte after `self` if not found. function findPtr(uint selflen, uint selfptr, uint needlelen, uint needleptr) private returns (uint) { uint ptr; uint idx; if (needlelen <= selflen) { if (needlelen <= 32) { // Optimized assembly for 68 gas per byte on short strings assembly { let mask := not(sub(exp(2, mul(8, sub(32, needlelen))), 1)) let needledata := and(mload(needleptr), mask) let end := add(selfptr, sub(selflen, needlelen)) ptr := selfptr loop: jumpi(exit, eq(and(mload(ptr), mask), needledata)) ptr := add(ptr, 1) jumpi(loop, lt(sub(ptr, 1), end)) ptr := add(selfptr, selflen) exit: } return ptr; } else { // For long needles, use hashing bytes32 hash; assembly { hash := sha3(needleptr, needlelen) } ptr = selfptr; for (idx = 0; idx <= selflen - needlelen; idx++) { bytes32 testHash; assembly { testHash := sha3(ptr, needlelen) } if (hash == testHash) return ptr; ptr += 1; } } } return selfptr + selflen; } // Returns the memory address of the first byte after the last occurrence of // `needle` in `self`, or the address of `self` if not found. function rfindPtr(uint selflen, uint selfptr, uint needlelen, uint needleptr) private returns (uint) { uint ptr; if (needlelen <= selflen) { if (needlelen <= 32) { // Optimized assembly for 69 gas per byte on short strings assembly { let mask := not(sub(exp(2, mul(8, sub(32, needlelen))), 1)) let needledata := and(mload(needleptr), mask) ptr := add(selfptr, sub(selflen, needlelen)) loop: jumpi(ret, eq(and(mload(ptr), mask), needledata)) ptr := sub(ptr, 1) jumpi(loop, gt(add(ptr, 1), selfptr)) ptr := selfptr jump(exit) ret: ptr := add(ptr, needlelen) exit: } return ptr; } else { // For long needles, use hashing bytes32 hash; assembly { hash := sha3(needleptr, needlelen) } ptr = selfptr + (selflen - needlelen); while (ptr >= selfptr) { bytes32 testHash; assembly { testHash := sha3(ptr, needlelen) } if (hash == testHash) return ptr + needlelen; ptr -= 1; } } } return selfptr; } /* * @dev Modifies `self` to contain everything from the first occurrence of * `needle` to the end of the slice. `self` is set to the empty slice * if `needle` is not found. * @param self The slice to search and modify. * @param needle The text to search for. * @return `self`. */ function find(slice self, slice needle) internal returns (slice) { uint ptr = findPtr(self._len, self._ptr, needle._len, needle._ptr); self._len -= ptr - self._ptr; self._ptr = ptr; return self; } /* * @dev Modifies `self` to contain the part of the string from the start of * `self` to the end of the first occurrence of `needle`. If `needle` * is not found, `self` is set to the empty slice. * @param self The slice to search and modify. * @param needle The text to search for. * @return `self`. */ function rfind(slice self, slice needle) internal returns (slice) { uint ptr = rfindPtr(self._len, self._ptr, needle._len, needle._ptr); self._len = ptr - self._ptr; return self; } /* * @dev Splits the slice, setting `self` to everything after the first * occurrence of `needle`, and `token` to everything before it. If * `needle` does not occur in `self`, `self` is set to the empty slice, * and `token` is set to the entirety of `self`. * @param self The slice to split. * @param needle The text to search for in `self`. * @param token An output parameter to which the first token is written. * @return `token`. */ function split(slice self, slice needle, slice token) internal returns (slice) { uint ptr = findPtr(self._len, self._ptr, needle._len, needle._ptr); token._ptr = self._ptr; token._len = ptr - self._ptr; if (ptr == self._ptr + self._len) { // Not found self._len = 0; } else { self._len -= token._len + needle._len; self._ptr = ptr + needle._len; } return token; } /* * @dev Splits the slice, setting `self` to everything after the first * occurrence of `needle`, and returning everything before it. If * `needle` does not occur in `self`, `self` is set to the empty slice, * and the entirety of `self` is returned. * @param self The slice to split. * @param needle The text to search for in `self`. * @return The part of `self` up to the first occurrence of `delim`. */ function split(slice self, slice needle) internal returns (slice token) { split(self, needle, token); } /* * @dev Splits the slice, setting `self` to everything before the last * occurrence of `needle`, and `token` to everything after it. If * `needle` does not occur in `self`, `self` is set to the empty slice, * and `token` is set to the entirety of `self`. * @param self The slice to split. * @param needle The text to search for in `self`. * @param token An output parameter to which the first token is written. * @return `token`. */ function rsplit(slice self, slice needle, slice token) internal returns (slice) { uint ptr = rfindPtr(self._len, self._ptr, needle._len, needle._ptr); token._ptr = ptr; token._len = self._len - (ptr - self._ptr); if (ptr == self._ptr) { // Not found self._len = 0; } else { self._len -= token._len + needle._len; } return token; } /* * @dev Splits the slice, setting `self` to everything before the last * occurrence of `needle`, and returning everything after it. If * `needle` does not occur in `self`, `self` is set to the empty slice, * and the entirety of `self` is returned. * @param self The slice to split. * @param needle The text to search for in `self`. * @return The part of `self` after the last occurrence of `delim`. */ function rsplit(slice self, slice needle) internal returns (slice token) { rsplit(self, needle, token); } /* * @dev Counts the number of nonoverlapping occurrences of `needle` in `self`. * @param self The slice to search. * @param needle The text to search for in `self`. * @return The number of occurrences of `needle` found in `self`. */ function count(slice self, slice needle) internal returns (uint count) { uint ptr = findPtr(self._len, self._ptr, needle._len, needle._ptr) + needle._len; while (ptr <= self._ptr + self._len) { count++; ptr = findPtr(self._len - (ptr - self._ptr), ptr, needle._len, needle._ptr) + needle._len; } } /* * @dev Returns True if `self` contains `needle`. * @param self The slice to search. * @param needle The text to search for in `self`. * @return True if `needle` is found in `self`, false otherwise. */ function contains(slice self, slice needle) internal returns (bool) { return rfindPtr(self._len, self._ptr, needle._len, needle._ptr) != self._ptr; } /* * @dev Returns a newly allocated string containing the concatenation of * `self` and `other`. * @param self The first slice to concatenate. * @param other The second slice to concatenate. * @return The concatenation of the two strings. */ function concat(slice self, slice other) internal returns (string) { var ret = new string(self._len + other._len); uint retptr; assembly { retptr := add(ret, 32) } memcpy(retptr, self._ptr, self._len); memcpy(retptr + self._len, other._ptr, other._len); return ret; } /* * @dev Joins an array of slices, using `self` as a delimiter, returning a * newly allocated string. * @param self The delimiter to use. * @param parts A list of slices to join. * @return A newly allocated string containing all the slices in `parts`, * joined with `self`. */ function join(slice self, slice[] parts) internal returns (string) { if (parts.length == 0) return ""; uint len = self._len * (parts.length - 1); for(uint i = 0; i < parts.length; i++) len += parts[i]._len; var ret = new string(len); uint retptr; assembly { retptr := add(ret, 32) } for(i = 0; i < parts.length; i++) { memcpy(retptr, parts[i]._ptr, parts[i]._len); retptr += parts[i]._len; if (i < parts.length - 1) { memcpy(retptr, self._ptr, self._len); retptr += self._len; } } return ret; } } contract DSSafeAddSub { function safeToAdd(uint a, uint b) internal returns (bool) { return (a + b >= a); } function safeAdd(uint a, uint b) internal returns (uint) { if (!safeToAdd(a, b)) throw; return a + b; } function safeToSubtract(uint a, uint b) internal returns (bool) { return (b <= a); } function safeSub(uint a, uint b) internal returns (uint) { if (!safeToSubtract(a, b)) throw; return a - b; } } contract Etheroll is usingOraclize, DSSafeAddSub { using strings for *; /* * checks player profit, bet size and player number is within range */ modifier betIsValid(uint _betSize, uint _playerNumber) { if(((((_betSize * (100-(safeSub(_playerNumber,1)))) / (safeSub(_playerNumber,1))+_betSize))*houseEdge/houseEdgeDivisor)-_betSize > maxProfit || _betSize < minBet || _playerNumber < minNumber || _playerNumber > maxNumber) throw; _; } /* * checks game is currently active */ modifier gameIsActive { if(gamePaused == true) throw; _; } /* * checks payouts are currently active */ modifier payoutsAreActive { if(payoutsPaused == true) throw; _; } /* * checks only Oraclize address is calling */ modifier onlyOraclize { if (msg.sender != oraclize_cbAddress()) throw; _; } /* * checks only owner address is calling */ modifier onlyOwner { if (msg.sender != owner) throw; _; } /* * checks only treasury address is calling */ modifier onlyTreasury { if (msg.sender != treasury) throw; _; } /* * game vars */ uint constant public maxProfitDivisor = 1000000; uint constant public houseEdgeDivisor = 1000; uint constant public maxNumber = 99; uint constant public minNumber = 2; bool public gamePaused; uint32 public gasForOraclize; address public owner; bool public payoutsPaused; address public treasury; uint public contractBalance; uint public houseEdge; uint public maxProfit; uint public maxProfitAsPercentOfHouse; uint public minBet; uint public totalBets = 749047; uint public maxPendingPayouts; uint public totalWeiWon = 362757632550582691579193; uint public totalWeiWagered = 873210001157519117574271; uint private randomQueryID = 0; /* * player vars */ mapping (bytes32 => address) playerAddress; mapping (bytes32 => address) playerTempAddress; mapping (bytes32 => bytes32) playerBetId; mapping (bytes32 => uint) playerBetValue; mapping (bytes32 => uint) playerTempBetValue; mapping (bytes32 => uint) playerDieResult; mapping (bytes32 => uint) playerNumber; mapping (address => uint) playerPendingWithdrawals; mapping (bytes32 => uint) playerProfit; mapping (bytes32 => uint) playerTempReward; mapping (bytes32 => bytes32) playerIdentityRequest; /* * oracle query builder */ string constant private queryString1 = "[identity] "; string constant private queryString2 = " ${[URL] ['json(https://api.random.org/json-rpc/1/invoke).result.random[\"serialNumber\",\"data\"]', '\\n{\"jsonrpc\":\"2.0\",\"method\":\"generateSignedIntegers\",\"params\":{\"apiKey\":${[decrypt] BHPtlnzIqWuK1tooGTlPu+Zjer6uMHufHK644OLypzSF+xafckDq/TDErBxKMCCbsSYJQhX5nb6sWkP5oWbTqOn4DFfIgBIRa+5Fq5DsBsKo3AJCgXIXb4QsG2rhxJad4+VLnoxNDEaiR/M5qDAAyIiuWd3Tcbg=},\"n\":1,\"min\":1,\"max\":100,\"replacement\":true,\"base\":10${[identity] \"}\"},\"id\":"; string constant private queryString3 = "${[identity] \"}\"}']}"; /* * events */ /* log bets + output to web3 for precise 'payout on win' field in UI */ event LogBet(bytes32 indexed BetID, address indexed PlayerAddress, uint indexed RewardValue, uint ProfitValue, uint BetValue, uint PlayerNumber, uint RandomQueryID); /* output to web3 UI on bet result*/ /* Status: 0=lose, 1=win, 2=win + failed send, 3=refund, 4=refund + failed send*/ event LogResult(uint indexed ResultSerialNumber, bytes32 indexed BetID, address indexed PlayerAddress, uint PlayerNumber, uint DiceResult, uint Value, int Status, bytes Proof); /* log manual refunds */ event LogRefund(bytes32 indexed BetID, address indexed PlayerAddress, uint indexed RefundValue); /* log owner transfers */ event LogOwnerTransfer(address indexed SentToAddress, uint indexed AmountTransferred); /* * init */ function Etheroll() { owner = msg.sender; treasury = msg.sender; oraclize_setNetwork(networkID_auto); /* use TLSNotary for oraclize call */ oraclize_setProof(proofType_TLSNotary | proofStorage_IPFS); /* init 990 = 99% (1% houseEdge)*/ ownerSetHouseEdge(990); /* init 10,000 = 1% */ ownerSetMaxProfitAsPercentOfHouse(10000); /* init min bet (0.1 ether) */ ownerSetMinBet(100000000000000000); /* init gas for oraclize */ gasForOraclize = 235000; /* init gas price for callback (default 20 gwei)*/ oraclize_setCustomGasPrice(20000000000 wei); } /* * public function * player submit bet * only if game is active & bet is valid can query oraclize and set player vars */ function playerRollDice(uint rollUnder) public payable gameIsActive betIsValid(msg.value, rollUnder) { /* * assign partially encrypted query to oraclize * only the apiKey is encrypted * integer query is in plain text */ randomQueryID += 1; string memory identityString = string(abi.encodePacked(uint2str(randomQueryID), uint2str(rollUnder), uint2str(msg.value))); bytes32 rngId = oraclize_query("nested", string(abi.encodePacked(queryString1, identityString, queryString2, identityString, queryString3)), gasForOraclize); /* map bet id to this oraclize query */ playerBetId[rngId] = rngId; /* map identity string to this oraclize query */ playerIdentityRequest[rngId] = sha3(identityString); /* map player lucky number to this oraclize query */ playerNumber[rngId] = rollUnder; /* map value of wager to this oraclize query */ playerBetValue[rngId] = msg.value; /* map player address to this oraclize query */ playerAddress[rngId] = msg.sender; /* safely map player profit to this oraclize query */ playerProfit[rngId] = ((((msg.value * (100-(safeSub(rollUnder,1)))) / (safeSub(rollUnder,1))+msg.value))*houseEdge/houseEdgeDivisor)-msg.value; /* safely increase maxPendingPayouts liability - calc all pending payouts under assumption they win */ maxPendingPayouts = safeAdd(maxPendingPayouts, playerProfit[rngId]); /* check contract can payout on win */ if(maxPendingPayouts >= contractBalance) throw; /* provides accurate numbers for web3 and allows for manual refunds in case of no oraclize __callback */ LogBet(playerBetId[rngId], playerAddress[rngId], safeAdd(playerBetValue[rngId], playerProfit[rngId]), playerProfit[rngId], playerBetValue[rngId], playerNumber[rngId], randomQueryID); } /* * semi-public function - only oraclize can call */ /*TLSNotary for oraclize call */ function __callback(bytes32 myid, string result, bytes proof) public onlyOraclize payoutsAreActive { /* player address mapped to query id does not exist*/ if (playerAddress[myid]==0x0) throw; var sl_result = result.toSlice(); /* get player identityResponse to compare against playerIdentityRequest[myid]*/ bytes32 identityResponse = sha3(sl_result.split(' '.toSlice()).toString()); /* get random.org serialNumber from result */ uint serialNumberOfResult = parseInt(sl_result.split(','.toSlice()).toString()); /* map random result to player */ playerDieResult[myid] = parseInt(sl_result.toString()); /* get the playerAddress for this query id */ playerTempAddress[myid] = playerAddress[myid]; /* delete playerAddress for this query id */ delete playerAddress[myid]; /* map the playerProfit for this query id */ playerTempReward[myid] = playerProfit[myid]; /* set playerProfit for this query id to 0 */ playerProfit[myid] = 0; /* safely reduce maxPendingPayouts liability */ maxPendingPayouts = safeSub(maxPendingPayouts, playerTempReward[myid]); /* map the playerBetValue for this query id */ playerTempBetValue[myid] = playerBetValue[myid]; /* set playerBetValue for this query id to 0 */ playerBetValue[myid] = 0; /* total number of bets */ totalBets += 1; /* total wagered */ totalWeiWagered += playerTempBetValue[myid]; /* * refund * no proof || identity mismatch || result 0 || result empty refund original bet value * if refund fails save refund value to playerPendingWithdrawals */ if(bytes(proof).length == 0 || playerIdentityRequest[myid] != identityResponse || playerDieResult[myid] == 0 || bytes(result).length == 0){ LogResult(serialNumberOfResult, playerBetId[myid], playerTempAddress[myid], playerNumber[myid], playerDieResult[myid], playerTempBetValue[myid], 3, proof); /* * send refund - external call to an untrusted contract * if send fails map refund value to playerPendingWithdrawals[address] * for withdrawal later via playerWithdrawPendingTransactions */ if(!playerTempAddress[myid].send(playerTempBetValue[myid])){ LogResult(serialNumberOfResult, playerBetId[myid], playerTempAddress[myid], playerNumber[myid], playerDieResult[myid], playerTempBetValue[myid], 4, proof); /* if send failed let player withdraw via playerWithdrawPendingTransactions */ playerPendingWithdrawals[playerTempAddress[myid]] = safeAdd(playerPendingWithdrawals[playerTempAddress[myid]], playerTempBetValue[myid]); } return; } /* * pay winner * update contract balance to calculate new max bet * send reward * if send of reward fails save value to playerPendingWithdrawals */ if(playerDieResult[myid] < playerNumber[myid]){ /* safely reduce contract balance by player profit */ contractBalance = safeSub(contractBalance, playerTempReward[myid]); /* update total wei won */ totalWeiWon = safeAdd(totalWeiWon, playerTempReward[myid]); /* safely calculate payout via profit plus original wager */ playerTempReward[myid] = safeAdd(playerTempReward[myid], playerTempBetValue[myid]); LogResult(serialNumberOfResult, playerBetId[myid], playerTempAddress[myid], playerNumber[myid], playerDieResult[myid], playerTempReward[myid], 1, proof); /* update maximum profit */ setMaxProfit(); /* * send win - external call to an untrusted contract * if send fails map reward value to playerPendingWithdrawals[address] * for withdrawal later via playerWithdrawPendingTransactions */ if(!playerTempAddress[myid].send(playerTempReward[myid])){ LogResult(serialNumberOfResult, playerBetId[myid], playerTempAddress[myid], playerNumber[myid], playerDieResult[myid], playerTempReward[myid], 2, proof); /* if send failed let player withdraw via playerWithdrawPendingTransactions */ playerPendingWithdrawals[playerTempAddress[myid]] = safeAdd(playerPendingWithdrawals[playerTempAddress[myid]], playerTempReward[myid]); } return; } /* * no win * send 1 wei to a losing bet * update contract balance to calculate new max bet */ if(playerDieResult[myid] >= playerNumber[myid]){ LogResult(serialNumberOfResult, playerBetId[myid], playerTempAddress[myid], playerNumber[myid], playerDieResult[myid], playerTempBetValue[myid], 0, proof); /* * safe adjust contractBalance * setMaxProfit * send 1 wei to losing bet */ contractBalance = safeAdd(contractBalance, (playerTempBetValue[myid]-1)); /* update maximum profit */ setMaxProfit(); /* * send 1 wei - external call to an untrusted contract */ if(!playerTempAddress[myid].send(1)){ /* if send failed let player withdraw via playerWithdrawPendingTransactions */ playerPendingWithdrawals[playerTempAddress[myid]] = safeAdd(playerPendingWithdrawals[playerTempAddress[myid]], 1); } return; } } /* * public function * in case of a failed refund or win send */ function playerWithdrawPendingTransactions() public payoutsAreActive returns (bool) { uint withdrawAmount = playerPendingWithdrawals[msg.sender]; playerPendingWithdrawals[msg.sender] = 0; /* external call to untrusted contract */ if (msg.sender.call.value(withdrawAmount)()) { return true; } else { /* if send failed revert playerPendingWithdrawals[msg.sender] = 0; */ /* player can try to withdraw again later */ playerPendingWithdrawals[msg.sender] = withdrawAmount; return false; } } /* check for pending withdrawals */ function playerGetPendingTxByAddress(address addressToCheck) public constant returns (uint) { return playerPendingWithdrawals[addressToCheck]; } /* * internal function * sets max profit */ function setMaxProfit() internal { maxProfit = (contractBalance*maxProfitAsPercentOfHouse)/maxProfitDivisor; } /* * owner/treasury address only functions */ function () payable onlyTreasury { /* safely update contract balance */ contractBalance = safeAdd(contractBalance, msg.value); /* update the maximum profit */ setMaxProfit(); } /* set gas price for oraclize callback */ function ownerSetCallbackGasPrice(uint newCallbackGasPrice) public onlyOwner { oraclize_setCustomGasPrice(newCallbackGasPrice); } /* set gas limit for oraclize query */ function ownerSetOraclizeSafeGas(uint32 newSafeGasToOraclize) public onlyOwner { gasForOraclize = newSafeGasToOraclize; } /* only owner adjust contract balance variable (only used for max profit calc) */ function ownerUpdateContractBalance(uint newContractBalanceInWei) public onlyOwner { contractBalance = newContractBalanceInWei; } /* only owner address can set houseEdge */ function ownerSetHouseEdge(uint newHouseEdge) public onlyOwner { houseEdge = newHouseEdge; } /* only owner address can set maxProfitAsPercentOfHouse */ function ownerSetMaxProfitAsPercentOfHouse(uint newMaxProfitAsPercent) public onlyOwner { /* restrict each bet to a maximum profit of 1% contractBalance */ if(newMaxProfitAsPercent > 10000) throw; maxProfitAsPercentOfHouse = newMaxProfitAsPercent; setMaxProfit(); } /* only owner address can set minBet */ function ownerSetMinBet(uint newMinimumBet) public onlyOwner { minBet = newMinimumBet; } /* only owner address can transfer ether */ function ownerTransferEther(address sendTo, uint amount) public onlyOwner { /* safely update contract balance when sending out funds*/ contractBalance = safeSub(contractBalance, amount); /* update max profit */ setMaxProfit(); if(!sendTo.send(amount)) throw; LogOwnerTransfer(sendTo, amount); } /* only owner address can do manual refund * used only if bet placed + oraclize failed to __callback * filter LogBet by address and/or playerBetId: * LogBet(playerBetId[rngId], playerAddress[rngId], safeAdd(playerBetValue[rngId], playerProfit[rngId]), playerProfit[rngId], playerBetValue[rngId], playerNumber[rngId]); * check the following logs do not exist for playerBetId and/or playerAddress[rngId] before refunding: * LogResult or LogRefund * if LogResult exists player should use the withdraw pattern playerWithdrawPendingTransactions */ function ownerRefundPlayer(bytes32 originalPlayerBetId, address sendTo, uint originalPlayerProfit, uint originalPlayerBetValue) public onlyOwner { /* safely reduce pendingPayouts by playerProfit[rngId] */ maxPendingPayouts = safeSub(maxPendingPayouts, originalPlayerProfit); /* send refund */ if(!sendTo.send(originalPlayerBetValue)) throw; /* log refunds */ LogRefund(originalPlayerBetId, sendTo, originalPlayerBetValue); } /* only owner address can set emergency pause #1 */ function ownerPauseGame(bool newStatus) public onlyOwner { gamePaused = newStatus; } /* only owner address can set emergency pause #2 */ function ownerPausePayouts(bool newPayoutStatus) public onlyOwner { payoutsPaused = newPayoutStatus; } /* only owner address can set treasury address */ function ownerSetTreasury(address newTreasury) public onlyOwner { treasury = newTreasury; } /* only owner address can set owner address */ function ownerChangeOwner(address newOwner) public onlyOwner { owner = newOwner; } /* only owner address can suicide - emergency */ function ownerkill() public onlyOwner { suicide(owner); } }
public function in case of a failed refund or win send/ external call to untrusted contract /
function playerWithdrawPendingTransactions() public payoutsAreActive returns (bool) { uint withdrawAmount = playerPendingWithdrawals[msg.sender]; playerPendingWithdrawals[msg.sender] = 0; if (msg.sender.call.value(withdrawAmount)()) { return true; playerPendingWithdrawals[msg.sender] = withdrawAmount; return false; }
6,815,911
./full_match/97/0x001079B961fE0873E47c20d704E13Fb2c3Ea7cc7/sources/project_/contracts/UGRTokenFactory.sol
devolver el precio que vale crear el token con BNB
function getDeployPriceBNB() external view returns(uint256){
5,045,334
pragma solidity ^0.4.11; contract DoNotDeployThisGetTheRightOneCosParityPutsThisOnTop { uint256 nothing; function DoNotDeployThisGetTheRightOneCosParityPutsThisOnTop() { nothing = 27; } } //*************** Ownable contract Ownable { address public owner; function Ownable() { owner = msg.sender; } modifier onlyOwner() { require(msg.sender == owner); _; } function transferOwnership(address newOwner) onlyOwner { if (newOwner != address(0)) { owner = newOwner; } } } //***********Pausible 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() onlyOwner whenNotPaused returns (bool) { paused = true; Pause(); return true; } /** * @dev called by the owner to unpause, returns to normal state */ function unpause() onlyOwner whenPaused returns (bool) { paused = false; Unpause(); return true; } } //*************ERC20 contract ERC20 { uint public totalSupply; function balanceOf(address who) constant returns (uint); function allowance(address owner, address spender) constant returns (uint); function transfer(address to, uint value) returns (bool ok); function transferFrom(address from, address to, uint value) returns (bool ok); function approve(address spender, uint value) returns (bool ok); event Transfer(address indexed from, address indexed to, uint value); event Approval(address indexed owner, address indexed spender, uint value); } //*************** SafeMath contract SafeMath { function safeMul(uint a, uint b) internal returns (uint) { uint c = a * b; assert(a == 0 || c / a == b); return c; } function safeDiv(uint a, uint b) internal returns (uint) { assert(b > 0); uint c = a / b; assert(a == b * c + a % b); return c; } function safeSub(uint a, uint b) internal returns (uint) { assert(b <= a); return a - b; } function safeAdd(uint a, uint b) internal returns (uint) { uint c = a + b; assert(c>=a && c>=b); return c; } function max64(uint64 a, uint64 b) internal constant returns (uint64) { return a >= b ? a : b; } function min64(uint64 a, uint64 b) internal constant returns (uint64) { return a < b ? a : b; } function max256(uint256 a, uint256 b) internal constant returns (uint256) { return a >= b ? a : b; } function min256(uint256 a, uint256 b) internal constant returns (uint256) { return a < b ? a : b; } } //**************** StandardToken contract StandardToken is ERC20, SafeMath { /** * @dev Fix for the ERC20 short address attack. */ modifier onlyPayloadSize(uint size) { require(msg.data.length >= size + 4); _; } mapping(address => uint) balances; mapping (address => mapping (address => uint)) allowed; function transfer(address _to, uint _value) onlyPayloadSize(2 * 32) returns (bool success){ balances[msg.sender] = safeSub(balances[msg.sender], _value); balances[_to] = safeAdd(balances[_to], _value); Transfer(msg.sender, _to, _value); return true; } function transferFrom(address _from, address _to, uint _value) onlyPayloadSize(3 * 32) returns (bool success) { var _allowance = allowed[_from][msg.sender]; // Check is not needed because safeSub(_allowance, _value) will already throw if this condition is not met // if (_value > _allowance) throw; balances[_to] = safeAdd(balances[_to], _value); balances[_from] = safeSub(balances[_from], _value); allowed[_from][msg.sender] = safeSub(_allowance, _value); Transfer(_from, _to, _value); return true; } function balanceOf(address _owner) constant returns (uint balance) { return balances[_owner]; } function approve(address _spender, uint _value) returns (bool success) { require((_value == 0) || (allowed[msg.sender][_spender] == 0)); allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); return true; } function allowance(address _owner, address _spender) constant returns (uint remaining) { return allowed[_owner][_spender]; } } contract GBT { function parentChange(address,uint); function parentFees(address); function setHGT(address _hgt); } //************ HELLOGOLDTOKEN contract HelloGoldToken is ERC20, SafeMath, Pausable, StandardToken { string public name; string public symbol; uint8 public decimals; GBT goldtoken; function setGBT(address gbt_) onlyOwner { goldtoken = GBT(gbt_); } function GBTAddress() constant returns (address) { return address(goldtoken); } function HelloGoldToken(address _reserve) { name = "HelloGold Token"; symbol = "HGT"; decimals = 8; totalSupply = 1 * 10 ** 9 * 10 ** uint256(decimals); balances[_reserve] = totalSupply; } function parentChange(address _to) internal { require(address(goldtoken) != 0x0); goldtoken.parentChange(_to,balances[_to]); } function parentFees(address _to) internal { require(address(goldtoken) != 0x0); goldtoken.parentFees(_to); } function transferFrom(address _from, address _to, uint256 _value) returns (bool success){ parentFees(_from); parentFees(_to); success = super.transferFrom(_from,_to,_value); parentChange(_from); parentChange(_to); return; } function transfer(address _to, uint _value) whenNotPaused returns (bool success) { parentFees(msg.sender); parentFees(_to); success = super.transfer(_to,_value); parentChange(msg.sender); parentChange(_to); return; } function approve(address _spender, uint _value) whenNotPaused returns (bool success) { return super.approve(_spender,_value); } } //********* GOLDFEES ************************ contract GoldFees is SafeMath,Ownable { // e.g. if rate = 0.0054 //uint rateN = 9999452055; uint rateN = 9999452054794520548; uint rateD = 19; uint public maxDays; uint public maxRate; function GoldFees() { calcMax(); } function calcMax() { maxDays = 1; maxRate = rateN; uint pow = 2; do { uint newN = rateN ** pow; if (newN / maxRate != maxRate) { maxDays = pow / 2; break; } maxRate = newN; pow *= 2; } while (pow < 2000); } function updateRate(uint256 _n, uint256 _d) onlyOwner{ rateN = _n; rateD = _d; calcMax(); } function rateForDays(uint256 numDays) constant returns (uint256 rate) { if (numDays <= maxDays) { uint r = rateN ** numDays; uint d = rateD * numDays; if (d > 18) { uint div = 10 ** (d-18); rate = r / div; } else { div = 10 ** (18 - d); rate = r * div; } } else { uint256 md1 = numDays / 2; uint256 md2 = numDays - md1; uint256 r2; uint256 r1 = rateForDays(md1); if (md1 == md2) { r2 = r1; } else { r2 = rateForDays(md2); } //uint256 r1 = rateForDays(maxDays); //uint256 r2 = rateForDays(numDays-maxDays); rate = safeMul( r1 , r2) / 10 ** 18; } return; } uint256 constant public UTC2MYT = 1483200000; function wotDay(uint256 time) returns (uint256) { return (time - UTC2MYT) / (1 days); } // minimum fee is 1 unless same day function calcFees(uint256 start, uint256 end, uint256 startAmount) constant returns (uint256 amount, uint256 fee) { if (startAmount == 0) return; uint256 numberOfDays = wotDay(end) - wotDay(start); if (numberOfDays == 0) { amount = startAmount; return; } amount = (rateForDays(numberOfDays) * startAmount) / (1 ether); if ((fee == 0) && (amount != 0)) amount--; fee = safeSub(startAmount,amount); } } //******************** GoldBackedToken contract GoldBackedToken is Ownable, SafeMath, ERC20, Pausable { event Transfer(address indexed from, address indexed to, uint value); event Approval(address indexed owner, address indexed spender, uint value); event DeductFees(address indexed owner,uint256 amount); event TokenMinted(address destination, uint256 amount); event TokenBurned(address source, uint256 amount); string public name = "HelloGold Gold Backed Token"; string public symbol = "GBT"; uint256 constant public decimals = 18; // same as ETH uint256 constant public hgtDecimals = 8; uint256 constant public allocationPool = 1 * 10**9 * 10**hgtDecimals; // total HGT holdings uint256 constant public maxAllocation = 38 * 10**5 * 10**decimals; // max GBT that can ever ever be given out uint256 public totAllocation; // amount of GBT so far address public feeCalculator; address public HGT; // HGT contract address function setFeeCalculator(address newFC) onlyOwner { feeCalculator = newFC; } function calcFees(uint256 from, uint256 to, uint256 amount) returns (uint256 val, uint256 fee) { return GoldFees(feeCalculator).calcFees(from,to,amount); } function GoldBackedToken(address feeCalc) { feeCalculator = feeCalc; } struct allocation { uint256 amount; uint256 date; } allocation[] public allocationsOverTime; allocation[] public currentAllocations; function currentAllocationLength() constant returns (uint256) { return currentAllocations.length; } function aotLength() constant returns (uint256) { return allocationsOverTime.length; } struct Balance { uint256 amount; // amount through update or transfer uint256 lastUpdated; // DATE last updated uint256 nextAllocationIndex; // which allocationsOverTime record contains next update uint256 allocationShare; // the share of allocationPool that this holder gets (means they hold HGT) } /*Creates an array with all balances*/ mapping (address => Balance) public balances; mapping (address => mapping (address => uint)) allowed; function update(address where) internal { uint256 pos; uint256 fees; uint256 val; (val,fees,pos) = updatedBalance(where); balances[where].nextAllocationIndex = pos; balances[where].amount = val; balances[where].lastUpdated = now; } function updatedBalance(address where) constant public returns (uint val, uint fees, uint pos) { uint256 c_val; uint256 c_fees; uint256 c_amount; (val, fees) = calcFees(balances[where].lastUpdated,now,balances[where].amount); pos = balances[where].nextAllocationIndex; if ((pos < currentAllocations.length) && (balances[where].allocationShare != 0)) { c_amount = currentAllocations[balances[where].nextAllocationIndex].amount * balances[where].allocationShare / allocationPool; (c_val,c_fees) = calcFees(currentAllocations[balances[where].nextAllocationIndex].date,now,c_amount); } val += c_val; fees += c_fees; pos = currentAllocations.length; } function balanceOf(address where) constant returns (uint256 val) { uint256 fees; uint256 pos; (val,fees,pos) = updatedBalance(where); return ; } event Allocation(uint256 amount, uint256 date); event FeeOnAllocation(uint256 fees, uint256 date); event PartComplete(); event StillToGo(uint numLeft); uint256 public partPos; uint256 public partFees; uint256 partL; allocation[] public partAllocations; function partAllocationLength() constant returns (uint) { return partAllocations.length; } function addAllocationPartOne(uint newAllocation,uint numSteps) onlyOwner{ uint256 thisAllocation = newAllocation; require(totAllocation < maxAllocation); // cannot allocate more than this; if (currentAllocations.length > partAllocations.length) { partAllocations = currentAllocations; } if (totAllocation + thisAllocation > maxAllocation) { thisAllocation = maxAllocation - totAllocation; log0("max alloc reached"); } totAllocation += thisAllocation; Allocation(thisAllocation,now); allocation memory newDiv; newDiv.amount = thisAllocation; newDiv.date = now; // store into history allocationsOverTime.push(newDiv); // add this record to the end of currentAllocations partL = partAllocations.push(newDiv); // update all other records with calcs from last record if (partAllocations.length < 2) { // no fees to consider PartComplete(); currentAllocations = partAllocations; FeeOnAllocation(0,now); return; } // // The only fees that need to be collected are the fees on location zero. // Since they are the last calculated = they come out with the break // for (partPos = partAllocations.length - 2; partPos >= 0; partPos-- ){ (partAllocations[partPos].amount,partFees) = calcFees(partAllocations[partPos].date,now,partAllocations[partPos].amount); partAllocations[partPos].amount += partAllocations[partL - 1].amount; partAllocations[partPos].date = now; if ((partPos == 0) || (partPos == partAllocations.length-numSteps)){ break; } } if (partPos != 0) { StillToGo(partPos); return; // not done yet } PartComplete(); FeeOnAllocation(partFees,now); currentAllocations = partAllocations; } function addAllocationPartTwo(uint numSteps) onlyOwner { require(numSteps > 0); require(partPos > 0); for (uint i = 0; i < numSteps; i++ ){ partPos--; (partAllocations[partPos].amount,partFees) = calcFees(partAllocations[partPos].date,now,partAllocations[partPos].amount); partAllocations[partPos].amount += partAllocations[partL - 1].amount; partAllocations[partPos].date = now; if (partPos == 0) { break; } } if (partPos != 0) { StillToGo(partPos); return; // not done yet } PartComplete(); FeeOnAllocation(partFees,now); currentAllocations = partAllocations; } function setHGT(address _hgt) onlyOwner { HGT = _hgt; } function parentFees(address where) whenNotPaused { require(msg.sender == HGT); update(where); } function parentChange(address where, uint newValue) whenNotPaused { // called when HGT balance changes require(msg.sender == HGT); balances[where].allocationShare = newValue; } /* send GBT */ function transfer(address _to, uint256 _value) whenNotPaused returns (bool ok) { update(msg.sender); // Do this to ensure sender has enough funds. update(_to); balances[msg.sender].amount = safeSub(balances[msg.sender].amount, _value); balances[_to].amount = safeAdd(balances[_to].amount, _value); Transfer(msg.sender, _to, _value); //Notify anyone listening that this transfer took place return true; } function transferFrom(address _from, address _to, uint _value) whenNotPaused returns (bool success) { var _allowance = allowed[_from][msg.sender]; update(_from); // Do this to ensure sender has enough funds. update(_to); balances[_to].amount = safeAdd(balances[_to].amount, _value); balances[_from].amount = safeSub(balances[_from].amount, _value); allowed[_from][msg.sender] = safeSub(_allowance, _value); Transfer(_from, _to, _value); return true; } function approve(address _spender, uint _value) whenNotPaused returns (bool success) { require((_value == 0) || (allowed[msg.sender][_spender] == 0)); allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); return true; } function allowance(address _owner, address _spender) constant returns (uint remaining) { return allowed[_owner][_spender]; } // Minting Functions address public authorisedMinter; function setMinter(address minter) onlyOwner { authorisedMinter = minter; } function mintTokens(address destination, uint256 amount) { require(msg.sender == authorisedMinter); update(destination); balances[destination].amount = safeAdd(balances[destination].amount, amount); balances[destination].lastUpdated = now; balances[destination].nextAllocationIndex = currentAllocations.length; TokenMinted(destination,amount); } function burnTokens(address source, uint256 amount) { require(msg.sender == authorisedMinter); update(source); balances[source].amount = safeSub(balances[source].amount,amount); balances[source].lastUpdated = now; balances[source].nextAllocationIndex = currentAllocations.length; TokenBurned(source,amount); } } //**************** HelloGoldSale contract HelloGoldSale is Pausable, SafeMath { uint256 public decimals = 8; uint256 public startDate = 1503892800; // Monday, August 28, 2017 12:00:00 PM GMT+08:00 uint256 public endDate = 1504497600; // Monday, September 4, 2017 12:00:00 PM GMT+08:00 uint256 tranchePeriod = 1 weeks; // address of HGT Token. HGT must Approve this contract to disburse 300M tokens HelloGoldToken token; uint256 constant MaxCoinsR1 = 180 * 10**6 * 10**8; // 180M HGT uint256 public coinsRemaining = 180 * 10**6 * 10**8; uint256 coinsPerTier = 20 * 10**6 * 10**8; // 20M HGT uint256 public coinsLeftInTier = 20 * 10**6 * 10**8; uint256 public minimumCap = 0; // 40M HGT uint256 numTiers = 5; uint16 public tierNo; uint256 public preallocCoins; // used for testing against cap (inc placement) uint256 public purchasedCoins; // used for testing against tier pricing uint256 public ethRaised; uint256 public personalMax = 10 * 1 ether; // max ether per person during public sale uint256 public contributors; address public cs; address public multiSig; address public HGT_Reserve; struct csAction { bool passedKYC; bool blocked; } /* This creates an array with all balances */ mapping (address => csAction) public permissions; mapping (address => uint256) public deposits; modifier MustBeEnabled(address x) { require (!permissions[x].blocked) ; require (permissions[x].passedKYC) ; _; } function HelloGoldSale(address _cs, address _hgt, address _multiSig, address _reserve) { cs = _cs; token = HelloGoldToken(_hgt); multiSig = _multiSig; HGT_Reserve = _reserve; } // We only expect to use this to set/reset the start of the contract under exceptional circumstances function setStart(uint256 when_) onlyOwner { startDate = when_; endDate = when_ + tranchePeriod; } modifier MustBeCs() { require (msg.sender == cs) ; _; } // 1 ether = N HGT tokens uint256[5] public hgtRates = [1248900000000,1196900000000,1144800000000,1092800000000,1040700000000]; /* Approve the account for operation */ function approve(address user) MustBeCs { permissions[user].passedKYC = true; } function block(address user) MustBeCs { permissions[user].blocked = true; } function unblock(address user) MustBeCs { permissions[user].blocked = false; } function newCs(address newCs) onlyOwner { cs = newCs; } function setPeriod(uint256 period_) onlyOwner { require (!funding()) ; tranchePeriod = period_; endDate = startDate + tranchePeriod; if (endDate < now + tranchePeriod) { endDate = now + tranchePeriod; } } function when() constant returns (uint256) { return now; } function funding() constant returns (bool) { if (paused) return false; // frozen if (now < startDate) return false; // too early if (now > endDate) return false; // too late if (coinsRemaining == 0) return false; // no more coins if (tierNo >= numTiers ) return false; // passed end of top tier. Tiers start at zero return true; } function success() constant returns (bool succeeded) { if (coinsRemaining == 0) return true; bool complete = (now > endDate) ; bool didOK = (coinsRemaining <= (MaxCoinsR1 - minimumCap)); // not even 40M Gone?? Aargh. succeeded = (complete && didOK) ; // (out of steam but enough sold) return ; } function failed() constant returns (bool didNotSucceed) { bool complete = (now > endDate ); bool didBad = (coinsRemaining > (MaxCoinsR1 - minimumCap)); didNotSucceed = (complete && didBad); return; } function () payable MustBeEnabled(msg.sender) whenNotPaused { createTokens(msg.sender,msg.value); } function linkCoin(address coin) onlyOwner { token = HelloGoldToken(coin); } function coinAddress() constant returns (address) { return address(token); } // hgtRates in whole tokens per ETH // max individual contribution in whole ETH function setHgtRates(uint256 p0,uint256 p1,uint256 p2,uint256 p3,uint256 p4, uint256 _max ) onlyOwner { require (now < startDate) ; hgtRates[0] = p0 * 10**8; hgtRates[1] = p1 * 10**8; hgtRates[2] = p2 * 10**8; hgtRates[3] = p3 * 10**8; hgtRates[4] = p4 * 10**8; personalMax = _max * 1 ether; // max ETH per person } event Purchase(address indexed buyer, uint256 level,uint256 value, uint256 tokens); event Reduction(string msg, address indexed buyer, uint256 wanted, uint256 allocated); function createTokens(address recipient, uint256 value) private { uint256 totalTokens; uint256 hgtRate; require (funding()) ; require (value > 1 finney) ; require (deposits[recipient] < personalMax); uint256 maxRefund = 0; if ((deposits[msg.sender] + value) > personalMax) { maxRefund = deposits[msg.sender] + value - personalMax; value -= maxRefund; log0("maximum funds exceeded"); } uint256 val = value; ethRaised = safeAdd(ethRaised,value); if (deposits[recipient] == 0) contributors++; do { hgtRate = hgtRates[tierNo]; // hgtRate must include the 10^8 uint tokens = safeMul(val, hgtRate); // (val in eth * 10^18) * #tokens per eth tokens = safeDiv(tokens, 1 ether); // val is in ether, msg.value is in wei if (tokens <= coinsLeftInTier) { uint256 actualTokens = tokens; uint refund = 0; if (tokens > coinsRemaining) { //can't sell desired # tokens Reduction("in tier",recipient,tokens,coinsRemaining); actualTokens = coinsRemaining; refund = safeSub(tokens, coinsRemaining ); // refund amount in tokens refund = safeDiv(refund*1 ether,hgtRate ); // refund amount in ETH // need a refund mechanism here too coinsRemaining = 0; val = safeSub( val,refund); } else { coinsRemaining = safeSub(coinsRemaining, actualTokens); } purchasedCoins = safeAdd(purchasedCoins, actualTokens); totalTokens = safeAdd(totalTokens,actualTokens); require (token.transferFrom(HGT_Reserve, recipient,totalTokens)) ; Purchase(recipient,tierNo,val,actualTokens); // event deposits[recipient] = safeAdd(deposits[recipient],val); // in case of refund - could pull off etherscan refund += maxRefund; if (refund > 0) { ethRaised = safeSub(ethRaised,refund); recipient.transfer(refund); } if (coinsRemaining <= (MaxCoinsR1 - minimumCap)){ // has passed success criteria if (!multiSig.send(this.balance)) { // send funds to HGF log0("cannot forward funds to owner"); } } coinsLeftInTier = safeSub(coinsLeftInTier,actualTokens); if ((coinsLeftInTier == 0) && (coinsRemaining != 0)) { // exact sell out of non final tier coinsLeftInTier = coinsPerTier; tierNo++; endDate = now + tranchePeriod; } return; } // check that coinsLeftInTier >= coinsRemaining uint256 coins2buy = min256(coinsLeftInTier , coinsRemaining); endDate = safeAdd( now, tranchePeriod); // Have bumped levels - need to modify end date here purchasedCoins = safeAdd(purchasedCoins, coins2buy); // give all coins remaining in this tier totalTokens = safeAdd(totalTokens,coins2buy); coinsRemaining = safeSub(coinsRemaining,coins2buy); uint weiCoinsLeftInThisTier = safeMul(coins2buy,1 ether); uint costOfTheseCoins = safeDiv(weiCoinsLeftInThisTier, hgtRate); // how much did that cost? Purchase(recipient, tierNo,costOfTheseCoins,coins2buy); // event deposits[recipient] = safeAdd(deposits[recipient],costOfTheseCoins); val = safeSub(val,costOfTheseCoins); tierNo = tierNo + 1; coinsLeftInTier = coinsPerTier; } while ((val > 0) && funding()); // escaped because we passed the end of the universe..... // so give them their tokens require (token.transferFrom(HGT_Reserve, recipient,totalTokens)) ; if ((val > 0) || (maxRefund > 0)){ Reduction("finished crowdsale, returning ",recipient,value,totalTokens); // return the remainder ! recipient.transfer(val+maxRefund); // if you can't return the balance, abort whole process } if (!multiSig.send(this.balance)) { ethRaised = safeSub(ethRaised,this.balance); log0("cannot send at tier jump"); } } function allocatedTokens(address grantee, uint256 numTokens) onlyOwner { require (now < startDate) ; if (numTokens < coinsRemaining) { coinsRemaining = safeSub(coinsRemaining, numTokens); } else { numTokens = coinsRemaining; coinsRemaining = 0; } preallocCoins = safeAdd(preallocCoins,numTokens); require (token.transferFrom(HGT_Reserve,grantee,numTokens)); } function withdraw() { // it failed. Come and get your ether. if (failed()) { if (deposits[msg.sender] > 0) { uint256 val = deposits[msg.sender]; deposits[msg.sender] = 0; msg.sender.transfer(val); } } } function complete() onlyOwner { // this should not have to be called. Extreme measures. if (success()) { uint256 val = this.balance; if (val > 0) { if (!multiSig.send(val)) { log0("cannot withdraw"); } else { log0("funds withdrawn"); } } else { log0("nothing to withdraw"); } } } }
Approve the account for operation /
function approve(address user) MustBeCs { permissions[user].passedKYC = true; }
1,011,406
pragma solidity ^0.4.21; library strings { struct slice { uint _len; uint _ptr; } /* * @dev Returns a slice containing the entire string. * @param self The string to make a slice from. * @return A newly allocated slice containing the entire string. */ function toSlice(string self) internal pure returns (slice) { uint ptr; assembly { ptr := add(self, 0x20) } return slice(bytes(self).length, ptr); } function memcpy(uint dest, uint src, uint len) private pure { // 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)) } } function concat(slice self, slice other) internal returns (string) { var ret = new string(self._len + other._len); uint retptr; assembly { retptr := add(ret, 32) } memcpy(retptr, self._ptr, self._len); memcpy(retptr + self._len, other._ptr, other._len); return ret; } /* * @dev Counts the number of nonoverlapping occurrences of `needle` in `self`. * @param self The slice to search. * @param needle The text to search for in `self`. * @return The number of occurrences of `needle` found in `self`. */ function count(slice self, slice needle) internal returns (uint cnt) { uint ptr = findPtr(self._len, self._ptr, needle._len, needle._ptr) + needle._len; while (ptr <= self._ptr + self._len) { cnt++; ptr = findPtr(self._len - (ptr - self._ptr), ptr, needle._len, needle._ptr) + needle._len; } } // Returns the memory address of the first byte of the first occurrence of // `needle` in `self`, or the first byte after `self` if not found. function findPtr(uint selflen, uint selfptr, uint needlelen, uint needleptr) private returns (uint) { uint ptr; uint idx; if (needlelen <= selflen) { if (needlelen <= 32) { // Optimized assembly for 68 gas per byte on short strings assembly { let mask := not(sub(exp(2, mul(8, sub(32, needlelen))), 1)) let needledata := and(mload(needleptr), mask) let end := add(selfptr, sub(selflen, needlelen)) ptr := selfptr loop: jumpi(exit, eq(and(mload(ptr), mask), needledata)) ptr := add(ptr, 1) jumpi(loop, lt(sub(ptr, 1), end)) ptr := add(selfptr, selflen) exit: } return ptr; } else { // For long needles, use hashing bytes32 hash; assembly { hash := sha3(needleptr, needlelen) } ptr = selfptr; for (idx = 0; idx <= selflen - needlelen; idx++) { bytes32 testHash; assembly { testHash := sha3(ptr, needlelen) } if (hash == testHash) return ptr; ptr += 1; } } } return selfptr + selflen; } /* * @dev Splits the slice, setting `self` to everything after the first * occurrence of `needle`, and `token` to everything before it. If * `needle` does not occur in `self`, `self` is set to the empty slice, * and `token` is set to the entirety of `self`. * @param self The slice to split. * @param needle The text to search for in `self`. * @param token An output parameter to which the first token is written. * @return `token`. */ function split(slice self, slice needle, slice token) internal returns (slice) { uint ptr = findPtr(self._len, self._ptr, needle._len, needle._ptr); token._ptr = self._ptr; token._len = ptr - self._ptr; if (ptr == self._ptr + self._len) { // Not found self._len = 0; } else { self._len -= token._len + needle._len; self._ptr = ptr + needle._len; } return token; } /* * @dev Splits the slice, setting `self` to everything after the first * occurrence of `needle`, and returning everything before it. If * `needle` does not occur in `self`, `self` is set to the empty slice, * and the entirety of `self` is returned. * @param self The slice to split. * @param needle The text to search for in `self`. * @return The part of `self` up to the first occurrence of `delim`. */ function split(slice self, slice needle) internal returns (slice token) { split(self, needle, token); } /* * @dev Copies a slice to a new string. * @param self The slice to copy. * @return A newly allocated string containing the slice&#39;s text. */ function toString(slice self) internal pure returns (string) { var ret = new string(self._len); uint retptr; assembly { retptr := add(ret, 32) } memcpy(retptr, self._ptr, self._len); return ret; } } /* Helper String Functions for Game Manager Contract * @title String Healpers * @author Fazri Zubair & Farhan Khwaja (Lucid Sight, Inc.) */ contract StringHelpers { using strings for *; function stringToBytes32(string memory source) internal returns (bytes32 result) { bytes memory tempEmptyStringTest = bytes(source); if (tempEmptyStringTest.length == 0) { return 0x0; } assembly { result := mload(add(source, 32)) } } function bytes32ToString(bytes32 x) constant internal returns (string) { bytes memory bytesString = new bytes(32); uint charCount = 0; for (uint j = 0; j < 32; j++) { byte char = byte(bytes32(uint(x) * 2 ** (8 * j))); if (char != 0) { bytesString[charCount] = char; charCount++; } } bytes memory bytesStringTrimmed = new bytes(charCount); for (j = 0; j < charCount; j++) { bytesStringTrimmed[j] = bytesString[j]; } return string(bytesStringTrimmed); } } /* Controls state and access rights for contract functions * @title Operational Control * @author Fazri Zubair & Farhan Khwaja (Lucid Sight, Inc.) * Inspired and adapted from contract created by OpenZeppelin * Ref: https://github.com/OpenZeppelin/zeppelin-solidity/ */ contract OperationalControl { // Facilitates access & control for the game. // Roles: // -The Managers (Primary/Secondary): Has universal control of all elements (No ability to withdraw) // -The Banker: The Bank can withdraw funds and adjust fees / prices. // -otherManagers: Contracts that need access to functions for gameplay /// @dev Emited when contract is upgraded event ContractUpgrade(address newContract); // The addresses of the accounts (or contracts) that can execute actions within each roles. address public managerPrimary; address public managerSecondary; address public bankManager; // Contracts that require access for gameplay mapping(address => uint8) public otherManagers; // @dev Keeps track whether the contract is paused. When that is true, most actions are blocked bool public paused = false; // @dev Keeps track whether the contract erroredOut. When that is true, most actions are blocked & refund can be claimed bool public error = false; /// @dev Operation modifiers for limiting access modifier onlyManager() { require(msg.sender == managerPrimary || msg.sender == managerSecondary); _; } modifier onlyBanker() { require(msg.sender == bankManager); _; } modifier onlyOtherManagers() { require(otherManagers[msg.sender] == 1); _; } modifier anyOperator() { require( msg.sender == managerPrimary || msg.sender == managerSecondary || msg.sender == bankManager || otherManagers[msg.sender] == 1 ); _; } /// @dev Assigns a new address to act as the Other Manager. (State = 1 is active, 0 is disabled) function setOtherManager(address _newOp, uint8 _state) external onlyManager { require(_newOp != address(0)); otherManagers[_newOp] = _state; } /// @dev Assigns a new address to act as the Primary Manager. function setPrimaryManager(address _newGM) external onlyManager { require(_newGM != address(0)); managerPrimary = _newGM; } /// @dev Assigns a new address to act as the Secondary Manager. function setSecondaryManager(address _newGM) external onlyManager { require(_newGM != address(0)); managerSecondary = _newGM; } /// @dev Assigns a new address to act as the Banker. function setBanker(address _newBK) external onlyManager { require(_newBK != address(0)); bankManager = _newBK; } /*** Pausable functionality adapted from OpenZeppelin ***/ /// @dev Modifier to allow actions only when the contract IS NOT paused modifier whenNotPaused() { require(!paused); _; } /// @dev Modifier to allow actions only when the contract IS paused modifier whenPaused { require(paused); _; } /// @dev Modifier to allow actions only when the contract has Error modifier whenError { require(error); _; } /// @dev Called by any Operator role to pause the contract. /// Used only if a bug or exploit is discovered (Here to limit losses / damage) function pause() external onlyManager whenNotPaused { paused = true; } /// @dev Unpauses the smart contract. Can only be called by the Game Master /// @notice This is public rather than external so it can be called by derived contracts. function unpause() public onlyManager whenPaused { // can&#39;t unpause if contract was upgraded paused = false; } /// @dev Unpauses the smart contract. Can only be called by the Game Master /// @notice This is public rather than external so it can be called by derived contracts. function hasError() public onlyManager whenPaused { error = true; } /// @dev Unpauses the smart contract. Can only be called by the Game Master /// @notice This is public rather than external so it can be called by derived contracts. function noError() public onlyManager whenPaused { error = false; } } /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { /** * @dev Multiplies two numbers, throws on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256 c) { if (a == 0) { return 0; } c = a * b; assert(c / a == b); return c; } /** * @dev Integer division of two numbers, truncating the quotient. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 // uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn&#39;t hold return a / b; } /** * @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } /** * @dev Adds two numbers, throws on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256 c) { c = a + b; assert(c >= a); return c; } } /** * @title ERC20Basic * @dev Simpler version of ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/179 */ contract ERC20Basic { function totalSupply() public view returns (uint256); function balanceOf(address who) public view returns (uint256); function transfer(address to, uint256 value) public returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); } /** * @title Basic token * @dev Basic version of StandardToken, with no allowances. */ contract BasicToken is ERC20Basic { using SafeMath for uint256; mapping(address => uint256) balances; uint256 totalSupply_; /** * @dev total number of tokens in existence */ function totalSupply() public view returns (uint256) { return totalSupply_; } /** * @dev transfer token for a specified address * @param _to The address to transfer to. * @param _value The amount to be transferred. */ function transfer(address _to, uint256 _value) public returns (bool) { require(_to != address(0)); require(_value <= balances[msg.sender]); balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); emit Transfer(msg.sender, _to, _value); return true; } /** * @dev Gets the balance of the specified address. * @param _owner The address to query the the balance of. * @return An uint256 representing the amount owned by the passed address. */ function balanceOf(address _owner) public view returns (uint256) { return balances[_owner]; } } /** * @title ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/20 */ contract ERC20 is ERC20Basic { function allowance(address owner, address spender) public view returns (uint256); function transferFrom(address from, address to, uint256 value) public returns (bool); function approve(address spender, uint256 value) public returns (bool); event Approval(address indexed owner, address indexed spender, uint256 value); } /** * @title ERC827 interface, an extension of ERC20 token standard * * @dev Interface of a ERC827 token, following the ERC20 standard with extra * @dev methods to transfer value and data and execute calls in transfers and * @dev approvals. */ contract ERC827 is ERC20 { function approveAndCall( address _spender, uint256 _value, bytes _data) public payable returns (bool); function transferAndCall( address _to, uint256 _value, bytes _data) public payable returns (bool); function transferFromAndCall( address _from, address _to, uint256 _value, bytes _data ) public payable returns (bool); } /** * @title Standard ERC20 token * * @dev Implementation of the basic standard token. * @dev https://github.com/ethereum/EIPs/issues/20 * @dev Based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol */ contract StandardToken is ERC20, BasicToken { mapping (address => mapping (address => uint256)) internal allowed; /** * @dev Transfer tokens from one address to another * @param _from address The address which you want to send tokens from * @param _to address The address which you want to transfer to * @param _value uint256 the amount of tokens to be transferred */ function transferFrom(address _from, address _to, uint256 _value) public returns (bool) { require(_to != address(0)); require(_value <= balances[_from]); require(_value <= allowed[_from][msg.sender]); balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); emit Transfer(_from, _to, _value); return true; } /** * @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender. * * Beware that changing an allowance with this method brings the risk that someone may use both the old * and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this * race condition is to first reduce the spender&#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; emit Approval(msg.sender, _spender, _value); return true; } /** * @dev Function to check the amount of tokens that an owner allowed to a spender. * @param _owner address The address which owns the funds. * @param _spender address The address which will spend the funds. * @return A uint256 specifying the amount of tokens still available for the spender. */ function allowance(address _owner, address _spender) public view returns (uint256) { return allowed[_owner][_spender]; } /** * @dev Increase the amount of tokens that an owner allowed to a spender. * * approve should be called when allowed[_spender] == 0. To increment * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param _spender The address which will spend the funds. * @param _addedValue The amount of tokens to increase the allowance by. */ function increaseApproval(address _spender, uint _addedValue) public returns (bool) { allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue); emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } /** * @dev Decrease the amount of tokens that an owner allowed to a spender. * * approve should be called when allowed[_spender] == 0. To decrement * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param _spender The address which will spend the funds. * @param _subtractedValue The amount of tokens to decrease the allowance by. */ function decreaseApproval(address _spender, uint _subtractedValue) public returns (bool) { uint oldValue = allowed[msg.sender][_spender]; if (_subtractedValue > oldValue) { allowed[msg.sender][_spender] = 0; } else { allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue); } emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } } /* solium-disable security/no-low-level-calls */ /** * @title ERC827, an extension of ERC20 token standard * * @dev Implementation the ERC827, following the ERC20 standard with extra * @dev methods to transfer value and data and execute calls in transfers and * @dev approvals. * * @dev Uses OpenZeppelin StandardToken. */ contract ERC827Token is ERC827, StandardToken { /** * @dev Addition to ERC20 token methods. It allows to * @dev approve the transfer of value and execute a call with the sent data. * * @dev Beware that changing an allowance with this method brings the risk that * @dev someone may use both the old and the new allowance by unfortunate * @dev transaction ordering. One possible solution to mitigate this race condition * @dev is to first reduce the spender&#39;s allowance to 0 and set the desired value * @dev afterwards: * @dev https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * @param _spender The address that will spend the funds. * @param _value The amount of tokens to be spent. * @param _data ABI-encoded contract call to call `_to` address. * * @return true if the call function was executed successfully */ function approveAndCall(address _spender, uint256 _value, bytes _data) public payable returns (bool) { require(_spender != address(this)); super.approve(_spender, _value); // solium-disable-next-line security/no-call-value require(_spender.call.value(msg.value)(_data)); return true; } /** * @dev Addition to ERC20 token methods. Transfer tokens to a specified * @dev address and execute a call with the sent data on the same transaction * * @param _to address The address which you want to transfer to * @param _value uint256 the amout of tokens to be transfered * @param _data ABI-encoded contract call to call `_to` address. * * @return true if the call function was executed successfully */ function transferAndCall(address _to, uint256 _value, bytes _data) public payable returns (bool) { require(_to != address(this)); super.transfer(_to, _value); // solium-disable-next-line security/no-call-value require(_to.call.value(msg.value)(_data)); return true; } /** * @dev Addition to ERC20 token methods. Transfer tokens from one address to * @dev another and make a contract call on the same transaction * * @param _from The address which you want to send tokens from * @param _to The address which you want to transfer to * @param _value The amout of tokens to be transferred * @param _data ABI-encoded contract call to call `_to` address. * * @return true if the call function was executed successfully */ function transferFromAndCall( address _from, address _to, uint256 _value, bytes _data ) public payable returns (bool) { require(_to != address(this)); super.transferFrom(_from, _to, _value); // solium-disable-next-line security/no-call-value require(_to.call.value(msg.value)(_data)); return true; } /** * @dev Addition to StandardToken methods. Increase the amount of tokens that * @dev an owner allowed to a spender and execute a call with the sent data. * * @dev approve should be called when allowed[_spender] == 0. To increment * @dev allowed value is better to use this function to avoid 2 calls (and wait until * @dev the first transaction is mined) * @dev From MonolithDAO Token.sol * * @param _spender The address which will spend the funds. * @param _addedValue The amount of tokens to increase the allowance by. * @param _data ABI-encoded contract call to call `_spender` address. */ function increaseApprovalAndCall(address _spender, uint _addedValue, bytes _data) public payable returns (bool) { require(_spender != address(this)); super.increaseApproval(_spender, _addedValue); // solium-disable-next-line security/no-call-value require(_spender.call.value(msg.value)(_data)); return true; } /** * @dev Addition to StandardToken methods. Decrease the amount of tokens that * @dev an owner allowed to a spender and execute a call with the sent data. * * @dev approve should be called when allowed[_spender] == 0. To decrement * @dev allowed value is better to use this function to avoid 2 calls (and wait until * @dev the first transaction is mined) * @dev From MonolithDAO Token.sol * * @param _spender The address which will spend the funds. * @param _subtractedValue The amount of tokens to decrease the allowance by. * @param _data ABI-encoded contract call to call `_spender` address. */ function decreaseApprovalAndCall(address _spender, uint _subtractedValue, bytes _data) public payable returns (bool) { require(_spender != address(this)); super.decreaseApproval(_spender, _subtractedValue); // solium-disable-next-line security/no-call-value require(_spender.call.value(msg.value)(_data)); return true; } } /** * @title Mintable token * @title Burnable Token * @dev Token that can be irreversibly burned (destroyed). * @dev Simple ERC20 Token example, with mintable token creation * @dev Issue: * https://github.com/OpenZeppelin/openzeppelin-solidity/issues/120 * Based on code by TokenMarketNet: https://github.com/TokenMarketNet/ico/blob/master/contracts/MintableToken.sol */ contract CSCResource is ERC827Token, OperationalControl { event Burn(address indexed burner, uint256 value); event Mint(address indexed to, uint256 amount); // Token Name string public NAME; // Token Symbol string public SYMBOL; // Token decimals uint public constant DECIMALS = 0; /** * Construct the token. * * This token must be created through a team multisig wallet, so that it is owned by that wallet. * */ function CSCResource(string _name, string _symbol, uint _initialSupply) public { // Create any address, can be transferred managerPrimary = msg.sender; managerSecondary = msg.sender; bankManager = msg.sender; NAME = _name; SYMBOL = _symbol; // Create initial supply totalSupply_ = totalSupply_.add(_initialSupply); balances[msg.sender] = balances[msg.sender].add(_initialSupply); emit Mint(msg.sender, _initialSupply); emit Transfer(address(0), msg.sender, _initialSupply); } /** * @dev Burns a specific amount of tokens. * @param _value The amount of token to be burned. */ function burn(uint256 _value) public { _burn(msg.sender, _value); } function _burn(address _who, uint256 _value) internal { require(_value <= balances[_who]); // no need to require value <= totalSupply, since that would imply the // sender&#39;s balance is greater than the totalSupply, which *should* be an assertion failure balances[_who] = balances[_who].sub(_value); totalSupply_ = totalSupply_.sub(_value); emit Burn(_who, _value); emit Transfer(_who, address(0), _value); } /** * @dev Function to mint tokens * @param _to The address that will receive the minted tokens. * @param _amount The amount of tokens to mint. * @return A boolean that indicates if the operation was successful. */ function mint(address _to, uint256 _amount) public anyOperator returns (bool) { totalSupply_ = totalSupply_.add(_amount); balances[_to] = balances[_to].add(_amount); emit Mint(_to, _amount); emit Transfer(address(0), _to, _amount); return true; } } contract CSCResourceFactory is OperationalControl, StringHelpers { event CSCResourceCreated(string resourceContract, address contractAddress, uint256 amount); mapping(uint16 => address) public resourceIdToAddress; mapping(bytes32 => address) public resourceNameToAddress; mapping(uint16 => bytes32) public resourceIdToName; uint16 resourceTypeCount; function CSCResourceFactory() public { managerPrimary = msg.sender; managerSecondary = msg.sender; bankManager = msg.sender; } function createNewCSCResource(string _name, string _symbol, uint _initialSupply) public anyOperator { require(resourceNameToAddress[stringToBytes32(_name)] == 0x0); address resourceContract = new CSCResource(_name, _symbol, _initialSupply); resourceIdToAddress[resourceTypeCount] = resourceContract; resourceNameToAddress[stringToBytes32(_name)] = resourceContract; resourceIdToName[resourceTypeCount] = stringToBytes32(_name); emit CSCResourceCreated(_name, resourceContract, _initialSupply); //Inc. for next resource resourceTypeCount += 1; } function setResourcesPrimaryManager(address _op) public onlyManager { require(_op != address(0)); uint16 totalResources = getResourceCount(); for(uint16 i = 0; i < totalResources; i++) { CSCResource resContract = CSCResource(resourceIdToAddress[i]); resContract.setPrimaryManager(_op); } } function setResourcesSecondaryManager(address _op) public onlyManager { require(_op != address(0)); uint16 totalResources = getResourceCount(); for(uint16 i = 0; i < totalResources; i++) { CSCResource resContract = CSCResource(resourceIdToAddress[i]); resContract.setSecondaryManager(_op); } } function setResourcesBanker(address _op) public onlyManager { require(_op != address(0)); uint16 totalResources = getResourceCount(); for(uint16 i = 0; i < totalResources; i++) { CSCResource resContract = CSCResource(resourceIdToAddress[i]); resContract.setBanker(_op); } } function setResourcesOtherManager(address _op, uint8 _state) public anyOperator { require(_op != address(0)); uint16 totalResources = getResourceCount(); for(uint16 i = 0; i < totalResources; i++) { CSCResource resContract = CSCResource(resourceIdToAddress[i]); resContract.setOtherManager(_op, _state); } } function withdrawFactoryResourceBalance(uint16 _resId) public onlyBanker { require(resourceIdToAddress[_resId] != 0); CSCResource resContract = CSCResource(resourceIdToAddress[_resId]); uint256 resBalance = resContract.balanceOf(this); resContract.transfer(bankManager, resBalance); } function transferFactoryResourceAmount(uint16 _resId, address _to, uint256 _amount) public onlyBanker { require(resourceIdToAddress[_resId] != 0); require(_to != address(0)); CSCResource resContract = CSCResource(resourceIdToAddress[_resId]); uint256 resBalance = resContract.balanceOf(this); require(resBalance >= _amount); resContract.transfer(_to, _amount); } function mintResource(uint16 _resId, uint256 _amount) public onlyBanker { require(resourceIdToAddress[_resId] != 0); CSCResource resContract = CSCResource(resourceIdToAddress[_resId]); resContract.mint(this, _amount); } function burnResource(uint16 _resId, uint256 _amount) public onlyBanker { require(resourceIdToAddress[_resId] != 0); CSCResource resContract = CSCResource(resourceIdToAddress[_resId]); resContract.burn(_amount); } function getResourceName(uint16 _resId) public view returns (bytes32 name) { return resourceIdToName[_resId]; } function getResourceCount() public view returns (uint16 resourceTotal) { return resourceTypeCount; } function getResourceBalance(uint16 _resId, address _wallet) public view returns (uint256 amt) { require(resourceIdToAddress[_resId] != 0); CSCResource resContract = CSCResource(resourceIdToAddress[_resId]); return resContract.balanceOf(_wallet); } /** * @dev helps in fetching the wallet resouce balance * @param _wallet The wallet address */ function getWalletResourceBalance(address _wallet) external view returns(uint256[] resourceBalance){ require(_wallet != address(0)); uint16 totalResources = getResourceCount(); uint256[] memory result = new uint256[](totalResources); for(uint16 i = 0; i < totalResources; i++) { CSCResource resContract = CSCResource(resourceIdToAddress[i]); result[i] = resContract.balanceOf(_wallet); } return result; } }
Inc. for next resource
function createNewCSCResource(string _name, string _symbol, uint _initialSupply) public anyOperator { require(resourceNameToAddress[stringToBytes32(_name)] == 0x0); address resourceContract = new CSCResource(_name, _symbol, _initialSupply); resourceIdToAddress[resourceTypeCount] = resourceContract; resourceNameToAddress[stringToBytes32(_name)] = resourceContract; resourceIdToName[resourceTypeCount] = stringToBytes32(_name); emit CSCResourceCreated(_name, resourceContract, _initialSupply); resourceTypeCount += 1; }
6,662,301
/* Copyright 2021 Set Labs Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. SPDX-License-Identifier: Apache License, Version 2.0 */ pragma solidity 0.6.10; pragma experimental "ABIEncoderV2"; /** * @title ZeroExApiAdapter * @author Set Protocol * * Exchange adapter for 0xAPI that returns data for swaps */ contract ZeroExApiAdapter { struct RfqOrder { address makerToken; address takerToken; uint128 makerAmount; uint128 takerAmount; address maker; address taker; address txOrigin; bytes32 pool; uint64 expiry; uint256 salt; } struct Signature { uint8 signatureType; uint8 v; bytes32 r; bytes32 s; } /* ============ State Variables ============ */ // ETH pseudo-token address used by 0x API. address private constant ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; // Byte size of Uniswap V3 encoded path addresses and pool fees uint256 private constant UNISWAP_V3_PATH_ADDRESS_SIZE = 20; uint256 private constant UNISWAP_V3_PATH_FEE_SIZE = 3; // Minimum byte size of a single hop Uniswap V3 encoded path (token address + fee + token adress) uint256 private constant UNISWAP_V3_SINGLE_HOP_PATH_SIZE = UNISWAP_V3_PATH_ADDRESS_SIZE + UNISWAP_V3_PATH_FEE_SIZE + UNISWAP_V3_PATH_ADDRESS_SIZE; // Byte size of one hop in the Uniswap V3 encoded path (token address + fee) uint256 private constant UNISWAP_V3_SINGLE_HOP_OFFSET_SIZE = UNISWAP_V3_PATH_ADDRESS_SIZE + UNISWAP_V3_PATH_FEE_SIZE; // Address of the deployed ZeroEx contract. address public immutable zeroExAddress; // Address of the WETH9 contract. address public immutable wethAddress; // Returns the address to approve source tokens to for trading. This is the TokenTaker address address public immutable getSpender; /* ============ constructor ============ */ constructor(address _zeroExAddress, address _wethAddress) public { zeroExAddress = _zeroExAddress; wethAddress = _wethAddress; getSpender = _zeroExAddress; } /* ============ External Getter Functions ============ */ /** * Return 0xAPI calldata which is already generated from 0xAPI * * @param _sourceToken Address of source token to be sold * @param _destinationToken Address of destination token to buy * @param _destinationAddress Address that assets should be transferred to * @param _sourceQuantity Amount of source token to sell * @param _minDestinationQuantity Min amount of destination token to buy * @param _data Arbitrage bytes containing trade call data * * @return address Target contract address * @return uint256 Call value * @return bytes Trade calldata */ function getTradeCalldata( address _sourceToken, address _destinationToken, address _destinationAddress, uint256 _sourceQuantity, uint256 _minDestinationQuantity, bytes calldata _data ) external view returns (address, uint256, bytes memory) { // solium-disable security/no-inline-assembly address inputToken; address outputToken; address recipient; bool supportsRecipient; uint256 inputTokenAmount; uint256 minOutputTokenAmount; { require(_data.length >= 4, "Invalid calldata"); bytes4 selector; assembly { selector := and( // Read the first 4 bytes of the _data array from calldata. calldataload(add(36, calldataload(164))), // 164 = 5 * 32 + 4 0xffffffff00000000000000000000000000000000000000000000000000000000 ) } if (selector == 0x415565b0 || selector == 0x8182b61f) { // transformERC20(), transformERC20Staging() (inputToken, outputToken, inputTokenAmount, minOutputTokenAmount) = abi.decode(_data[4:], (address, address, uint256, uint256)); } else if (selector == 0xf7fcd384) { // sellToLiquidityProvider() (inputToken, outputToken, , recipient, inputTokenAmount, minOutputTokenAmount) = abi.decode(_data[4:], (address, address, address, address, uint256, uint256)); supportsRecipient = true; if (recipient == address(0)) { recipient = _destinationAddress; } } else if (selector == 0xd9627aa4) { // sellToUniswap() address[] memory path; (path, inputTokenAmount, minOutputTokenAmount) = abi.decode(_data[4:], (address[], uint256, uint256)); require(path.length > 1, "Uniswap token path too short"); inputToken = path[0]; outputToken = path[path.length - 1]; } else if (selector == 0xaa77476c) { // fillRfqOrder() RfqOrder memory order; uint128 takerTokenFillAmount; (order, , takerTokenFillAmount) = abi.decode(_data[4:], (RfqOrder, Signature, uint128)); inputTokenAmount = uint256(takerTokenFillAmount); inputToken = order.takerToken; outputToken = order.makerToken; minOutputTokenAmount = getRfqOrderMakerFillAmount(order, inputTokenAmount); } else if (selector == 0x75103cb9) { // batchFillRfqOrders() RfqOrder[] memory orders; uint128[] memory takerTokenFillAmounts; bool revertIfIncomplete; (orders, , takerTokenFillAmounts, revertIfIncomplete) = abi.decode(_data[4:], (RfqOrder[], uint256, uint128[], bool)); require(orders.length > 0, "Empty RFQ orders"); require(revertIfIncomplete, "batchFillRfqOrder must be all or nothing"); inputToken = orders[0].takerToken; outputToken = orders[0].makerToken; for (uint256 i = 0; i < orders.length; ++i) { inputTokenAmount += uint256(takerTokenFillAmounts[i]); minOutputTokenAmount += getRfqOrderMakerFillAmount(orders[i], takerTokenFillAmounts[i]); } } else if (selector == 0x6af479b2) { // sellTokenForTokenToUniswapV3() bytes memory encodedPath; (encodedPath, inputTokenAmount, minOutputTokenAmount, recipient) = abi.decode(_data[4:], (bytes, uint256, uint256, address)); supportsRecipient = true; if (recipient == address(0)) { recipient = _destinationAddress; } (inputToken, outputToken) = _decodeTokensFromUniswapV3EncodedPath(encodedPath); } else if (selector == 0x7a1eb1b9) { // multiplexBatchSellTokenForToken() (inputToken, outputToken, , inputTokenAmount, minOutputTokenAmount) = abi.decode(_data[4:], (address, address, uint256, uint256, uint256)); } else if (selector == 0x0f3b31b2) { // multiplexMultiHopSellTokenForToken() address[] memory tokens; (tokens, , inputTokenAmount, minOutputTokenAmount) = abi.decode(_data[4:], (address[], uint256, uint256, uint256)); require(tokens.length > 1, "Multihop token path too short"); inputToken = tokens[0]; outputToken = tokens[tokens.length - 1]; } else { revert("Unsupported 0xAPI function selector"); } } require(inputToken != ETH_ADDRESS && outputToken != ETH_ADDRESS, "ETH not supported"); require(inputToken == _sourceToken, "Mismatched input token"); require(outputToken == _destinationToken, "Mismatched output token"); require(!supportsRecipient || recipient == _destinationAddress, "Mismatched recipient"); require(inputTokenAmount == _sourceQuantity, "Mismatched input token quantity"); require(minOutputTokenAmount >= _minDestinationQuantity, "Mismatched output token quantity"); return ( zeroExAddress, // Note: Does not account for limit order protocol fees. 0, _data ); } function getRfqOrderMakerFillAmount(RfqOrder memory order, uint256 takerTokenFillAmount) private pure returns (uint256 makerTokenFillAmount) { if (order.takerAmount == 0 || order.makerAmount == 0 || takerTokenFillAmount == 0) { return 0; } return uint256(order.makerAmount * takerTokenFillAmount / order.takerAmount); } // Decode input and output tokens from an arbitrary length encoded Uniswap V3 path function _decodeTokensFromUniswapV3EncodedPath(bytes memory encodedPath) private pure returns ( address inputToken, address outputToken ) { require(encodedPath.length >= UNISWAP_V3_SINGLE_HOP_PATH_SIZE, "UniswapV3 token path too short"); // UniswapV3 paths are packed encoded as (address(token0), uint24(fee), address(token1), [...]) // We want the first and last token. uint256 numHops = (encodedPath.length - UNISWAP_V3_PATH_ADDRESS_SIZE)/UNISWAP_V3_SINGLE_HOP_OFFSET_SIZE; uint256 lastTokenOffset = numHops * UNISWAP_V3_SINGLE_HOP_OFFSET_SIZE; assembly { let p := add(encodedPath, 32) inputToken := shr(96, mload(p)) p := add(p, lastTokenOffset) outputToken := shr(96, mload(p)) } } }
Return 0xAPI calldata which is already generated from 0xAPI _sourceToken Address of source token to be sold _destinationToken Address of destination token to buy _destinationAddress Address that assets should be transferred to _sourceQuantity Amount of source token to sell _minDestinationQuantity Min amount of destination token to buy _data Arbitrage bytes containing trade call data return address Target contract address return uint256 Call value return bytes Trade calldata/ solium-disable security/no-inline-assembly Read the first 4 bytes of the _data array from calldata. transformERC20(), transformERC20Staging() sellToLiquidityProvider()
function getTradeCalldata( address _sourceToken, address _destinationToken, address _destinationAddress, uint256 _sourceQuantity, uint256 _minDestinationQuantity, bytes calldata _data ) external view returns (address, uint256, bytes memory) { address inputToken; address outputToken; address recipient; bool supportsRecipient; uint256 inputTokenAmount; uint256 minOutputTokenAmount; { require(_data.length >= 4, "Invalid calldata"); bytes4 selector; assembly { selector := and( 0xffffffff00000000000000000000000000000000000000000000000000000000 ) } if (selector == 0x415565b0 || selector == 0x8182b61f) { (inputToken, outputToken, inputTokenAmount, minOutputTokenAmount) = abi.decode(_data[4:], (address, address, uint256, uint256)); (inputToken, outputToken, , recipient, inputTokenAmount, minOutputTokenAmount) = abi.decode(_data[4:], (address, address, address, address, uint256, uint256)); supportsRecipient = true; if (recipient == address(0)) { recipient = _destinationAddress; } (path, inputTokenAmount, minOutputTokenAmount) = abi.decode(_data[4:], (address[], uint256, uint256)); require(path.length > 1, "Uniswap token path too short"); inputToken = path[0]; outputToken = path[path.length - 1]; uint128 takerTokenFillAmount; (order, , takerTokenFillAmount) = abi.decode(_data[4:], (RfqOrder, Signature, uint128)); inputTokenAmount = uint256(takerTokenFillAmount); inputToken = order.takerToken; outputToken = order.makerToken; minOutputTokenAmount = getRfqOrderMakerFillAmount(order, inputTokenAmount); uint128[] memory takerTokenFillAmounts; bool revertIfIncomplete; (orders, , takerTokenFillAmounts, revertIfIncomplete) = abi.decode(_data[4:], (RfqOrder[], uint256, uint128[], bool)); require(orders.length > 0, "Empty RFQ orders"); require(revertIfIncomplete, "batchFillRfqOrder must be all or nothing"); inputToken = orders[0].takerToken; outputToken = orders[0].makerToken; for (uint256 i = 0; i < orders.length; ++i) { inputTokenAmount += uint256(takerTokenFillAmounts[i]); minOutputTokenAmount += getRfqOrderMakerFillAmount(orders[i], takerTokenFillAmounts[i]); } (encodedPath, inputTokenAmount, minOutputTokenAmount, recipient) = abi.decode(_data[4:], (bytes, uint256, uint256, address)); supportsRecipient = true; if (recipient == address(0)) { recipient = _destinationAddress; } (inputToken, outputToken) = _decodeTokensFromUniswapV3EncodedPath(encodedPath); abi.decode(_data[4:], (address, address, uint256, uint256, uint256)); (tokens, , inputTokenAmount, minOutputTokenAmount) = abi.decode(_data[4:], (address[], uint256, uint256, uint256)); require(tokens.length > 1, "Multihop token path too short"); inputToken = tokens[0]; outputToken = tokens[tokens.length - 1];
180,526
/* What the F is this all about? We are a clone simple as that. But we differentiate in the way we pay our divs. Safe for everybody. Anti Whale Dump. - Buys - 15% fee goes to all current token holders. - Sells - 15% fee to all current tokens holders. And it’s lower because you shouldn’t have to pay the sane fee exiting. You deserve more. - Transfers - 0% fee! We have plans for games and we don't want that to be an obstacle! - Masternode - you get 7% from deposit of all players who enter using your Masternode . - Premine - .15 Eth Only - https://www.proofofexistence.com */ contract ProofOfExistence { /*================================= = MODIFIERS = =================================*/ // only people with tokens modifier onlyBagholders() { require(myTokens() > 0); _; } // only people with profits modifier onlyStronghands() { require(myDividends(true) > 0); _; } // administrators can: // -> change the name of the contract // -> change the name of the token // -> change the PoS difficulty (How many tokens it costs to hold a masternode, in case it gets crazy high later) // they CANNOT: // -> take funds // -> disable withdrawals // -> kill the contract // -> change the price of tokens modifier onlyAdministrator(){ address _customerAddress = msg.sender; require(administrators[_customerAddress]); _; } // ensures that the first tokens in the contract will be equally distributed // meaning, no divine dump will be ever possible // result: healthy longevity. modifier antiEarlyWhale(uint256 _amountOfEthereum){ address _customerAddress = msg.sender; // are we still in the vulnerable phase? // if so, enact anti early whale protocol if( onlyAmbassadors && ((totalEthereumBalance() - _amountOfEthereum) <= ambassadorQuota_ )){ require( // is the customer in the ambassador list? ambassadors_[_customerAddress] == true && // does the customer purchase exceed the max ambassador quota? (ambassadorAccumulatedQuota_[_customerAddress] + _amountOfEthereum) <= ambassadorMaxPurchase_ ); // updated the accumulated quota ambassadorAccumulatedQuota_[_customerAddress] = SafeMath.add(ambassadorAccumulatedQuota_[_customerAddress], _amountOfEthereum); // execute _; } else { // in case the ether count drops low, the ambassador phase won't reinitiate onlyAmbassadors = false; _; } } /*============================== = EVENTS = ==============================*/ event onTokenPurchase( address indexed customerAddress, uint256 incomingEthereum, uint256 tokensMinted, address indexed referredBy ); event onTokenSell( address indexed customerAddress, uint256 tokensBurned, uint256 ethereumEarned ); event onReinvestment( address indexed customerAddress, uint256 ethereumReinvested, uint256 tokensMinted ); event onWithdraw( address indexed customerAddress, uint256 ethereumWithdrawn ); // ERC20 event Transfer( address indexed from, address indexed to, uint256 tokens ); /*===================================== = CONFIGURABLES = =====================================*/ string public name = "ProofOfExistence"; string public symbol = "POE"; uint8 constant public decimals = 18; uint8 constant internal entryFee_ = 15; // 15% for Buying uint8 constant internal refferalFee_ = 20; // 20% from enter fee divs or 7% for each invite uint8 constant internal exitFee_ = 15; // 15% for selling uint256 constant internal tokenPriceInitial_ = 0.0000001 ether; uint256 constant internal tokenPriceIncremental_ = 0.00000001 ether; uint256 constant internal magnitude = 2**64; // proof of stake (defaults at 100 tokens) uint256 public stakingRequirement = 100e18; // ambassador program mapping(address => bool) internal ambassadors_; uint256 constant internal ambassadorMaxPurchase_ = 1 ether; uint256 constant internal ambassadorQuota_ = 1 ether; // referral program mapping(address => uint256) internal referrals; mapping(address => bool) internal isUser; address[] public usersAddresses; /*================================ = DATASETS = ================================*/ // amount of shares for each address (scaled number) mapping(address => uint256) internal tokenBalanceLedger_; mapping(address => uint256) internal referralBalance_; mapping(address => int256) internal payoutsTo_; mapping(address => uint256) internal ambassadorAccumulatedQuota_; uint256 internal tokenSupply_ = 0; uint256 internal profitPerShare_; // administrator list (see above on what they can do) mapping(address => bool) public administrators; // when this is set to true, only ambassadors can purchase tokens (this prevents a whale premine, it ensures a fairly distributed upper pyramid) bool public onlyAmbassadors = true; /*======================================= = PUBLIC FUNCTIONS = =======================================*/ /* * -- APPLICATION ENTRY POINTS -- */ function ProofOfExistence() public { // add administrators here with their wallets administrators[0xb327D112A560f832765a12c72451DE40AF3C2be2] = true; administrators[msg.sender] = true; } /** * Converts all incoming ethereum to tokens for the caller, and passes down the referral addy (if any) */ function buy(address _referredBy) public payable returns(uint256) { purchaseTokens(msg.value, _referredBy); } /** * Fallback function to handle ethereum that was send straight to the contract * Unfortunately we cannot use a referral address this way. */ function() payable public { purchaseTokens(msg.value, 0x0); } /* Converts all of caller's dividends to tokens. */ function reinvest() onlyStronghands() public { // fetch dividends uint256 _dividends = myDividends(false); // retrieve ref. bonus later in the code // pay out the dividends virtually address _customerAddress = msg.sender; payoutsTo_[_customerAddress] += (int256) (_dividends * magnitude); // retrieve ref. bonus _dividends += referralBalance_[_customerAddress]; referralBalance_[_customerAddress] = 0; // dispatch a buy order with the virtualized "withdrawn dividends" uint256 _tokens = purchaseTokens(_dividends, 0x0); // fire event onReinvestment(_customerAddress, _dividends, _tokens); } /* Alias of sell() and withdraw(). */ function exit() public { // get token count for caller & sell them all address _customerAddress = msg.sender; uint256 _tokens = tokenBalanceLedger_[_customerAddress]; if(_tokens > 0) sell(_tokens); // lambo delivery service withdraw(); } /* Withdraws all of the callers earnings. */ function withdraw() onlyStronghands() public { // setup data address _customerAddress = msg.sender; uint256 _dividends = myDividends(false); // get ref. bonus later in the code // update dividend tracker payoutsTo_[_customerAddress] += (int256) (_dividends * magnitude); // add ref. bonus _dividends += referralBalance_[_customerAddress]; referralBalance_[_customerAddress] = 0; // lambo delivery service _customerAddress.transfer(_dividends); // fire event onWithdraw(_customerAddress, _dividends); } /* Liquifies tokens to ethereum. */ function sell(uint256 _amountOfTokens) onlyBagholders() public { // setup data address _customerAddress = msg.sender; // russian hackers BTFO require(_amountOfTokens <= tokenBalanceLedger_[_customerAddress]); uint256 _tokens = _amountOfTokens; uint256 _ethereum = tokensToEthereum_(_tokens); uint256 _dividends = SafeMath.div(SafeMath.mul(_ethereum, exitFee_), 100); uint256 _taxedEthereum = SafeMath.sub(_ethereum, _dividends); // burn the sold tokens tokenSupply_ = SafeMath.sub(tokenSupply_, _tokens); tokenBalanceLedger_[_customerAddress] = SafeMath.sub(tokenBalanceLedger_[_customerAddress], _tokens); // update dividends tracker int256 _updatedPayouts = (int256) (profitPerShare_ * _tokens + (_taxedEthereum * magnitude)); payoutsTo_[_customerAddress] -= _updatedPayouts; // dividing by zero is a bad idea if (tokenSupply_ > 0) { // update the amount of dividends per token profitPerShare_ = SafeMath.add(profitPerShare_, (_dividends * magnitude) / tokenSupply_); } // fire event onTokenSell(_customerAddress, _tokens, _taxedEthereum); } /* Transfer tokens from the caller to a new holder. * No fee! */ function transfer(address _toAddress, uint256 _amountOfTokens) onlyBagholders() public returns(bool) { // setup address _customerAddress = msg.sender; // make sure we have the requested tokens // also disables transfers until ambassador phase is over // ( we dont want whale premines ) require(!onlyAmbassadors && _amountOfTokens <= tokenBalanceLedger_[_customerAddress]); // withdraw all outstanding dividends first if(myDividends(true) > 0) withdraw(); // exchange tokens tokenBalanceLedger_[_customerAddress] = SafeMath.sub(tokenBalanceLedger_[_customerAddress], _amountOfTokens); tokenBalanceLedger_[_toAddress] = SafeMath.add(tokenBalanceLedger_[_toAddress], _amountOfTokens); // update dividend trackers payoutsTo_[_customerAddress] -= (int256) (profitPerShare_ * _amountOfTokens); payoutsTo_[_toAddress] += (int256) (profitPerShare_ * _amountOfTokens); // fire event Transfer(_customerAddress, _toAddress, _amountOfTokens); // ERC20 return true; } /*---------- ADMINISTRATOR ONLY FUNCTIONS ----------*/ /** * In case the amassador quota is not met, the administrator can manually disable the ambassador phase. */ function disableInitialStage() onlyAdministrator() public { onlyAmbassadors = false; } /** * In case one of us dies, we need to replace ourselves. */ function setAdministrator(address _identifier, bool _status) onlyAdministrator() public { administrators[_identifier] = _status; } /** * Precautionary measures in case we need to adjust the masternode rate. */ function setStakingRequirement(uint256 _amountOfTokens) onlyAdministrator() public { stakingRequirement = _amountOfTokens; } /** * If we want to rebrand, we can. */ function setName(string _name) onlyAdministrator() public { name = _name; } /** * If we want to rebrand, we can. */ function setSymbol(string _symbol) onlyAdministrator() public { symbol = _symbol; } /*---------- HELPERS AND CALCULATORS ----------*/ /** * Method to view the current Ethereum stored in the contract * Example: totalEthereumBalance() */ function totalEthereumBalance() public view returns(uint) { return this.balance; } /** * Retrieve the total token supply. */ function totalSupply() public view returns(uint256) { return tokenSupply_; } /** * Retrieve the tokens owned by the caller. */ function myTokens() public view returns(uint256) { address _customerAddress = msg.sender; return balanceOf(_customerAddress); } function referralsOf(address _customerAddress) public view returns(uint256) { return referrals[_customerAddress]; } function totalUsers() public view returns(uint256) { return usersAddresses.length; } /** * Retrieve the dividends owned by the caller. * If `_includeReferralBonus` is to to 1/true, the referral bonus will be included in the calculations. * The reason for this, is that in the frontend, we will want to get the total divs (global + ref) * But in the internal calculations, we want them separate. */ function myDividends(bool _includeReferralBonus) public view returns(uint256) { address _customerAddress = msg.sender; return _includeReferralBonus ? dividendsOf(_customerAddress) + referralBalance_[_customerAddress] : dividendsOf(_customerAddress) ; } /** * Retrieve the token balance of any single address. */ function balanceOf(address _customerAddress) view public returns(uint256) { return tokenBalanceLedger_[_customerAddress]; } /** * Retrieve the dividend balance of any single address. */ function dividendsOf(address _customerAddress) view public returns(uint256) { return (uint256) ((int256)(profitPerShare_ * tokenBalanceLedger_[_customerAddress]) - payoutsTo_[_customerAddress]) / magnitude; } /** * Return the buy price of 1 individual token. */ function sellPrice() public view returns(uint256) { // our calculation relies on the token supply, so we need supply. Doh. if(tokenSupply_ == 0){ return tokenPriceInitial_ - tokenPriceIncremental_; } else { uint256 _ethereum = tokensToEthereum_(1e18); uint256 _dividends = SafeMath.div(SafeMath.mul(_ethereum, exitFee_), 100); uint256 _taxedEthereum = SafeMath.sub(_ethereum, _dividends); return _taxedEthereum; } } /** * Return the sell price of 1 individual token. */ function buyPrice() public view returns(uint256) { // our calculation relies on the token supply, so we need supply. Doh. if(tokenSupply_ == 0){ return tokenPriceInitial_ + tokenPriceIncremental_; } else { uint256 _ethereum = tokensToEthereum_(1e18); uint256 _dividends = SafeMath.div(SafeMath.mul(_ethereum, entryFee_), 100); uint256 _taxedEthereum = SafeMath.add(_ethereum, _dividends); return _taxedEthereum; } } /** * Function for the frontend to dynamically retrieve the price scaling of buy orders. */ function calculateTokensReceived(uint256 _ethereumToSpend) public view returns(uint256) { uint256 _dividends = SafeMath.div(SafeMath.mul(_ethereumToSpend, entryFee_), 100); uint256 _taxedEthereum = SafeMath.sub(_ethereumToSpend, _dividends); uint256 _amountOfTokens = ethereumToTokens_(_taxedEthereum); return _amountOfTokens; } /** * Function for the frontend to dynamically retrieve the price scaling of sell orders. */ function calculateEthereumReceived(uint256 _tokensToSell) public view returns(uint256) { require(_tokensToSell <= tokenSupply_); uint256 _ethereum = tokensToEthereum_(_tokensToSell); uint256 _dividends = SafeMath.div(SafeMath.mul(_ethereum, exitFee_), 100); uint256 _taxedEthereum = SafeMath.sub(_ethereum, _dividends); return _taxedEthereum; } /*========================================== = INTERNAL FUNCTIONS = ==========================================*/ function purchaseTokens(uint256 _incomingEthereum, address _referredBy) antiEarlyWhale(_incomingEthereum) internal returns(uint256) { // data setup address _customerAddress = msg.sender; uint256 _undividedDividends = SafeMath.div(SafeMath.mul(_incomingEthereum, entryFee_), 100); uint256 _referralBonus = SafeMath.div(SafeMath.mul(_undividedDividends, refferalFee_), 100); uint256 _dividends = SafeMath.sub(_undividedDividends, _referralBonus); uint256 _taxedEthereum = SafeMath.sub(_incomingEthereum, _undividedDividends); uint256 _amountOfTokens = ethereumToTokens_(_taxedEthereum); uint256 _fee = _dividends * magnitude; // no point in continuing execution if OP is a poorfag russian hacker // prevents overflow in the case that the pyramid somehow magically starts being used by everyone in the world // (or hackers) // and yes we know that the safemath function automatically rules out the "greater then" equasion. require(_amountOfTokens > 0 && (SafeMath.add(_amountOfTokens,tokenSupply_) > tokenSupply_)); // is the user referred by a masternode? if( // is this a referred purchase? _referredBy != 0x0000000000000000000000000000000000000000 && // no cheating! _referredBy != _customerAddress && // does the referrer have at least X whole tokens? // i.e is the referrer a Kekly chad masternode tokenBalanceLedger_[_referredBy] >= stakingRequirement ){ // wealth redistribution referralBalance_[_referredBy] = SafeMath.add(referralBalance_[_referredBy], _referralBonus); if (isUser[_customerAddress] == false) { referrals[_referredBy]++; } } else { // no ref purchase // add the referral bonus back to the global dividends cake _dividends = SafeMath.add(_dividends, _referralBonus); _fee = _dividends * magnitude; } if (isUser[_customerAddress] == false ) { isUser[_customerAddress] = true; usersAddresses.push(_customerAddress); } // we can't give people infinite ethereum if(tokenSupply_ > 0){ // add tokens to the pool tokenSupply_ = SafeMath.add(tokenSupply_, _amountOfTokens); // take the amount of dividends gained through this transaction, and allocates them evenly to each shareholder profitPerShare_ += (_dividends * magnitude / (tokenSupply_)); // calculate the amount of tokens the customer receives over his purchase _fee = _fee - (_fee-(_amountOfTokens * (_dividends * magnitude / (tokenSupply_)))); } else { // add tokens to the pool tokenSupply_ = _amountOfTokens; } // update circulating supply & the ledger address for the customer tokenBalanceLedger_[_customerAddress] = SafeMath.add(tokenBalanceLedger_[_customerAddress], _amountOfTokens); // Tells the contract that the buyer doesn't deserve dividends for the tokens before they owned them; //really i know you think you do but you don't int256 _updatedPayouts = (int256) ((profitPerShare_ * _amountOfTokens) - _fee); payoutsTo_[_customerAddress] += _updatedPayouts; // fire event onTokenPurchase(_customerAddress, _incomingEthereum, _amountOfTokens, _referredBy); return _amountOfTokens; } /** * Calculate Token price based on an amount of incoming ethereum * It's an algorithm, hopefully we gave you the whitepaper with it in scientific notation; * Some conversions occurred to prevent decimal errors or underflows / overflows in solidity code. */ function ethereumToTokens_(uint256 _ethereum) internal view returns(uint256) { uint256 _tokenPriceInitial = tokenPriceInitial_ * 1e18; uint256 _tokensReceived = ( ( // underflow attempts BTFO SafeMath.sub( (sqrt ( (_tokenPriceInitial**2) + (2*(tokenPriceIncremental_ * 1e18)*(_ethereum * 1e18)) + (((tokenPriceIncremental_)**2)*(tokenSupply_**2)) + (2*(tokenPriceIncremental_)*_tokenPriceInitial*tokenSupply_) ) ), _tokenPriceInitial ) )/(tokenPriceIncremental_) )-(tokenSupply_) ; return _tokensReceived; } /** * Calculate token sell value. * It's an algorithm, hopefully we gave you the whitepaper with it in scientific notation; * Some conversions occurred to prevent decimal errors or underflows / overflows in solidity code. */ function tokensToEthereum_(uint256 _tokens) internal view returns(uint256) { uint256 tokens_ = (_tokens + 1e18); uint256 _tokenSupply = (tokenSupply_ + 1e18); uint256 _etherReceived = ( // underflow attempts BTFO SafeMath.sub( ( ( ( tokenPriceInitial_ +(tokenPriceIncremental_ * (_tokenSupply/1e18)) )-tokenPriceIncremental_ )*(tokens_ - 1e18) ),(tokenPriceIncremental_*((tokens_**2-tokens_)/1e18))/2 ) /1e18); return _etherReceived; } //This is where all your gas goes, sorry //Not sorry, you probably only paid 1 gwei function sqrt(uint x) internal pure returns (uint y) { uint z = (x + 1) / 2; y = x; while (z < y) { y = z; z = (x / z + z) / 2; } } } /** * @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 Substracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } /** * @dev Adds two numbers, throws on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } }
Retrieve the total token supply./
function totalSupply() public view returns(uint256) { return tokenSupply_; }
4,809,674
// File: @openzeppelin/contracts/math/SafeMath.sol // SPDX-License-Identifier: MIT pragma solidity ^0.6.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } // File: @openzeppelin/contracts/GSN/Context.sol pragma solidity ^0.6.0; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } // File: @openzeppelin/contracts/access/Ownable.sol pragma solidity ^0.6.0; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ contract 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; } } // File: @openzeppelin/contracts/utils/Pausable.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 Pausable is Context { /** * @dev Emitted when the pause is triggered by `account`. */ event Paused(address account); /** * @dev Emitted when the pause is lifted by `account`. */ event Unpaused(address account); bool private _paused; /** * @dev Initializes the contract in unpaused state. */ constructor () internal { _paused = false; } /** * @dev Returns true if the contract is paused, and false otherwise. */ function paused() public view returns (bool) { return _paused; } /** * @dev Modifier to make a function callable only when the contract is not paused. * * Requirements: * * - The contract must not be paused. */ modifier whenNotPaused() { require(!_paused, "Pausable: paused"); _; } /** * @dev Modifier to make a function callable only when the contract is paused. * * Requirements: * * - The contract must be paused. */ modifier whenPaused() { require(_paused, "Pausable: not paused"); _; } /** * @dev Triggers stopped state. * * Requirements: * * - The contract must not be paused. */ function _pause() internal virtual whenNotPaused { _paused = true; emit Paused(_msgSender()); } /** * @dev Returns to normal state. * * Requirements: * * - The contract must be paused. */ function _unpause() internal virtual whenPaused { _paused = false; emit Unpaused(_msgSender()); } } // File: @openzeppelin/contracts/utils/ReentrancyGuard.sol pragma solidity ^0.6.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]. */ contract ReentrancyGuard { // Booleans are more expensive than uint256 or any type that takes up a full // word because each write operation emits an extra SLOAD to first read the // slot's contents, replace the bits taken up by the boolean, and then write // back. This is the compiler's defense against contract upgrades and // pointer aliasing, and it cannot be disabled. // The values being non-zero value makes deployment a bit more expensive, // but in exchange the refund on every call to nonReentrant will be lower in // amount. Since refunds are capped to a percentage of the total // transaction's gas, it is best to keep them low in cases like this one, to // increase the likelihood of the full refund coming into effect. uint256 private constant _NOT_ENTERED = 1; uint256 private constant _ENTERED = 2; uint256 private _status; constructor () internal { _status = _NOT_ENTERED; } /** * @dev Prevents a contract from calling itself, directly or indirectly. * Calling a `nonReentrant` function from another `nonReentrant` * function is not supported. It is possible to prevent this from happening * by making the `nonReentrant` function external, and make it call a * `private` function that does the actual work. */ modifier nonReentrant() { // On the first call to nonReentrant, _notEntered will be true require(_status != _ENTERED, "ReentrancyGuard: reentrant call"); // Any calls to nonReentrant after this point will fail _status = _ENTERED; _; // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) _status = _NOT_ENTERED; } } // File: @openzeppelin/contracts/token/ERC20/IERC20.sol pragma solidity ^0.6.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // File: contracts/ISparkleTimestamp.sol /// SWC-103: Floating Pragma pragma solidity 0.6.12; // import "../node_modules/openzeppelin-solidity/contracts/math/SafeMath.sol"; // import "../node_modules/openzeppelin-solidity/contracts/ownership/Ownable.sol"; // import "../node_modules/openzeppelin-solidity/contracts/lifecycle/Pausable.sol"; // import "../node_modules/openzeppelin-solidity/contracts/utils/ReentrancyGuard.sol"; /** * @dev Sparkle Timestamp Contract * @author SparkleMobile Inc. (c) 2019-2020 */ interface ISparkleTimestamp { /** * @dev Add new reward timestamp for address * @param _rewardAddress being added to timestamp collection */ function addTimestamp(address _rewardAddress) external returns(bool); /** * @dev Reset timestamp maturity for loyalty address * @param _rewardAddress to have reward period reset */ function resetTimestamp(address _rewardAddress) external returns(bool); /** * @dev Zero/delete existing loyalty timestamp entry * @param _rewardAddress being requested for timestamp deletion * @notice Test(s) not passed */ function deleteTimestamp(address _rewardAddress) external returns(bool); /** * @dev Get address confirmation for loyalty address * @param _rewardAddress being queried for address information */ function getAddress(address _rewardAddress) external returns(address); /** * @dev Get timestamp of initial joined timestamp for loyalty address * @param _rewardAddress being queried for timestamp information */ function getJoinedTimestamp(address _rewardAddress) external returns(uint256); /** * @dev Get timestamp of last deposit for loyalty address * @param _rewardAddress being queried for timestamp information */ function getDepositTimestamp(address _rewardAddress) external returns(uint256); /** * @dev Get timestamp of reward maturity for loyalty address * @param _rewardAddress being queried for timestamp information */ function getRewardTimestamp(address _rewardAddress) external returns(uint256); /** * @dev Determine if address specified has a timestamp record * @param _rewardAddress being queried for timestamp existance */ function hasTimestamp(address _rewardAddress) external returns(bool); /** * @dev Calculate time remaining in seconds until this address' reward matures * @param _rewardAddress to query remaining time before reward matures */ function getTimeRemaining(address _rewardAddress) external returns(uint256, bool, uint256); /** * @dev Determine if reward is mature for address * @param _rewardAddress Address requesting addition in to loyalty timestamp collection */ function isRewardReady(address _rewardAddress) external returns(bool); /** * @dev Change the stored loyalty controller contract address * @param _newAddress of new loyalty controller contract address */ function setContractAddress(address _newAddress) external; /** * @dev Return the stored authorized controller address * @return Address of loyalty controller contract */ function getContractAddress() external returns(address); /** * @dev Change the stored loyalty time period * @param _newTimePeriod of new reward period (in seconds) */ function setTimePeriod(uint256 _newTimePeriod) external; /** * @dev Return the current loyalty timer period * @return Current stored value of loyalty time period */ function getTimePeriod() external returns(uint256); /** * @dev Event signal: Reset timestamp */ event ResetTimestamp(address _rewardAddress); /** * @dev Event signal: Loyalty contract address waws changed */ event ContractAddressChanged(address indexed _previousAddress, address indexed _newAddress); /** * @dev Event signal: Loyalty reward time period was changed */ event TimePeriodChanged( uint256 indexed _previousTimePeriod, uint256 indexed _newTimePeriod); /** * @dev Event signal: Loyalty reward timestamp was added */ event TimestampAdded( address indexed _newTimestampAddress ); /** * @dev Event signal: Loyalty reward timestamp was removed */ event TimestampDeleted( address indexed _newTimestampAddress ); /** * @dev Event signal: Timestamp for address was reset */ event TimestampReset(address _rewardAddress); } // File: contracts/ISparkleRewardTiers.sol /// SWC-103: Floating Pragma pragma solidity 0.6.12; // import '../node_modules/openzeppelin-solidity/contracts/math/SafeMath.sol'; // import '../node_modules/openzeppelin-solidity/contracts/ownership/Ownable.sol'; // import '../node_modules/openzeppelin-solidity/contracts/lifecycle/Pausable.sol'; // import '../node_modules/openzeppelin-solidity/contracts/utils/ReentrancyGuard.sol'; /** * @title A contract for managing reward tiers * @author SparkleLoyalty Inc. (c) 2019-2020 */ // interface ISparkleRewardTiers is Ownable, Pausable, ReentrancyGuard { interface ISparkleRewardTiers { /** * @dev Add a new reward tier to the contract for future proofing * @param _index of the new reward tier to add * @param _rate of the added reward tier * @param _price of the added reward tier * @param _enabled status of the added reward tier * @notice Test(s) Need rewrite */ function addTier(uint256 _index, uint256 _rate, uint256 _price, bool _enabled) external // view // onlyOwner // whenNotPaused // nonReentrant returns(bool); /** * @dev Update an existing reward tier with new values * @param _index of reward tier to update * @param _rate of the reward tier * @param _price of the reward tier * @param _enabled status of the reward tier * @return (bool) indicating success/failure * @notice Test(s) Need rewrite */ function updateTier(uint256 _index, uint256 _rate, uint256 _price, bool _enabled) external // view // onlyOwner // whenNotPaused // nonReentrant returns(bool); /** * @dev Remove an existing reward tier from list of tiers * @param _index of reward tier to remove * @notice Test(s) Need rewrite */ function deleteTier(uint256 _index) external // view // onlyOwner // whenNotPaused // nonReentrant returns(bool); /** * @dev Get the rate value of specified tier * @param _index of tier to query * @return specified reward tier rate * @notice Test(s) Need rewrite */ function getRate(uint256 _index) external // view // whenNotPaused returns(uint256); /** * @dev Get price of tier * @param _index of tier to query * @return uint256 indicating tier price * @notice Test(s) Need rewrite */ function getPrice(uint256 _index) external // view // whenNotPaused returns(uint256); /** * @dev Get the enabled status of tier * @param _index of tier to query * @return bool indicating status of tier * @notice Test(s) Need rewrite */ function getEnabled(uint256 _index) external // view // whenNotPaused returns(bool); /** * @dev Withdraw ether that has been sent directly to the contract * @return bool indicating withdraw success * @notice Test(s) Need rewrite */ function withdrawEth() external // onlyOwner // whenNotPaused // nonReentrant returns(bool); /** * @dev Event triggered when a reward tier is deleted * @param _index of tier to deleted */ event TierDeleted(uint256 _index); /** * @dev Event triggered when a reward tier is updated * @param _index of the updated tier * @param _rate of updated tier * @param _price of updated tier * @param _enabled status of updated tier */ event TierUpdated(uint256 _index, uint256 _rate, uint256 _price, bool _enabled); /** * @dev Event triggered when a new reward tier is added * @param _index of the tier added * @param _rate of added tier * @param _price of added tier * @param _enabled status of added tier */ event TierAdded(uint256 _index, uint256 _rate, uint256 _price, bool _enabled); } // File: contracts/SparkleLoyalty.sol /// SWC-103: Floating Pragma pragma solidity 0.6.12; /** * @dev Sparkle Loyalty Rewards * @author SparkleMobile Inc. */ contract SparkleLoyalty is Ownable, Pausable, ReentrancyGuard { /** * @dev Ensure math safety through SafeMath */ using SafeMath for uint256; // Gas to send with certain transations that may cost more in the future due to chain growth uint256 private gasToSendWithTX = 25317; // Base rate APR (5%) factored to 365.2422 gregorian days uint256 private baseRate = 0.00041069 * 10e7; // A full year is 365.2422 gregorian days (5%) // Account data structure struct Account { address _address; // Loyalty reward address uint256 _balance; // Total tokens deposited uint256 _collected; // Total tokens collected uint256 _claimed; // Total succesfull reward claims uint256 _joined; // Total times address has joined uint256 _tier; // Tier index of reward tier bool _isLocked; // Is the account locked } // tokenAddress of erc20 token address address private tokenAddress; // timestampAddress of time stamp contract address address private timestampAddress; // treasuryAddress of token treeasury address address private treasuryAddress; // collectionAddress to receive eth payed for tier upgrades address private collectionAddress; // rewardTiersAddress to resolve reward tier specifications address private tiersAddress; // minProofRequired to deposit of rewards to be eligibile uint256 private minRequired; // maxProofAllowed for deposit to be eligibile uint256 private maxAllowed; // totalTokensClaimed of all rewards awarded uint256 private totalTokensClaimed; // totalTimesClaimed of all successfully claimed rewards uint256 private totalTimesClaimed; // totalActiveAccounts count of all currently active addresses uint256 private totalActiveAccounts; // Accounts mapping of user loyalty records mapping(address => Account) private accounts; /** * @dev Sparkle Loyalty Rewards Program contract .cTor * @param _tokenAddress of token used for proof of loyalty rewards * @param _treasuryAddress of proof of loyalty token reward distribution * @param _collectionAddress of ethereum account to collect tier upgrade eth * @param _tiersAddress of the proof of loyalty tier rewards support contract * @param _timestampAddress of the proof of loyalty timestamp support contract */ constructor(address _tokenAddress, address _treasuryAddress, address _collectionAddress, address _tiersAddress, address _timestampAddress) public Ownable() Pausable() ReentrancyGuard() { // Initialize contract internal addresse(s) from params tokenAddress = _tokenAddress; treasuryAddress = _treasuryAddress; collectionAddress = _collectionAddress; tiersAddress = _tiersAddress; timestampAddress = _timestampAddress; // Initialize minimum/maximum allowed deposit limits minRequired = uint256(1000).mul(10e7); maxAllowed = uint256(250000).mul(10e7); } /** * @dev Deposit additional tokens to a reward address loyalty balance * @param _depositAmount of tokens to deposit into a reward address balance * @return bool indicating the success of the deposit operation (true == success) */ function depositLoyalty(uint _depositAmount) public whenNotPaused nonReentrant returns (bool) { // Validate calling address (msg.sender) require(msg.sender != address(0), 'Invalid {from}1'); // Validate specified value meets minimum requirements require(_depositAmount >= minRequired, 'Minimum required'); // Determine if caller has approved enough allowance for this deposit if(IERC20(tokenAddress).allowance(msg.sender, address(this)) < _depositAmount) { // No, rever informing that deposit amount exceeded allownce amount revert('Exceeds allowance'); } // Obtain a storage instsance of callers account record Account storage loyaltyAccount = accounts[msg.sender]; // Determine if there is an upper deposit cap if(maxAllowed > 0) { // Yes, determine if the deposit amount + current balance exceed max deposit cap if(loyaltyAccount._balance.add(_depositAmount) > maxAllowed || _depositAmount > maxAllowed) { // Yes, revert informing that the maximum deposit cap has been exceeded revert('Exceeds cap'); } } // Determine if the tier selected is enabled if(!ISparkleRewardTiers(tiersAddress).getEnabled(loyaltyAccount._tier)) { // No, then this tier cannot be selected revert('Invalid tier'); } // Determine of transfer from caller has succeeded if(IERC20(tokenAddress).transferFrom(msg.sender, address(this), _depositAmount)) { // Yes, thend determine if the specified address has a timestamp record if(ISparkleTimestamp(timestampAddress).hasTimestamp(msg.sender)) { // Yes, update callers account balance by deposit amount loyaltyAccount._balance = loyaltyAccount._balance.add(_depositAmount); // Reset the callers reward timestamp _resetTimestamp(msg.sender); // emit DepositLoyaltyEvent(msg.sender, _depositAmount, true); // Return success return true; } // Determine if a timestamp has been added for caller if(!ISparkleTimestamp(timestampAddress).addTimestamp(msg.sender)) { // No, revert indicating there was some kind of error revert('No timestamp created'); } // Prepare loyalty account record loyaltyAccount._address = address(msg.sender); loyaltyAccount._balance = _depositAmount; loyaltyAccount._joined = loyaltyAccount._joined.add(1); // Update global account counter totalActiveAccounts = totalActiveAccounts.add(1); // emit DepositLoyaltyEvent(msg.sender, _depositAmount, false); // Return success return true; } // Return failure return false; } /** * @dev Claim Sparkle Loyalty reward */ function claimLoyaltyReward() public whenNotPaused nonReentrant returns(bool) { // Validate calling address (msg.sender) require(msg.sender != address(0), 'Invalid {from}'); // Validate caller has a timestamp and it has matured require(ISparkleTimestamp(timestampAddress).hasTimestamp(msg.sender), 'No record'); require(ISparkleTimestamp(timestampAddress).isRewardReady(msg.sender), 'Not mature'); // Obtain the current state of the callers timestamp (uint256 timeRemaining, bool isReady, uint256 rewardDate) = ISparkleTimestamp(timestampAddress).getTimeRemaining(msg.sender); // Determine if the callers reward has matured if(isReady) { // Value not used but throw unused var warning (cleanup) rewardDate = 0; // Yes, then obtain a storage instance of callers account record Account storage loyaltyAccount = accounts[msg.sender]; // Obtain values required for caculations uint256 dayCount = (timeRemaining.div(ISparkleTimestamp(timestampAddress).getTimePeriod())).add(1); uint256 tokenBalance = loyaltyAccount._balance.add(loyaltyAccount._collected); uint256 rewardRate = ISparkleRewardTiers(tiersAddress).getRate(loyaltyAccount._tier); uint256 rewardTotal = baseRate.mul(tokenBalance).mul(rewardRate).mul(dayCount).div(10e7).div(10e7); // Increment collected by reward total loyaltyAccount._collected = loyaltyAccount._collected.add(rewardTotal); // Increment total number of times a reward has been claimed loyaltyAccount._claimed = loyaltyAccount._claimed.add(1); // Incrememtn total number of times rewards have been collected by all totalTimesClaimed = totalTimesClaimed.add(1); // Increment total number of tokens claimed totalTokensClaimed += rewardTotal; // Reset the callers timestamp record _resetTimestamp(msg.sender); // Emit event log to the block chain for future web3 use emit RewardClaimedEvent(msg.sender, rewardTotal); // Return success return true; } // Revert opposed to returning boolean (May or may not return a txreceipt) revert('Failed claim'); } /** * @dev Withdraw the current deposit balance + any earned loyalty rewards */ function withdrawLoyalty() public whenNotPaused nonReentrant { // Validate calling address (msg.sender) require(msg.sender != address(0), 'Invalid {from}'); // validate that caller has a loyalty timestamp require(ISparkleTimestamp(timestampAddress).hasTimestamp(msg.sender), 'No timestamp2'); // Determine if the account has been locked if(accounts[msg.sender]._isLocked) { // Yes, revert informing that this loyalty account has been locked revert('Locked'); } // Obtain values needed from account record before zeroing uint256 joinCount = accounts[msg.sender]._joined; uint256 collected = accounts[msg.sender]._collected; uint256 deposit = accounts[msg.sender]._balance; bool isLocked = accounts[msg.sender]._isLocked; // Zero out the callers account record Account storage account = accounts[msg.sender]; account._address = address(0x0); account._balance = 0x0; account._collected = 0x0; account._joined = joinCount; account._claimed = 0x0; account._tier = 0x0; // Preserve account lock even after withdraw (account always locked) account._isLocked = isLocked; // Decement the total number of active accounts totalActiveAccounts = totalActiveAccounts.sub(1); // Delete the callers timestamp record _deleteTimestamp(msg.sender); // Determine if transfer from treasury address is a success if(!IERC20(tokenAddress).transferFrom(treasuryAddress, msg.sender, collected)) { // No, revert indicating that the transfer and wisthdraw has failed revert('Withdraw failed'); } // Determine if transfer from contract address is a sucess if(!IERC20(tokenAddress).transfer(msg.sender, deposit)) { // No, revert indicating that the treansfer and withdraw has failed revert('Withdraw failed'); } // Emit event log to the block chain for future web3 use emit LoyaltyWithdrawnEvent(msg.sender, deposit.add(collected)); } function returnLoyaltyDeposit(address _rewardAddress) public whenNotPaused onlyOwner nonReentrant { // Validate calling address (msg.sender) require(msg.sender != address(0), 'Invalid {from}'); // validate that caller has a loyalty timestamp require(ISparkleTimestamp(timestampAddress).hasTimestamp(_rewardAddress), 'No timestamp2'); // Validate that reward address is locked require(accounts[_rewardAddress]._isLocked, 'Lock account first'); uint256 deposit = accounts[_rewardAddress]._balance; Account storage account = accounts[_rewardAddress]; account._balance = 0x0; // Determine if transfer from contract address is a sucess if(!IERC20(tokenAddress).transfer(_rewardAddress, deposit)) { // No, revert indicating that the treansfer and withdraw has failed revert('Withdraw failed'); } // Emit event log to the block chain for future web3 use emit LoyaltyDepositWithdrawnEvent(_rewardAddress, deposit); } function returnLoyaltyCollected(address _rewardAddress) public whenNotPaused onlyOwner nonReentrant { // Validate calling address (msg.sender) require(msg.sender != address(0), 'Invalid {from}'); // validate that caller has a loyalty timestamp require(ISparkleTimestamp(timestampAddress).hasTimestamp(_rewardAddress), 'No timestamp2b'); // Validate that reward address is locked require(accounts[_rewardAddress]._isLocked, 'Lock account first'); uint256 collected = accounts[_rewardAddress]._collected; Account storage account = accounts[_rewardAddress]; account._collected = 0x0; // Determine if transfer from treasury address is a success if(!IERC20(tokenAddress).transferFrom(treasuryAddress, _rewardAddress, collected)) { // No, revert indicating that the transfer and wisthdraw has failed revert('Withdraw failed'); } // Emit event log to the block chain for future web3 use emit LoyaltyCollectedWithdrawnEvent(_rewardAddress, collected); } function removeLoyaltyAccount(address _rewardAddress) public whenNotPaused onlyOwner nonReentrant { // Validate calling address (msg.sender) require(msg.sender != address(0), 'Invalid {from}'); // validate that caller has a loyalty timestamp require(ISparkleTimestamp(timestampAddress).hasTimestamp(_rewardAddress), 'No timestamp2b'); // Validate that reward address is locked require(accounts[_rewardAddress]._isLocked, 'Lock account first'); uint256 joinCount = accounts[_rewardAddress]._joined; Account storage account = accounts[_rewardAddress]; account._address = address(0x0); account._balance = 0x0; account._collected = 0x0; account._joined = joinCount; account._claimed = 0x0; account._tier = 0x0; account._isLocked = false; // Decement the total number of active accounts totalActiveAccounts = totalActiveAccounts.sub(1); // Delete the callers timestamp record _deleteTimestamp(_rewardAddress); emit LoyaltyAccountRemovedEvent(_rewardAddress); } /** * @dev Gets the locked status of the specified address * @param _loyaltyAddress of account * @return (bool) indicating locked status */ function isLocked(address _loyaltyAddress) public view whenNotPaused returns (bool) { return accounts[_loyaltyAddress]._isLocked; } function lockAccount(address _rewardAddress, bool _value) public onlyOwner whenNotPaused nonReentrant { // Validate calling address (msg.sender) require(msg.sender != address(0x0), 'Invalid {from}'); require(_rewardAddress != address(0x0), 'Invalid {reward}'); // Validate specified address has timestamp require(ISparkleTimestamp(timestampAddress).hasTimestamp(_rewardAddress), 'No timstamp'); // Set the specified address' locked status accounts[_rewardAddress]._isLocked = _value; // Emit event log to the block chain for future web3 use emit LockedAccountEvent(_rewardAddress, _value); } /** * @dev Gets the storage address value of the specified address * @param _loyaltyAddress of account * @return (address) indicating the address stored calls account record */ function getLoyaltyAddress(address _loyaltyAddress) public view whenNotPaused returns(address) { return accounts[_loyaltyAddress]._address; } /** * @dev Get the deposit balance value of specified address * @param _loyaltyAddress of account * @return (uint256) indicating the balance value */ function getDepositBalance(address _loyaltyAddress) public view whenNotPaused returns(uint256) { return accounts[_loyaltyAddress]._balance; } /** * @dev Get the tokens collected by the specified address * @param _loyaltyAddress of account * @return (uint256) indicating the tokens collected */ function getTokensCollected(address _loyaltyAddress) public view whenNotPaused returns(uint256) { return accounts[_loyaltyAddress]._collected; } /** * @dev Get the total balance (deposit + collected) of tokens * @param _loyaltyAddress of account * @return (uint256) indicating total balance */ function getTotalBalance(address _loyaltyAddress) public view whenNotPaused returns(uint256) { return accounts[_loyaltyAddress]._balance.add(accounts[_loyaltyAddress]._collected); } /** * @dev Get the times loyalty has been claimed * @param _loyaltyAddress of account * @return (uint256) indicating total time claimed */ function getTimesClaimed(address _loyaltyAddress) public view whenNotPaused returns(uint256) { return accounts[_loyaltyAddress]._claimed; } /** * @dev Get total number of times joined * @param _loyaltyAddress of account * @return (uint256) */ function getTimesJoined(address _loyaltyAddress) public view whenNotPaused returns(uint256) { return accounts[_loyaltyAddress]._joined; } /** * @dev Get time remaining before reward maturity * @param _loyaltyAddress of account * @return (uint256, bool) Indicating time remaining/past and boolean indicating maturity */ function getTimeRemaining(address _loyaltyAddress) public whenNotPaused returns (uint256, bool, uint256) { (uint256 remaining, bool status, uint256 deposit) = ISparkleTimestamp(timestampAddress).getTimeRemaining(_loyaltyAddress); return (remaining, status, deposit); } /** * @dev Withdraw any ether that has been sent directly to the contract * @param _loyaltyAddress of account * @return Total number of tokens that have been claimed by users * @notice Test(s) Not written */ function getRewardTier(address _loyaltyAddress) public view whenNotPaused returns(uint256) { return accounts[_loyaltyAddress]._tier; } /** * @dev Select reward tier for msg.sender * @param _tierSelected id of the reward tier interested in purchasing * @return (bool) indicating failure/success */ function selectRewardTier(uint256 _tierSelected) public payable whenNotPaused nonReentrant returns(bool) { // Validate calling address (msg.sender) require(msg.sender != address(0x0), 'Invalid {From}'); // Validate specified address has a timestamp require(accounts[msg.sender]._address == address(msg.sender), 'No timestamp3'); // Validate tier selection require(accounts[msg.sender]._tier != _tierSelected, 'Already selected'); // Validate that ether was sent with the call require(msg.value > 0, 'No ether'); // Determine if the specified rate is > than existing rate if(ISparkleRewardTiers(tiersAddress).getRate(accounts[msg.sender]._tier) >= ISparkleRewardTiers(tiersAddress).getRate(_tierSelected)) { // No, revert indicating failure revert('Invalid tier'); } // Determine if ether transfer for tier upgrade has completed successfully (bool success, ) = address(collectionAddress).call{value: ISparkleRewardTiers(tiersAddress).getPrice(_tierSelected), gas: gasToSendWithTX}(''); require(success, 'Rate unchanged'); // Update callers rate with the new selected rate accounts[msg.sender]._tier = _tierSelected; emit TierSelectedEvent(msg.sender, _tierSelected); // Return success return true; } function getRewardTiersAddress() public view whenNotPaused returns(address) { return tiersAddress; } /** * @dev Set tier collectionm address * @param _newAddress of new collection address * @notice Test(s) not written */ function setRewardTiersAddress(address _newAddress) public whenNotPaused onlyOwner nonReentrant { // Validate calling address (msg.sender) require(msg.sender != address(0x0), 'Invalid {From}'); // Validate specified address is valid require(_newAddress != address(0), 'Invalid {reward}'); // Set tier rewards contract address tiersAddress = _newAddress; emit TiersAddressChanged(_newAddress); } function getCollectionAddress() public view whenNotPaused returns(address) { return collectionAddress; } /** @notice Test(s) passed * @dev Set tier collectionm address * @param _newAddress of new collection address */ function setCollectionAddress(address _newAddress) public whenNotPaused onlyOwner nonReentrant { // Validate calling address (msg.sender) require(msg.sender != address(0x0), 'Invalid {From}'); // Validate specified address is valid require(_newAddress != address(0), 'Invalid {collection}'); // Set tier collection address collectionAddress = _newAddress; emit CollectionAddressChanged(_newAddress); } function getTreasuryAddress() public view whenNotPaused returns(address) { return treasuryAddress; } /** * @dev Set treasury address * @param _newAddress of the treasury address * @notice Test(s) passed */ function setTreasuryAddress(address _newAddress) public onlyOwner whenNotPaused nonReentrant { // Validate calling address (msg.sender) require(msg.sender != address(0), "Invalid {from}"); // Validate specified address require(_newAddress != address(0), "Invalid {treasury}"); // Set current treasury contract address treasuryAddress = _newAddress; emit TreasuryAddressChanged(_newAddress); } function getTimestampAddress() public view whenNotPaused returns(address) { return timestampAddress; } /** * @dev Set the timestamp address * @param _newAddress of timestamp address * @notice Test(s) passed */ function setTimestampAddress(address _newAddress) public onlyOwner whenNotPaused nonReentrant { // Validate calling address (msg.sender) require(msg.sender != address(0), "Invalid {from}"); // Set current timestamp contract address timestampAddress = _newAddress; emit TimestampAddressChanged(_newAddress); } function getTokenAddress() public view whenNotPaused returns(address) { return tokenAddress; } /** * @dev Set the loyalty token address * @param _newAddress of the new token address * @notice Test(s) passed */ function setTokenAddress(address _newAddress) public onlyOwner whenNotPaused nonReentrant { // Validate calling address (msg.sender) require(msg.sender != address(0), "Invalid {from}"); // Set current token contract address tokenAddress = _newAddress; emit TokenAddressChangedEvent(_newAddress); } function getSentGasAmount() public view whenNotPaused returns(uint256) { return gasToSendWithTX; } function setSentGasAmount(uint256 _amount) public onlyOwner whenNotPaused { // Validate calling address (msg.sender) require(msg.sender != address(0), 'Invalid {from}'); // Set the current minimum deposit allowed gasToSendWithTX = _amount; emit GasSentChanged(_amount); } function getBaseRate() public view whenNotPaused returns(uint256) { return baseRate; } function setBaseRate(uint256 _newRate) public onlyOwner whenNotPaused { // Validate calling address (msg.sender) require(msg.sender != address(0), 'Invalid {from}'); // Set the current minimum deposit allowed baseRate = _newRate; emit BaseRateChanged(_newRate); } /** * @dev Set the minimum Proof Of Loyalty amount allowed for deposit * @param _minProof amount for new minimum accepted loyalty reward deposit * @notice _minProof value is multiplied internally by 10e7. Do not multiply before calling! */ function setMinProof(uint256 _minProof) public onlyOwner whenNotPaused nonReentrant { // Validate calling address (msg.sender) require(msg.sender != address(0), 'Invalid {from}'); // Validate specified minimum is not lower than 1000 tokens require(_minProof >= 1000, 'Invalid amount'); // Set the current minimum deposit allowed minRequired = _minProof.mul(10e7); emit MinProofChanged(minRequired); } event MinProofChanged(uint256); /** * @dev Get the minimum Proof Of Loyalty amount allowed for deposit * @return Amount of tokens required for Proof Of Loyalty Rewards * @notice Test(s) passed */ function getMinProof() public view whenNotPaused returns(uint256) { // Return indicating minimum deposit allowed return minRequired; } /** * @dev Set the maximum Proof Of Loyalty amount allowed for deposit * @param _maxProof amount for new maximum loyalty reward deposit * @notice _maxProof value is multiplied internally by 10e7. Do not multiply before calling! * @notice Smallest maximum value is 1000 + _minProof amount. (Ex: If _minProof == 1000 then smallest _maxProof possible is 2000) */ function setMaxProof(uint256 _maxProof) public onlyOwner whenNotPaused nonReentrant { // Validate calling address (msg.sender) require(msg.sender != address(0), 'Invalid {from}'); require(_maxProof >= 2000, 'Invalid amount'); // Set allow maximum deposit maxAllowed = _maxProof.mul(10e7); } /** * @dev Get the maximum Proof Of Loyalty amount allowed for deposit * @return Maximum amount of tokens allowed for Proof Of Loyalty deposit * @notice Test(s) passed */ function getMaxProof() public view whenNotPaused returns(uint256) { // Return indicating current allowed maximum deposit return maxAllowed; } /** * @dev Get the total number of tokens claimed by all users * @return Total number of tokens that have been claimed by users * @notice Test(s) Not written */ function getTotalTokensClaimed() public view whenNotPaused returns(uint256) { // Return indicating total number of tokens that have been claimed by all return totalTokensClaimed; } /** * @dev Get total number of times rewards have been claimed for all users * @return Total number of times rewards have been claimed */ function getTotalTimesClaimed() public view whenNotPaused returns(uint256) { // Return indicating total number of tokens that have been claimed by all return totalTimesClaimed; } /** * @dev Withdraw any ether that has been sent directly to the contract */ function withdrawEth(address _toAddress) public onlyOwner whenNotPaused nonReentrant { // Validate calling address (msg.sender) require(msg.sender != address(0x0), 'Invalid {from}'); // Validate specified address require(_toAddress != address(0x0), 'Invalid {to}'); // Validate there is ether to withdraw require(address(this).balance > 0, 'No ether'); // Determine if ether transfer of stored ether has completed successfully // require(address(_toAddress).call.value(address(this).balance).gas(gasToSendWithTX)(), 'Withdraw failed'); (bool success, ) = address(_toAddress).call{value:address(this).balance, gas: gasToSendWithTX}(''); require(success, 'Withdraw failed'); } /** * @dev Withdraw any ether that has been sent directly to the contract * @param _toAddress to receive any stored token balance */ function withdrawTokens(address _toAddress) public onlyOwner whenNotPaused nonReentrant { // Validate calling address (msg.sender) require(msg.sender != address(0x0), 'Invalid {from}'); // Validate specified address require(_toAddress != address(0), "Invalid {to}"); // Validate there are tokens to withdraw uint256 balance = IERC20(tokenAddress).balanceOf(address(this)); require(balance != 0, "No tokens"); // Validate the transfer of tokens completed successfully if(IERC20(tokenAddress).transfer(_toAddress, balance)) { emit TokensWithdrawn(_toAddress, balance); } } /** * @dev Override loyalty account tier by contract owner * @param _loyaltyAccount loyalty account address to tier override * @param _tierSelected reward tier to override current tier value * @return (bool) indicating success status */ function overrideRewardTier(address _loyaltyAccount, uint256 _tierSelected) public whenNotPaused onlyOwner nonReentrant returns(bool) { // Validate calling address (msg.sender) require(msg.sender != address(0x0), 'Invalid {from}'); require(_loyaltyAccount != address(0x0), 'Invalid {account}'); // Validate specified address has a timestamp require(accounts[_loyaltyAccount]._address == address(_loyaltyAccount), 'No timestamp4'); // Update the specified loyalty address tier reward index accounts[_loyaltyAccount]._tier = _tierSelected; emit RewardTierChanged(_loyaltyAccount, _tierSelected); } /** * @dev Reset the specified loyalty account timestamp * @param _rewardAddress of the loyalty account to perfornm a reset */ function _resetTimestamp(address _rewardAddress) internal { // Validate calling address (msg.sender) require(msg.sender != address(0x0), 'Invalid {from}'); // Validate specified address require(_rewardAddress != address(0), "Invalid {reward}"); // Reset callers timestamp for specified address require(ISparkleTimestamp(timestampAddress).resetTimestamp(_rewardAddress), 'Reset failed'); emit ResetTimestampEvent(_rewardAddress); } /** * @dev Delete the specified loyalty account timestamp * @param _rewardAddress of the loyalty account to perfornm the delete */ function _deleteTimestamp(address _rewardAddress) internal { // Validate calling address (msg.sender) require(msg.sender != address(0x0), 'Invalid {from}16'); // Validate specified address require(_rewardAddress != address(0), "Invalid {reward}"); // Delete callers timestamp for specified address require(ISparkleTimestamp(timestampAddress).deleteTimestamp(_rewardAddress), 'Delete failed'); emit DeleteTimestampEvent(_rewardAddress); } /** * @dev Event signal: Treasury address updated */ event TreasuryAddressChanged(address); /** * @dev Event signal: Timestamp address updated */ event TimestampAddressChanged(address); /** * @dev Event signal: Token address updated */ event TokenAddressChangedEvent(address); /** * @dev Event signal: Timestamp reset */ event ResetTimestampEvent(address _rewardAddress); /** * @dev Event signal: Timestamp deleted */ event DeleteTimestampEvent(address _rewardAddress); /** * @dev Event signal: Loyalty deposited event */ event DepositLoyaltyEvent(address, uint256, bool); /** * @dev Event signal: Reward claimed successfully for address */ event RewardClaimedEvent(address, uint256); /** * @dev Event signal: Loyalty withdrawn */ event LoyaltyWithdrawnEvent(address, uint256); /** * @dev Event signal: Account locked/unlocked */ event LockedAccountEvent(address _rewardAddress, bool _locked); /** * @dev Event signal: Loyalty deposit balance withdrawn */ event LoyaltyDepositWithdrawnEvent(address, uint256); /** * @dev Event signal: Loyalty collected balance withdrawn */ event LoyaltyCollectedWithdrawnEvent(address, uint256); /** * @dev Event signal: Loyalty account removed */ event LoyaltyAccountRemovedEvent(address); /** * @dev Event signal: Gas sent with call.value amount updated */ event GasSentChanged(uint256); /** * @dev Event signal: Reward tiers address updated */ event TierSelectedEvent(address, uint256); /** * @dev Event signal: Reward tiers address updated */ event TiersAddressChanged(address); /** * @dev Event signal: Reward tier has been updated */ event RewardTierChanged(address, uint256); /** * @dev Event signal: Collection address updated */ event CollectionAddressChanged(address); /** * @dev Event signal: All stored tokens have been removed */ event TokensWithdrawn(address, uint256); /** * @dev Event signal: Apr base rate has been changed */ event BaseRateChanged(uint256); }
A contract for managing reward tiers SparkleLoyalty Inc. (c) 2019-2020/ interface ISparkleRewardTiers is Ownable, Pausable, ReentrancyGuard { view onlyOwner whenNotPaused nonReentrant view onlyOwner whenNotPaused nonReentrant view onlyOwner whenNotPaused nonReentrant view whenNotPaused view whenNotPaused view whenNotPaused onlyOwner whenNotPaused nonReentrant
interface ISparkleRewardTiers { function addTier(uint256 _index, uint256 _rate, uint256 _price, bool _enabled) external returns(bool); function updateTier(uint256 _index, uint256 _rate, uint256 _price, bool _enabled) external returns(bool); function deleteTier(uint256 _index) external returns(bool); function getRate(uint256 _index) external returns(uint256); function getPrice(uint256 _index) external returns(uint256); function getEnabled(uint256 _index) external returns(bool); function withdrawEth() external returns(bool); event TierDeleted(uint256 _index); event TierUpdated(uint256 _index, uint256 _rate, uint256 _price, bool _enabled); event TierAdded(uint256 _index, uint256 _rate, uint256 _price, bool _enabled); } pragma solidity 0.6.12; }
6,070,065
pragma solidity^0.5.0; /// @title Thuto smart contract /// @author Helda Mandlate /// @dev import contracts from openzeppelin related to ownable and ERC20, ERC721 tokens import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "@openzeppelin/contracts/token/ERC721/ERC721Metadata.sol"; import "@openzeppelin/contracts/ownership/Ownable.sol"; //import "github.com/OpenZeppelin/openzeppelin-solidity/contracts/token/ERC20/ERC20.sol"; //import "github.com/OpenZeppelin/openzeppelin-solidity/contracts/token/ERC721/ERC721Metadata.sol"; /// @notice contract begins here contract thuto is ERC721Metadata, Ownable { /// @notice Creates a struct for users of the plaform, needs their Ethereum address and profile URL struct User { address owned_address; string profile_uri; } /// @notice Creates an array of users that are registered User[] public users; address[] registeredUsers; /// @notice The mapping below maps all users' addresses to their userID mapping (address => uint256) public userAddresses ; /// @notice Creates session defined type enum sessionStatus {Pending, Accepted, Rejected, Cancelled} /// @notice Creates a struct for all requests for tutoring, one of the enum parameters, session Id and student Id struct Request { sessionStatus status; uint256 session_Id; uint256 student_Id; } /// @notice Creates an array of requests that have been placed Request[] public requests; /// @notice The mapping below maps all requesters' IDs to their studentId mapping(uint256 => uint256[]) public requestOwners; /** @notice Creates a struct for all sessions @param tutor_Id The Id of tutors @param session_uri session URL @param session_requests session requests @param isRunning status of the session, True if session is currently running, false if otherwise @param tutoring_price The value of the tutoring session */ struct Session { uint256 tutor_Id; string session_uri; uint256[] session_requests; bool isRunning; uint256 tutoring_price; string details; } /// @notice Creates an array of sessions for every tutoring session available Session[] public sessions; /// @notice The mapping below will map the addresses of all the successful student addresses to the ID of their owned users, session owners mapping(uint256 => uint256[]) public sessionOwners; /** @notice Creates a struct for licencing @param student_Id of each tutoring session student @param session_Id of the tutoring session being requested @param request_Id The request Id for the session */ struct LessonDesign { uint256 student_Id; uint256 session_Id; uint256 request_Id; } /// @notice Creates an array of accepted lessons LessonDesign[] public lessons; /// @notice Mapping of licence Id to get the licence owners mapping(uint256 => uint256[]) public sessionsOwners; /// @notice Mapping of licence Id to get the session Id mapping(uint256 => uint256[]) public sessionRequests; // Setting up events event newSession( address indexed _from, string _session_uri, uint256 _tutoring_price, string _details ); event newRequest( address indexed _from, uint256 indexed _session_Id, string _details ); event acceptedRequest( address indexed _from, uint256 _id ); event rejectedRequest( address indexed _from, uint256 _id ); event cancelledRequest( address indexed _from, uint256 _id ); event ChangeTutoringPrice( address indexed _from, uint256 indexed _session_Id, uint256 _tutoring_price ); event ChangeRunningStatus( address indexed _from, uint256 indexed _session_Id, bool _isRunning ); /// @dev ERC20 is now daiContract ERC20 daiContract; /// @dev The constructor below reserves tutor 0 for all unregistered users /// @param _daiContractAddress DAI contract address constructor(address _daiContractAddress) public ERC721Metadata("Thuto Licence", "THUTO"){ users.push(User(address(0), "")); lessons.push(LessonDesign(0, 0, 0)); daiContract = ERC20(_daiContractAddress); } /// @notice This function registers a tutor on the platform by taking in their profile URL /// @param _profile_uri tutor profile url /// @dev If the tutor's address is in position 0 of the userAddresses array, they are unregistered /// @dev Create an instance of the tutor and add the Id to their address function registerUser(string memory _profile_uri) public { require(bytes(_profile_uri).length > 0, "Profile URI should not be empty."); require(userAddresses[msg.sender]==0,"Tutor already registered."); uint256 id = users.push(User(msg.sender,_profile_uri)); userAddresses[msg.sender] = id - 1; } /// @notice This function creates a session on the system, with blank arrays for session requests and owners /// @notice since no one has requested a session for or bought a licence yet /// @dev The tutor only specifies the flat rate /// @dev Add instance to the respective arrays function addSession( string memory _session_uri, bool _isRunning, uint256 _tutoring_price, string memory _details) public { require(bytes(_session_uri).length > 0, "Session URI should not be empty."); require(userAddresses[msg.sender] != 0, "Tutor address is not registered."); require(_tutoring_price > 0, "Sell price not specified."); require(bytes(_details).length > 0, "Details should not be empty."); uint256 _tutor_Id = userAddresses[msg.sender]; uint256[] memory _session_requests; Session memory _session = Session( _tutor_Id, _session_uri, _session_requests, _isRunning, _tutoring_price, _details); uint256 _id = sessions.push(_session); sessionOwners[_tutor_Id].push(_id - 1); emit newSession(msg.sender,_session_uri, _tutoring_price, _details); } /// @notice This function creates a new request for a particular session /// @param _details for the session /// @param _session_Id is the index for the session Id /// @dev lesson Id is added to list of requested sessions function requestSession(uint256 _session_Id, string memory _details) public { require(sessions[_session_Id].tutor_Id != 0, "Session not enlisted."); require(sessions[_session_Id].isRunning, "Session is not running."); require(userAddresses[msg.sender] != 0, "Student address is not registered."); require(bytes(_details).length > 0, "Details should not be empty."); uint256 _id = requests.push(Request(sessionStatus.Pending, _session_Id, userAddresses[msg.sender])); sessions[_session_Id].session_requests.push(_id - 1); requestOwners[userAddresses[msg.sender]].push(_id - 1); emit newRequest(msg.sender, _session_Id, _details); } /** @param _id is the request Id @notice This function allows the tutor to accept the requests @dev parameters of licence design: student_Id, session id, request_Id @notice This function allows the tutor to reject the requests */ function acceptRequest(uint256 _id) public { uint256 _session_Id = requests[_id].session_Id; require(userAddresses[msg.sender] == sessions[_session_Id].tutor_Id, "User not the tutor of this session"); require(sessions[_session_Id].isRunning, "Session is not running"); requests[_id].status = sessionStatus.Accepted; uint256 _lesson_Id = lessons.push(LessonDesign(requests[_id].student_Id, _session_Id, _id)); requestOwners[requests[_id].student_Id].push(_lesson_Id); sessionRequests[_session_Id].push(_lesson_Id); _mint(users[requests[_id].student_Id].owned_address, _lesson_Id); emit acceptedRequest(msg.sender,_id); } /// @notice This function allows the tutor to reject the bids /// @param _id is the Request Id function rejectRequest(uint256 _id) public { uint256 _session_Id = requests[_id].session_Id; require(userAddresses[msg.sender] == sessions[_session_Id].tutor_Id, "User not the tutor of this session"); require(sessions[_session_Id].isRunning, "Session not running"); requests[_id].status = sessionStatus.Rejected; emit rejectedRequest(msg.sender,_id); } /// @notice This function allows the student to cancel the requests /// @param _id is the bid Id function cancelRequest(uint256 _id) public { //uint256 _session_Id = requests[_id].session_Id; // uint256 _session_Id = requests[_id].session_Id; uint256 _request_Id = requests[_id].student_Id; //uint256 _request_Id = sessions[_id].request_Id; require(userAddresses[msg.sender] == requests[_request_Id].student_Id, "Student not the owner of this request"); requests[_id].status = sessionStatus.Cancelled; emit cancelledRequest(msg.sender,_id); } /// @notice This function allows the tutor to change the sell price /// @param _session_Id session id number /// @param _tutoring_price for the session function changeTutoringPrice(uint256 _session_Id, uint256 _tutoring_price) public { require(userAddresses[msg.sender] == sessions[_session_Id].tutor_Id, "User not the tutor of this session"); sessions[_session_Id].tutoring_price = _tutoring_price; emit ChangeTutoringPrice(msg.sender, _session_Id, _tutoring_price); } /// @notice This function allows the tutor to change the running status /// @param _session_Id session id number function changeRunningStatus(uint256 _session_Id) public { require(userAddresses[msg.sender] == sessions[_session_Id].tutor_Id, "User not the tutor of this session"); sessions[_session_Id].isRunning = !sessions[_session_Id].isRunning; emit ChangeRunningStatus(msg.sender, _session_Id, sessions[_session_Id].isRunning); } /// @return This function allows anyone to get the list of sessions based on the address of the tutor /// @param _address eth address for the tutor function getSessions(address _address) public view returns(uint256[] memory) { uint256 _tutor_Id = userAddresses[_address]; return sessionOwners[_tutor_Id]; } /// @return This function allows anyone to get the list of requests based on address of the tutor function getRequests(address _address) public view returns(uint256[] memory) { uint256 _userAddress = userAddresses[_address]; return requestOwners[_userAddress]; } /// @return This function allows anyone to get list of requests per session /// @param _session_Id session id number function getSessionRequests(uint256 _session_Id) public view returns(uint256[] memory) { return sessions[_session_Id].session_requests; } /// @return This function allows the return of the total number of sessions function getSessionLength() public view returns(uint count) { return sessions.length; } /// @return Returns information about a spesific session ID /// @param _session_Id session id number function getSession(uint256 _session_Id) public view returns( uint256, string memory, uint256[] memory, bool, uint256, string memory){ Session memory _session = sessions[_session_Id]; return ( _session.tutor_Id, _session.session_uri, _session.session_requests, _session.isRunning, _session.tutoring_price, _session.details); } /// @return get the lessons per owner /// @param _address of the account holder function getLessonForAddress(address _address) public view returns(uint256[] memory) { uint256 _userNumber = userAddresses[_address]; return requestOwners[_userNumber]; } /// @return get the lessons information per lesson 'purchased' id /// @param _lessonId the lesson id function getLessons(uint256 _lessonId) public view returns(uint256, uint256, uint256){ LessonDesign memory _lesson = lessons[_lessonId]; return ( _lesson.student_Id, _lesson.session_Id, _lesson.request_Id); } /// @return get the array of registered users on the platform function getUsers() public view returns(address[] memory) { return registeredUsers; } bool public stopped = false; modifier haltInEmergency() { if ( !stopped) _; } modifier enableInEmergency() { if ( stopped) _; } /// @return onlyowner can determine status function toggleContractStopped() public onlyOwner { stopped = !stopped; } /// @return tell user that registration failed function registerUserFailed() public returns (string memory) { return "Failed Registration"; } /// @return shows the user list function userListNotChanged() public view returns (address[] memory) { return registeredUsers; } }
return get the lessons per owner _address of the account holder
function getLessonForAddress(address _address) public view returns(uint256[] memory) { uint256 _userNumber = userAddresses[_address]; return requestOwners[_userNumber]; }
5,527,874
pragma solidity 0.4.24; // File: ../../openzeppelin-solidity/contracts/token/ERC20/IERC20.sol /** * @title ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/20 */ interface IERC20 { function totalSupply() external view returns (uint256); function balanceOf(address who) external view returns (uint256); function allowance(address owner, address spender) external view returns (uint256); function transfer(address to, uint256 value) external returns (bool); function approve(address spender, uint256 value) external returns (bool); function transferFrom(address from, address to, uint256 value) external returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); event Approval(address indexed owner, address indexed spender, uint256 value); } // File: ../../openzeppelin-solidity/contracts/math/SafeMath.sol /** * @title SafeMath * @dev Math operations with safety checks that revert on error */ library SafeMath { /** * @dev Multiplies two numbers, reverts on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b); return c; } /** * @dev Integer division of two numbers truncating the quotient, reverts on division by zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // Solidity only automatically asserts when dividing by 0 require(b > 0); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Subtracts two numbers, reverts on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a); uint256 c = a - b; return c; } /** * @dev Adds two numbers, reverts on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a); return c; } /** * @dev Divides two numbers and returns the remainder (unsigned integer modulo), * reverts when dividing by zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b != 0); return a % b; } } // File: ../../openzeppelin-solidity/contracts/token/ERC20/ERC20.sol /** * @title Standard ERC20 token * * @dev Implementation of the basic standard token. * https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20.md * Originally based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol * * This implementation emits additional Approval events, allowing applications to reconstruct the allowance status for * all accounts just by listening to said events. Note that this isn't required by the specification, and other * compliant implementations may not do it. */ contract ERC20 is IERC20 { using SafeMath for uint256; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowed; uint256 private _totalSupply; /** * @dev Total number of tokens in existence */ function totalSupply() public view returns (uint256) { return _totalSupply; } /** * @dev Gets the balance of the specified address. * @param owner The address to query the balance of. * @return An uint256 representing the amount owned by the passed address. */ function balanceOf(address owner) public view returns (uint256) { return _balances[owner]; } /** * @dev Function to check the amount of tokens that an owner allowed to a spender. * @param owner address The address which owns the funds. * @param spender address The address which will spend the funds. * @return A uint256 specifying the amount of tokens still available for the spender. */ function allowance(address owner, address spender) public view returns (uint256) { return _allowed[owner][spender]; } /** * @dev Transfer token for a specified address * @param to The address to transfer to. * @param value The amount to be transferred. */ function transfer(address to, uint256 value) public returns (bool) { _transfer(msg.sender, to, value); return true; } /** * @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender. * Beware that changing an allowance with this method brings the risk that someone may use both the old * and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this * race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * @param spender The address which will spend the funds. * @param value The amount of tokens to be spent. */ function approve(address spender, uint256 value) public returns (bool) { require(spender != address(0)); _allowed[msg.sender][spender] = value; emit Approval(msg.sender, spender, value); return true; } /** * @dev Transfer tokens from one address to another. * Note that while this function emits an Approval event, this is not required as per the specification, * and other compliant implementations may not emit the event. * @param from address The address which you want to send tokens from * @param to address The address which you want to transfer to * @param value uint256 the amount of tokens to be transferred */ function transferFrom(address from, address to, uint256 value) public returns (bool) { _allowed[from][msg.sender] = _allowed[from][msg.sender].sub(value); _transfer(from, to, value); emit Approval(from, msg.sender, _allowed[from][msg.sender]); return true; } /** * @dev Increase the amount of tokens that an owner allowed to a spender. * approve should be called when allowed_[_spender] == 0. To increment * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * Emits an Approval event. * @param spender The address which will spend the funds. * @param addedValue The amount of tokens to increase the allowance by. */ function increaseAllowance(address spender, uint256 addedValue) public returns (bool) { require(spender != address(0)); _allowed[msg.sender][spender] = _allowed[msg.sender][spender].add(addedValue); emit Approval(msg.sender, spender, _allowed[msg.sender][spender]); return true; } /** * @dev Decrease the amount of tokens that an owner allowed to a spender. * approve should be called when allowed_[_spender] == 0. To decrement * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * Emits an Approval event. * @param spender The address which will spend the funds. * @param subtractedValue The amount of tokens to decrease the allowance by. */ function decreaseAllowance(address spender, uint256 subtractedValue) public returns (bool) { require(spender != address(0)); _allowed[msg.sender][spender] = _allowed[msg.sender][spender].sub(subtractedValue); emit Approval(msg.sender, spender, _allowed[msg.sender][spender]); return true; } /** * @dev Transfer token for a specified addresses * @param from The address to transfer from. * @param to The address to transfer to. * @param value The amount to be transferred. */ function _transfer(address from, address to, uint256 value) internal { require(to != address(0)); _balances[from] = _balances[from].sub(value); _balances[to] = _balances[to].add(value); emit Transfer(from, to, value); } /** * @dev Internal function that mints an amount of the token and assigns it to * an account. This encapsulates the modification of balances such that the * proper events are emitted. * @param account The account that will receive the created tokens. * @param value The amount that will be created. */ function _mint(address account, uint256 value) internal { require(account != address(0)); _totalSupply = _totalSupply.add(value); _balances[account] = _balances[account].add(value); emit Transfer(address(0), account, value); } /** * @dev Internal function that burns an amount of the token of a given * account. * @param account The account whose tokens will be burnt. * @param value The amount that will be burnt. */ function _burn(address account, uint256 value) internal { require(account != address(0)); _totalSupply = _totalSupply.sub(value); _balances[account] = _balances[account].sub(value); emit Transfer(account, address(0), value); } /** * @dev Internal function that burns an amount of the token of a given * account, deducting from the sender's allowance for said account. Uses the * internal burn function. * Emits an Approval event (reflecting the reduced allowance). * @param account The account whose tokens will be burnt. * @param value The amount that will be burnt. */ function _burnFrom(address account, uint256 value) internal { _allowed[account][msg.sender] = _allowed[account][msg.sender].sub(value); _burn(account, value); emit Approval(account, msg.sender, _allowed[account][msg.sender]); } } // File: contracts/ERC1132.sol /** * @title ERC1132 interface * @dev see https://github.com/ethereum/EIPs/issues/1132 */ contract ERC1132 { /** * @dev Reasons why a user's tokens have been locked */ mapping(address => bytes32[]) public lockReason; /** * @dev locked token structure */ struct lockToken { uint256 amount; uint256 validity; bool claimed; } /** * @dev Holds number & validity of tokens locked for a given reason for * a specified address */ mapping(address => mapping(bytes32 => lockToken)) public locked; /** * @dev Records data of all the tokens Locked */ event Locked( address indexed account, bytes32 indexed reason, uint256 amount, uint256 validity ); /** * @dev Records data of all the tokens unlocked */ event Unlocked( address indexed account, bytes32 indexed reason, uint256 amount ); /** * @dev Locks a specified amount of tokens against an address, * for a specified reason and time * @param reason The reason to lock tokens * @param amount Number of tokens to be locked * @param time Lock time in seconds */ function lock(bytes32 reason, uint256 amount, uint256 time) public returns (bool); /** * @dev Returns tokens locked for a specified address for a * specified reason * * @param account The address whose tokens are locked * @param reason The reason to query the lock tokens for */ function tokensLocked(address account, bytes32 reason) public view returns (uint256 amount); /** * @dev Returns tokens locked for a specified address for a * specified reason at a specific time * * @param account The address whose tokens are locked * @param reason The reason to query the lock tokens for * @param time The timestamp to query the lock tokens for */ function tokensLockedAtTime(address account, bytes32 reason, uint256 time) public view returns (uint256 amount); /** * @dev Returns total tokens held by an address (locked + transferable) * @param who The address to query the total balance of */ function totalBalanceOf(address who) public view returns (uint256 amount); /** * @dev Extends lock for a specified reason and time * @param reason The reason to lock tokens * @param time Lock extension time in seconds */ function extendLock(bytes32 reason, uint256 time) public returns (bool); /** * @dev Increase number of tokens locked for a specified reason * @param reason The reason to lock tokens * @param amount Number of tokens to be increased */ function increaseLockAmount(bytes32 reason, uint256 amount) public returns (bool); /** * @dev Returns unlockable tokens for a specified address for a specified reason * @param who The address to query the the unlockable token count of * @param reason The reason to query the unlockable tokens for */ function tokensUnlockable(address who, bytes32 reason) public view returns (uint256 amount); /** * @dev Unlocks the unlockable tokens of a specified address * @param account Address of user, claiming back unlockable tokens */ function unlock(address account) public returns (uint256 unlockableTokens); /** * @dev Gets the unlockable tokens of a specified address * @param account The address to query the the unlockable token count of */ function getUnlockableTokens(address account) public view returns (uint256 unlockableTokens); } // File: contracts/LockableToken.sol contract LockableToken is ERC1132, ERC20 { /** * @dev Error messages for require statements */ string internal constant ALREADY_LOCKED = "Tokens already locked"; string internal constant NOT_LOCKED = "No tokens locked"; string internal constant AMOUNT_ZERO = "Amount can not be 0"; /** * @dev constructor to mint initial tokens * Shall update to _mint once openzepplin updates their npm package. */ constructor(uint256 supply) public { _mint(msg.sender, supply); } /** * @dev Locks a specified amount of tokens against an address, * for a specified reason and time * @param reason The reason to lock tokens * @param amount Number of tokens to be locked * @param time Lock time in seconds */ function lock(bytes32 reason, uint256 amount, uint256 time) public returns (bool) { uint256 validUntil = now.add(time); //solhint-disable-line // If tokens are already locked, then functions extendLock or // increaseLockAmount should be used to make any changes require(tokensLocked(msg.sender, reason) == 0, ALREADY_LOCKED); require(amount != 0, AMOUNT_ZERO); if (locked[msg.sender][reason].amount == 0) lockReason[msg.sender].push(reason); _transfer(msg.sender, address(this), amount); locked[msg.sender][reason] = lockToken(amount, validUntil, false); emit Locked(msg.sender, reason, amount, validUntil); return true; } /** * @dev Transfers and Locks a specified amount of tokens, * for a specified reason and time * @param to adress to which tokens are to be transfered * @param reason The reason to lock tokens * @param amount Number of tokens to be transfered and locked * @param time Lock time in seconds */ function transferWithLock(address to, bytes32 reason, uint256 amount, uint256 time) public returns (bool) { uint256 validUntil = now.add(time); //solhint-disable-line require(tokensLocked(to, reason) == 0, ALREADY_LOCKED); require(amount != 0, AMOUNT_ZERO); if (locked[to][reason].amount == 0) lockReason[to].push(reason); _transfer(msg.sender, address(this), amount); locked[to][reason] = lockToken(amount, validUntil, false); emit Locked(to, reason, amount, validUntil); return true; } /** * @dev Returns tokens locked for a specified address for a * specified reason * * @param account The address whose tokens are locked * @param reason The reason to query the lock tokens for */ function tokensLocked(address account, bytes32 reason) public view returns (uint256 amount) { if (!locked[account][reason].claimed) amount = locked[account][reason].amount; } /** * @dev Returns tokens locked for a specified address for a * specified reason at a specific time * * @param account The address whose tokens are locked * @param reason The reason to query the lock tokens for * @param time The timestamp to query the lock tokens for */ function tokensLockedAtTime(address account, bytes32 reason, uint256 time) public view returns (uint256 amount) { if (locked[account][reason].validity > time) amount = locked[account][reason].amount; } /** * @dev Returns total tokens held by an address (locked + transferable) * @param who The address to query the total balance of */ function totalBalanceOf(address who) public view returns (uint256 amount) { amount = balanceOf(who); for (uint256 i = 0; i < lockReason[who].length; i++) { amount = amount.add(tokensLocked(who, lockReason[who][i])); } } /** * @dev Extends lock for a specified reason and time * @param reason The reason to lock tokens * @param time Lock extension time in seconds */ function extendLock(bytes32 reason, uint256 time) public returns (bool) { require(tokensLocked(msg.sender, reason) > 0, NOT_LOCKED); locked[msg.sender][reason].validity = locked[msg.sender][reason].validity.add(time); emit Locked(msg.sender, reason, locked[msg.sender][reason].amount, locked[msg.sender][reason].validity); return true; } /** * @dev Increase number of tokens locked for a specified reason * @param reason The reason to lock tokens * @param amount Number of tokens to be increased */ function increaseLockAmount(bytes32 reason, uint256 amount) public returns (bool) { require(tokensLocked(msg.sender, reason) > 0, NOT_LOCKED); _transfer(msg.sender, address(this), amount); locked[msg.sender][reason].amount = locked[msg.sender][reason].amount.add(amount); emit Locked(msg.sender, reason, locked[msg.sender][reason].amount, locked[msg.sender][reason].validity); return true; } /** * @dev Returns unlockable tokens for a specified address for a specified reason * @param who The address to query the the unlockable token count of * @param reason The reason to query the unlockable tokens for */ function tokensUnlockable(address who, bytes32 reason) public view returns (uint256 amount) { if (locked[who][reason].validity <= now && !locked[who][reason].claimed) //solhint-disable-line amount = locked[who][reason].amount; } /** * @dev Unlocks the unlockable tokens of a specified address * @param account Address of user, claiming back unlockable tokens */ function unlock(address account) public returns (uint256 unlockableTokens) { uint256 lockedTokens; for (uint256 i = 0; i < lockReason[account].length; i++) { lockedTokens = tokensUnlockable(account, lockReason[account][i]); if (lockedTokens > 0) { unlockableTokens = unlockableTokens.add(lockedTokens); locked[account][lockReason[account][i]].claimed = true; emit Unlocked(account, lockReason[account][i], lockedTokens); } } if (unlockableTokens > 0) _transfer(address(this), account, unlockableTokens); } /** * @dev Gets the unlockable tokens of a specified address * @param account The address to query the the unlockable token count of */ function getUnlockableTokens(address account) public view returns (uint256 unlockableTokens) { for (uint256 i = 0; i < lockReason[account].length; i++) { unlockableTokens = unlockableTokens.add(tokensUnlockable(account, lockReason[account][i])); } } } // File: ../../openzeppelin-solidity/contracts/token/ERC20/ERC20Detailed.sol /** * @title ERC20Detailed token * @dev The decimals are only for visualization purposes. * All the operations are done using the smallest and indivisible token unit, * just as on Ethereum all the operations are done in wei. */ contract ERC20Detailed is IERC20 { string private _name; string private _symbol; uint8 private _decimals; constructor (string name, string symbol, uint8 decimals) public { _name = name; _symbol = symbol; _decimals = decimals; } /** * @return the name of the token. */ function name() public view returns (string) { return _name; } /** * @return the symbol of the token. */ function symbol() public view returns (string) { return _symbol; } /** * @return the number of decimals of the token. */ function decimals() public view returns (uint8) { return _decimals; } } // File: contracts/BluenoteToken.sol contract BluenoteToken is LockableToken, ERC20Detailed { /** * @dev constructor to call constructors for LockableTocken and ERC20Detailed * */ constructor() public ERC20Detailed("Bluenote World Token", "BNOW", 18) LockableToken(12500000000000000000000000000) { // } }
Extends lock for a specified reason and time reason The reason to lock tokens time Lock extension time in seconds/
function extendLock(bytes32 reason, uint256 time) public returns (bool) { require(tokensLocked(msg.sender, reason) > 0, NOT_LOCKED); locked[msg.sender][reason].validity = locked[msg.sender][reason].validity.add(time); emit Locked(msg.sender, reason, locked[msg.sender][reason].amount, locked[msg.sender][reason].validity); return true; }
936,972
pragma solidity ^0.4.17; contract owned { address public owner; function owned() public { owner = msg.sender; } modifier onlyOwner { require(msg.sender == owner); _; } function transferOwnership(address newOwner) public onlyOwner { owner = newOwner; } } interface token { function mint(address receiver, uint amount) external; function transferOwnership(address) external; } /** * @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; } } contract Crowdsale is owned{ using SafeMath for uint256; address public beneficiary; uint256 public fundingGoal; uint256 public amountRaised; uint256 public openingTime; uint256 public closingTime; uint256 public initialRate; uint256 public finalRate; token public tokenReward; address public crowdsaleOwner; mapping(address => uint256) public balanceOf; bool fundingGoalReached = false; bool crowdsaleClosed = false; event GoalReached(address recipient, uint totalAmountRaised); event FundTransfer(address backer, uint amount, bool isContribution); event OwnershipTransferred(address indexed crowdsaleOwner, address indexed newOwner); event Closed(); /** * @dev Constructor, takes crowdsale opening and closing times. * @param _openingTime Crowdsale opening time * @param _closingTime Crowdsale closing time */ function TimedCrowdsale(uint256 _openingTime, uint256 _closingTime) public { require(_openingTime >= now); require(_closingTime >= _openingTime); openingTime = _openingTime; closingTime = _closingTime; } /** * @dev Checks whether the period in which the crowdsale is open has already elapsed. * @return Whether crowdsale period has elapsed */ function hasClosed() public view returns (bool) { return now > closingTime; } /** * Constrctor function * * Setup the owner */ function Crowdsale( address ifSuccessfulSendTo, uint256 fundingGoalInEthers, address addressOfTokenUsedAsReward, address ownerOfCrowdsale ) public { beneficiary = ifSuccessfulSendTo; fundingGoal = fundingGoalInEthers; tokenReward = token(addressOfTokenUsedAsReward); crowdsaleOwner = ownerOfCrowdsale; } modifier onlyOwner { require(msg.sender == owner); _; } function transferOwnerShipBack(address _newOwner) public onlyOwner { require(msg.sender == crowdsaleOwner); tokenReward.transferOwnership(_newOwner); // owner = crowdsaleOwner; } /** * @dev Constructor, takes intial and final rates of tokens received per wei contributed. * @param _initialRate Number of tokens a buyer gets per wei at the start of the crowdsale * @param _finalRate Number of tokens a buyer gets per wei at the end of the crowdsale */ function IncreasingPriceCrowdsale(uint256 _initialRate, uint256 _finalRate) public { require(_initialRate >= _finalRate); require(_finalRate > 0); initialRate = _initialRate; finalRate = _finalRate; } /** * @dev Returns the rate of tokens per wei at the present time. * Note that, as price _increases_ with time, the rate _decreases_. * @return The number of tokens a buyer gets per wei at a given time */ function getCurrentRate() public view returns (uint256) { uint256 elapsedTime = now - openingTime; uint256 timeRange = closingTime - openingTime; uint256 rateRange = initialRate - finalRate; return initialRate - elapsedTime * rateRange / timeRange; } /** * @dev Overrides parent method taking into account variable rate. * @param _weiAmount The value in wei to be converted into tokens * @return The number of tokens _weiAmount wei will buy at present time */ function _getTokenAmount(uint256 _weiAmount) internal view returns (uint256) { uint256 currentRate = getCurrentRate(); return currentRate * _weiAmount; } /** * Fallback function * * The function without name is the default function that is called whenever anyone sends funds to a contract */ function () payable public { require(!crowdsaleClosed); uint256 rateAmount = getCurrentRate(); uint256 amount = msg.value; balanceOf[msg.sender] += amount; amountRaised += amount; tokenReward.mint(msg.sender, amount / rateAmount); tokenReward.mint(beneficiary, amount / rateAmount); emit FundTransfer(msg.sender, amount, true); } modifier afterDeadline() { if (now >= closingTime) _; } /** * @dev Checks whether funding goal was reached. * @return Whether funding goal was reached */ function goalReached() public view returns (bool) { return amountRaised >= fundingGoal; } /** * Withdraw the funds * * Checks to see if goal or time limit has been reached, and if so, and the funding goal was reached, * sends the entire amount to the beneficiary. If goal was not reached, each contributor can withdraw * the amount they contributed. */ function safeWithdrawal() public afterDeadline { if (!fundingGoalReached) { uint amount = balanceOf[msg.sender]; balanceOf[msg.sender] = 0; if (amount > 0) { if (msg.sender.send(amount)) { emit FundTransfer(msg.sender, amount, false); } else { balanceOf[msg.sender] = amount; } } } } }
Fallback function The function without name is the default function that is called whenever anyone sends funds to a contract/
function () payable public { require(!crowdsaleClosed); uint256 rateAmount = getCurrentRate(); uint256 amount = msg.value; balanceOf[msg.sender] += amount; amountRaised += amount; tokenReward.mint(msg.sender, amount / rateAmount); tokenReward.mint(beneficiary, amount / rateAmount); emit FundTransfer(msg.sender, amount, true); }
1,027,230
./full_match/1/0xcafea112Db32436c2390F5EC988f3aDB96870627/sources/contracts/modules/capital/Pool.sol
If balanceOf reverts consider it 0 If the assetBalance is 0 skip the oracle call to save gas
function getAssetValueInEth(address assetAddress) internal view returns (uint) { uint assetBalance; if (assetAddress.code.length != 0) { try IERC20(assetAddress).balanceOf(address(this)) returns (uint balance) { assetBalance = balance; } } if (assetBalance == 0) { return 0; } return priceFeedOracle.getEthForAsset(assetAddress, assetBalance); }
3,156,070
./partial_match/1/0xc6208602889a0A26c74B6e64a4C76Fb8b5d12569/sources/CumRocketV2.sol
generate the uniswap pair path of token -> weth make the swap
function handleTax() internal lockTheSwap { address[] memory path = new address[](2); path[0] = address(this); path[1] = uniswapV2Router.WETH(); _approve( address(this), address(uniswapV2Router), balanceOf(address(this)) ); uniswapV2Router.swapExactTokensForETHSupportingFeeOnTransferTokens( minAmountToSwapTaxes, path, teamWallet, block.timestamp ); }
15,710,214
// SPDX-License-Identifier: MIT pragma solidity 0.8.10; import "@openzeppelin/contracts/utils/cryptography/draft-EIP712.sol"; import "./OrderMixin.sol"; import "./OrderRFQMixin.sol"; /// @title 1inch Limit Order Protocol v2 contract LimitOrderProtocol is EIP712("1inch Limit Order Protocol", "2"), OrderMixin, OrderRFQMixin { // solhint-disable-next-line func-name-mixedcase function DOMAIN_SEPARATOR() external view returns(bytes32) { return _domainSeparatorV4(); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./ECDSA.sol"; /** * @dev https://eips.ethereum.org/EIPS/eip-712[EIP 712] is a standard for hashing and signing of typed structured data. * * The encoding specified in the EIP is very generic, and such a generic implementation in Solidity is not feasible, * thus this contract does not implement the encoding itself. Protocols need to implement the type-specific encoding * they need in their contracts using a combination of `abi.encode` and `keccak256`. * * This contract implements the EIP 712 domain separator ({_domainSeparatorV4}) that is used as part of the encoding * scheme, and the final step of the encoding to obtain the message digest that is then signed via ECDSA * ({_hashTypedDataV4}). * * The implementation of the domain separator was designed to be as efficient as possible while still properly updating * the chain id to protect against replay attacks on an eventual fork of the chain. * * NOTE: This contract implements the version of the encoding known as "v4", as implemented by the JSON RPC method * https://docs.metamask.io/guide/signing-data.html[`eth_signTypedDataV4` in MetaMask]. * * _Available since v3.4._ */ abstract contract EIP712 { /* solhint-disable var-name-mixedcase */ // Cache the domain separator as an immutable value, but also store the chain id that it corresponds to, in order to // invalidate the cached domain separator if the chain id changes. bytes32 private immutable _CACHED_DOMAIN_SEPARATOR; uint256 private immutable _CACHED_CHAIN_ID; bytes32 private immutable _HASHED_NAME; bytes32 private immutable _HASHED_VERSION; bytes32 private immutable _TYPE_HASH; /* solhint-enable var-name-mixedcase */ /** * @dev Initializes the domain separator and parameter caches. * * The meaning of `name` and `version` is specified in * https://eips.ethereum.org/EIPS/eip-712#definition-of-domainseparator[EIP 712]: * * - `name`: the user readable name of the signing domain, i.e. the name of the DApp or the protocol. * - `version`: the current major version of the signing domain. * * NOTE: These parameters cannot be changed except through a xref:learn::upgrading-smart-contracts.adoc[smart * contract upgrade]. */ constructor(string memory name, string memory version) { bytes32 hashedName = keccak256(bytes(name)); bytes32 hashedVersion = keccak256(bytes(version)); bytes32 typeHash = keccak256( "EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)" ); _HASHED_NAME = hashedName; _HASHED_VERSION = hashedVersion; _CACHED_CHAIN_ID = block.chainid; _CACHED_DOMAIN_SEPARATOR = _buildDomainSeparator(typeHash, hashedName, hashedVersion); _TYPE_HASH = typeHash; } /** * @dev Returns the domain separator for the current chain. */ function _domainSeparatorV4() internal view returns (bytes32) { if (block.chainid == _CACHED_CHAIN_ID) { return _CACHED_DOMAIN_SEPARATOR; } else { return _buildDomainSeparator(_TYPE_HASH, _HASHED_NAME, _HASHED_VERSION); } } function _buildDomainSeparator( bytes32 typeHash, bytes32 nameHash, bytes32 versionHash ) private view returns (bytes32) { return keccak256(abi.encode(typeHash, nameHash, versionHash, block.chainid, address(this))); } /** * @dev Given an already https://eips.ethereum.org/EIPS/eip-712#definition-of-hashstruct[hashed struct], this * function returns the hash of the fully encoded EIP712 message for this domain. * * This hash can be used together with {ECDSA-recover} to obtain the signer of a message. For example: * * ```solidity * bytes32 digest = _hashTypedDataV4(keccak256(abi.encode( * keccak256("Mail(address to,string contents)"), * mailTo, * keccak256(bytes(mailContents)) * ))); * address signer = ECDSA.recover(digest, signature); * ``` */ function _hashTypedDataV4(bytes32 structHash) internal view virtual returns (bytes32) { return ECDSA.toTypedDataHash(_domainSeparatorV4(), structHash); } } // SPDX-License-Identifier: MIT pragma solidity 0.8.10; import "@openzeppelin/contracts/utils/Address.sol"; import "@openzeppelin/contracts/utils/cryptography/draft-EIP712.sol"; import "@openzeppelin/contracts/utils/cryptography/SignatureChecker.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "./helpers/AmountCalculator.sol"; import "./helpers/ChainlinkCalculator.sol"; import "./helpers/NonceManager.sol"; import "./helpers/PredicateHelper.sol"; import "./interfaces/InteractiveNotificationReceiver.sol"; import "./libraries/ArgumentsDecoder.sol"; import "./libraries/Permitable.sol"; /// @title Regular Limit Order mixin abstract contract OrderMixin is EIP712, AmountCalculator, ChainlinkCalculator, NonceManager, PredicateHelper, Permitable { using Address for address; using ArgumentsDecoder for bytes; /// @notice Emitted every time order gets filled, including partial fills event OrderFilled( address indexed maker, bytes32 orderHash, uint256 remaining ); /// @notice Emitted when order gets cancelled event OrderCanceled( address indexed maker, bytes32 orderHash, uint256 remainingRaw ); // Fixed-size order part with core information struct StaticOrder { uint256 salt; address makerAsset; address takerAsset; address maker; address receiver; address allowedSender; // equals to Zero address on public orders uint256 makingAmount; uint256 takingAmount; } // `StaticOrder` extension including variable-sized additional order meta information struct Order { uint256 salt; address makerAsset; address takerAsset; address maker; address receiver; address allowedSender; // equals to Zero address on public orders uint256 makingAmount; uint256 takingAmount; bytes makerAssetData; bytes takerAssetData; bytes getMakerAmount; // this.staticcall(abi.encodePacked(bytes, swapTakerAmount)) => (swapMakerAmount) bytes getTakerAmount; // this.staticcall(abi.encodePacked(bytes, swapMakerAmount)) => (swapTakerAmount) bytes predicate; // this.staticcall(bytes) => (bool) bytes permit; // On first fill: permit.1.call(abi.encodePacked(permit.selector, permit.2)) bytes interaction; } bytes32 constant public LIMIT_ORDER_TYPEHASH = keccak256( "Order(uint256 salt,address makerAsset,address takerAsset,address maker,address receiver,address allowedSender,uint256 makingAmount,uint256 takingAmount,bytes makerAssetData,bytes takerAssetData,bytes getMakerAmount,bytes getTakerAmount,bytes predicate,bytes permit,bytes interaction)" ); uint256 constant private _ORDER_DOES_NOT_EXIST = 0; uint256 constant private _ORDER_FILLED = 1; /// @notice Stores unfilled amounts for each order plus one. /// Therefore 0 means order doesn't exist and 1 means order was filled mapping(bytes32 => uint256) private _remaining; /// @notice Returns unfilled amount for order. Throws if order does not exist function remaining(bytes32 orderHash) external view returns(uint256) { uint256 amount = _remaining[orderHash]; require(amount != _ORDER_DOES_NOT_EXIST, "LOP: Unknown order"); unchecked { amount -= 1; } return amount; } /// @notice Returns unfilled amount for order /// @return Result Unfilled amount of order plus one if order exists. Otherwise 0 function remainingRaw(bytes32 orderHash) external view returns(uint256) { return _remaining[orderHash]; } /// @notice Same as `remainingRaw` but for multiple orders function remainingsRaw(bytes32[] memory orderHashes) external view returns(uint256[] memory) { uint256[] memory results = new uint256[](orderHashes.length); for (uint256 i = 0; i < orderHashes.length; i++) { results[i] = _remaining[orderHashes[i]]; } return results; } /** * @notice Calls every target with corresponding data. Then reverts with CALL_RESULTS_0101011 where zeroes and ones * denote failure or success of the corresponding call * @param targets Array of addresses that will be called * @param data Array of data that will be passed to each call */ function simulateCalls(address[] calldata targets, bytes[] calldata data) external { require(targets.length == data.length, "LOP: array size mismatch"); bytes memory reason = new bytes(targets.length); for (uint256 i = 0; i < targets.length; i++) { // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory result) = targets[i].call(data[i]); if (success && result.length > 0) { success = result.length == 32 && result.decodeBool(); } reason[i] = success ? bytes1("1") : bytes1("0"); } // Always revert and provide per call results revert(string(abi.encodePacked("CALL_RESULTS_", reason))); } /// @notice Cancels order by setting remaining amount to zero function cancelOrder(Order memory order) external { require(order.maker == msg.sender, "LOP: Access denied"); bytes32 orderHash = hashOrder(order); uint256 orderRemaining = _remaining[orderHash]; require(orderRemaining != _ORDER_FILLED, "LOP: already filled"); emit OrderCanceled(msg.sender, orderHash, orderRemaining); _remaining[orderHash] = _ORDER_FILLED; } /// @notice Fills an order. If one doesn't exist (first fill) it will be created using order.makerAssetData /// @param order Order quote to fill /// @param signature Signature to confirm quote ownership /// @param makingAmount Making amount /// @param takingAmount Taking amount /// @param thresholdAmount Specifies maximum allowed takingAmount when takingAmount is zero, otherwise specifies minimum allowed makingAmount function fillOrder( Order memory order, bytes calldata signature, uint256 makingAmount, uint256 takingAmount, uint256 thresholdAmount ) external returns(uint256 /* actualMakingAmount */, uint256 /* actualTakingAmount */) { return fillOrderTo(order, signature, makingAmount, takingAmount, thresholdAmount, msg.sender); } /// @notice Same as `fillOrder` but calls permit first, /// allowing to approve token spending and make a swap in one transaction. /// Also allows to specify funds destination instead of `msg.sender` /// @param order Order quote to fill /// @param signature Signature to confirm quote ownership /// @param makingAmount Making amount /// @param takingAmount Taking amount /// @param thresholdAmount Specifies maximum allowed takingAmount when takingAmount is zero, otherwise specifies minimum allowed makingAmount /// @param target Address that will receive swap funds /// @param permit Should consist of abiencoded token address and encoded `IERC20Permit.permit` call. /// @dev See tests for examples function fillOrderToWithPermit( Order memory order, bytes calldata signature, uint256 makingAmount, uint256 takingAmount, uint256 thresholdAmount, address target, bytes calldata permit ) external returns(uint256 /* actualMakingAmount */, uint256 /* actualTakingAmount */) { require(permit.length >= 20, "LOP: permit length too low"); (address token, bytes calldata permitData) = permit.decodeTargetAndData(); _permit(token, permitData); return fillOrderTo(order, signature, makingAmount, takingAmount, thresholdAmount, target); } /// @notice Same as `fillOrder` but allows to specify funds destination instead of `msg.sender` /// @param order Order quote to fill /// @param signature Signature to confirm quote ownership /// @param makingAmount Making amount /// @param takingAmount Taking amount /// @param thresholdAmount Specifies maximum allowed takingAmount when takingAmount is zero, otherwise specifies minimum allowed makingAmount /// @param target Address that will receive swap funds function fillOrderTo( Order memory order, bytes calldata signature, uint256 makingAmount, uint256 takingAmount, uint256 thresholdAmount, address target ) public returns(uint256 /* actualMakingAmount */, uint256 /* actualTakingAmount */) { require(target != address(0), "LOP: zero target is forbidden"); bytes32 orderHash = hashOrder(order); { // Stack too deep uint256 remainingMakerAmount = _remaining[orderHash]; require(remainingMakerAmount != _ORDER_FILLED, "LOP: remaining amount is 0"); require(order.allowedSender == address(0) || order.allowedSender == msg.sender, "LOP: private order"); if (remainingMakerAmount == _ORDER_DOES_NOT_EXIST) { // First fill: validate order and permit maker asset require(SignatureChecker.isValidSignatureNow(order.maker, orderHash, signature), "LOP: bad signature"); remainingMakerAmount = order.makingAmount; if (order.permit.length >= 20) { // proceed only if permit length is enough to store address (address token, bytes memory permit) = order.permit.decodeTargetAndCalldata(); _permitMemory(token, permit); require(_remaining[orderHash] == _ORDER_DOES_NOT_EXIST, "LOP: reentrancy detected"); } } else { unchecked { remainingMakerAmount -= 1; } } // Check if order is valid if (order.predicate.length > 0) { require(checkPredicate(order), "LOP: predicate returned false"); } // Compute maker and taker assets amount if ((takingAmount == 0) == (makingAmount == 0)) { revert("LOP: only one amount should be 0"); } else if (takingAmount == 0) { uint256 requestedMakingAmount = makingAmount; if (makingAmount > remainingMakerAmount) { makingAmount = remainingMakerAmount; } takingAmount = _callGetter(order.getTakerAmount, order.makingAmount, makingAmount); // check that actual rate is not worse than what was expected // takingAmount / makingAmount <= thresholdAmount / requestedMakingAmount require(takingAmount * requestedMakingAmount <= thresholdAmount * makingAmount, "LOP: taking amount too high"); } else { uint256 requestedTakingAmount = takingAmount; makingAmount = _callGetter(order.getMakerAmount, order.takingAmount, takingAmount); if (makingAmount > remainingMakerAmount) { makingAmount = remainingMakerAmount; takingAmount = _callGetter(order.getTakerAmount, order.makingAmount, makingAmount); } // check that actual rate is not worse than what was expected // makingAmount / takingAmount >= thresholdAmount / requestedTakingAmount require(makingAmount * requestedTakingAmount >= thresholdAmount * takingAmount, "LOP: making amount too low"); } require(makingAmount > 0 && takingAmount > 0, "LOP: can't swap 0 amount"); // Update remaining amount in storage unchecked { remainingMakerAmount = remainingMakerAmount - makingAmount; _remaining[orderHash] = remainingMakerAmount + 1; } emit OrderFilled(msg.sender, orderHash, remainingMakerAmount); } // Taker => Maker _makeCall( order.takerAsset, abi.encodePacked( IERC20.transferFrom.selector, uint256(uint160(msg.sender)), uint256(uint160(order.receiver == address(0) ? order.maker : order.receiver)), takingAmount, order.takerAssetData ) ); // Maker can handle funds interactively if (order.interaction.length >= 20) { // proceed only if interaction length is enough to store address (address interactionTarget, bytes memory interactionData) = order.interaction.decodeTargetAndCalldata(); InteractiveNotificationReceiver(interactionTarget).notifyFillOrder( msg.sender, order.makerAsset, order.takerAsset, makingAmount, takingAmount, interactionData ); } // Maker => Taker _makeCall( order.makerAsset, abi.encodePacked( IERC20.transferFrom.selector, uint256(uint160(order.maker)), uint256(uint160(target)), makingAmount, order.makerAssetData ) ); return (makingAmount, takingAmount); } /// @notice Checks order predicate function checkPredicate(Order memory order) public view returns(bool) { bytes memory result = address(this).functionStaticCall(order.predicate, "LOP: predicate call failed"); require(result.length == 32, "LOP: invalid predicate return"); return result.decodeBool(); } function hashOrder(Order memory order) public view returns(bytes32) { StaticOrder memory staticOrder; assembly { // solhint-disable-line no-inline-assembly staticOrder := order } return _hashTypedDataV4( keccak256( abi.encode( LIMIT_ORDER_TYPEHASH, staticOrder, keccak256(order.makerAssetData), keccak256(order.takerAssetData), keccak256(order.getMakerAmount), keccak256(order.getTakerAmount), keccak256(order.predicate), keccak256(order.permit), keccak256(order.interaction) ) ) ); } function _makeCall(address asset, bytes memory assetData) private { bytes memory result = asset.functionCall(assetData, "LOP: asset.call failed"); if (result.length > 0) { require(result.length == 32 && result.decodeBool(), "LOP: asset.call bad result"); } } function _callGetter(bytes memory getter, uint256 orderAmount, uint256 amount) private view returns(uint256) { if (getter.length == 0) { // On empty getter calldata only exact amount is allowed require(amount == orderAmount, "LOP: wrong amount"); return orderAmount; } else { bytes memory result = address(this).functionStaticCall(abi.encodePacked(getter, amount), "LOP: getAmount call failed"); require(result.length == 32, "LOP: invalid getAmount return"); return result.decodeUint256(); } } } // SPDX-License-Identifier: MIT pragma solidity 0.8.10; import "@openzeppelin/contracts/utils/cryptography/draft-EIP712.sol"; import "@openzeppelin/contracts/utils/cryptography/SignatureChecker.sol"; import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; import "./helpers/AmountCalculator.sol"; import "./libraries/Permitable.sol"; /// @title RFQ Limit Order mixin abstract contract OrderRFQMixin is EIP712, AmountCalculator, Permitable { using SafeERC20 for IERC20; /// @notice Emitted when RFQ gets filled event OrderFilledRFQ( bytes32 orderHash, uint256 makingAmount ); struct OrderRFQ { uint256 info; // lowest 64 bits is the order id, next 64 bits is the expiration timestamp IERC20 makerAsset; IERC20 takerAsset; address maker; address allowedSender; // equals to Zero address on public orders uint256 makingAmount; uint256 takingAmount; } bytes32 constant public LIMIT_ORDER_RFQ_TYPEHASH = keccak256( "OrderRFQ(uint256 info,address makerAsset,address takerAsset,address maker,address allowedSender,uint256 makingAmount,uint256 takingAmount)" ); mapping(address => mapping(uint256 => uint256)) private _invalidator; /// @notice Returns bitmask for double-spend invalidators based on lowest byte of order.info and filled quotes /// @return Result Each bit represents whether corresponding was already invalidated function invalidatorForOrderRFQ(address maker, uint256 slot) external view returns(uint256) { return _invalidator[maker][slot]; } /// @notice Cancels order's quote function cancelOrderRFQ(uint256 orderInfo) external { _invalidateOrder(msg.sender, orderInfo); } /// @notice Fills order's quote, fully or partially (whichever is possible) /// @param order Order quote to fill /// @param signature Signature to confirm quote ownership /// @param makingAmount Making amount /// @param takingAmount Taking amount function fillOrderRFQ( OrderRFQ memory order, bytes calldata signature, uint256 makingAmount, uint256 takingAmount ) external returns(uint256, uint256) { return fillOrderRFQTo(order, signature, makingAmount, takingAmount, msg.sender); } /// @notice Fills Same as `fillOrderRFQ` but calls permit first, /// allowing to approve token spending and make a swap in one transaction. /// Also allows to specify funds destination instead of `msg.sender` /// @param order Order quote to fill /// @param signature Signature to confirm quote ownership /// @param makingAmount Making amount /// @param takingAmount Taking amount /// @param target Address that will receive swap funds /// @param permit Should consist of abiencoded token address and encoded `IERC20Permit.permit` call. /// @dev See tests for examples function fillOrderRFQToWithPermit( OrderRFQ memory order, bytes calldata signature, uint256 makingAmount, uint256 takingAmount, address target, bytes calldata permit ) external returns(uint256, uint256) { _permit(address(order.takerAsset), permit); return fillOrderRFQTo(order, signature, makingAmount, takingAmount, target); } /// @notice Same as `fillOrderRFQ` but allows to specify funds destination instead of `msg.sender` /// @param order Order quote to fill /// @param signature Signature to confirm quote ownership /// @param makingAmount Making amount /// @param takingAmount Taking amount /// @param target Address that will receive swap funds function fillOrderRFQTo( OrderRFQ memory order, bytes calldata signature, uint256 makingAmount, uint256 takingAmount, address target ) public returns(uint256, uint256) { require(target != address(0), "LOP: zero target is forbidden"); address maker = order.maker; // Validate order require(order.allowedSender == address(0) || order.allowedSender == msg.sender, "LOP: private order"); bytes32 orderHash = _hashTypedDataV4(keccak256(abi.encode(LIMIT_ORDER_RFQ_TYPEHASH, order))); require(SignatureChecker.isValidSignatureNow(maker, orderHash, signature), "LOP: bad signature"); { // Stack too deep uint256 info = order.info; // Check time expiration uint256 expiration = uint128(info) >> 64; require(expiration == 0 || block.timestamp <= expiration, "LOP: order expired"); // solhint-disable-line not-rely-on-time _invalidateOrder(maker, info); } { // stack too deep uint256 orderMakingAmount = order.makingAmount; uint256 orderTakingAmount = order.takingAmount; // Compute partial fill if needed if (takingAmount == 0 && makingAmount == 0) { // Two zeros means whole order makingAmount = orderMakingAmount; takingAmount = orderTakingAmount; } else if (takingAmount == 0) { require(makingAmount <= orderMakingAmount, "LOP: making amount exceeded"); takingAmount = getTakerAmount(orderMakingAmount, orderTakingAmount, makingAmount); } else if (makingAmount == 0) { require(takingAmount <= orderTakingAmount, "LOP: taking amount exceeded"); makingAmount = getMakerAmount(orderMakingAmount, orderTakingAmount, takingAmount); } else { revert("LOP: both amounts are non-zero"); } } require(makingAmount > 0 && takingAmount > 0, "LOP: can't swap 0 amount"); // Maker => Taker, Taker => Maker order.makerAsset.safeTransferFrom(maker, target, makingAmount); order.takerAsset.safeTransferFrom(msg.sender, maker, takingAmount); emit OrderFilledRFQ(orderHash, makingAmount); return (makingAmount, takingAmount); } function _invalidateOrder(address maker, uint256 orderInfo) private { uint256 invalidatorSlot = uint64(orderInfo) >> 8; uint256 invalidatorBit = 1 << uint8(orderInfo); mapping(uint256 => uint256) storage invalidatorStorage = _invalidator[maker]; uint256 invalidator = invalidatorStorage[invalidatorSlot]; require(invalidator & invalidatorBit == 0, "LOP: invalidated order"); invalidatorStorage[invalidatorSlot] = invalidator | invalidatorBit; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Elliptic Curve Digital Signature Algorithm (ECDSA) operations. * * These functions can be used to verify that a message was signed by the holder * of the private keys of a given address. */ library ECDSA { enum RecoverError { NoError, InvalidSignature, InvalidSignatureLength, InvalidSignatureS, InvalidSignatureV } function _throwError(RecoverError error) private pure { if (error == RecoverError.NoError) { return; // no error: do nothing } else if (error == RecoverError.InvalidSignature) { revert("ECDSA: invalid signature"); } else if (error == RecoverError.InvalidSignatureLength) { revert("ECDSA: invalid signature length"); } else if (error == RecoverError.InvalidSignatureS) { revert("ECDSA: invalid signature 's' value"); } else if (error == RecoverError.InvalidSignatureV) { revert("ECDSA: invalid signature 'v' value"); } } /** * @dev Returns the address that signed a hashed message (`hash`) with * `signature` or error string. This address can then be used for verification purposes. * * The `ecrecover` EVM opcode allows for malleable (non-unique) signatures: * this function rejects them by requiring the `s` value to be in the lower * half order, and the `v` value to be either 27 or 28. * * IMPORTANT: `hash` _must_ be the result of a hash operation for the * verification to be secure: it is possible to craft signatures that * recover to arbitrary addresses for non-hashed data. A safe way to ensure * this is by receiving a hash of the original message (which may otherwise * be too long), and then calling {toEthSignedMessageHash} on it. * * Documentation for signature generation: * - with https://web3js.readthedocs.io/en/v1.3.4/web3-eth-accounts.html#sign[Web3.js] * - with https://docs.ethers.io/v5/api/signer/#Signer-signMessage[ethers] * * _Available since v4.3._ */ function tryRecover(bytes32 hash, bytes memory signature) internal pure returns (address, RecoverError) { // Check the signature length // - case 65: r,s,v signature (standard) // - case 64: r,vs signature (cf https://eips.ethereum.org/EIPS/eip-2098) _Available since v4.1._ if (signature.length == 65) { bytes32 r; bytes32 s; uint8 v; // ecrecover takes the signature parameters, and the only way to get them // currently is to use assembly. assembly { r := mload(add(signature, 0x20)) s := mload(add(signature, 0x40)) v := byte(0, mload(add(signature, 0x60))) } return tryRecover(hash, v, r, s); } else if (signature.length == 64) { bytes32 r; bytes32 vs; // ecrecover takes the signature parameters, and the only way to get them // currently is to use assembly. assembly { r := mload(add(signature, 0x20)) vs := mload(add(signature, 0x40)) } return tryRecover(hash, r, vs); } else { return (address(0), RecoverError.InvalidSignatureLength); } } /** * @dev Returns the address that signed a hashed message (`hash`) with * `signature`. This address can then be used for verification purposes. * * The `ecrecover` EVM opcode allows for malleable (non-unique) signatures: * this function rejects them by requiring the `s` value to be in the lower * half order, and the `v` value to be either 27 or 28. * * IMPORTANT: `hash` _must_ be the result of a hash operation for the * verification to be secure: it is possible to craft signatures that * recover to arbitrary addresses for non-hashed data. A safe way to ensure * this is by receiving a hash of the original message (which may otherwise * be too long), and then calling {toEthSignedMessageHash} on it. */ function recover(bytes32 hash, bytes memory signature) internal pure returns (address) { (address recovered, RecoverError error) = tryRecover(hash, signature); _throwError(error); return recovered; } /** * @dev Overload of {ECDSA-tryRecover} that receives the `r` and `vs` short-signature fields separately. * * See https://eips.ethereum.org/EIPS/eip-2098[EIP-2098 short signatures] * * _Available since v4.3._ */ function tryRecover( bytes32 hash, bytes32 r, bytes32 vs ) internal pure returns (address, RecoverError) { bytes32 s; uint8 v; assembly { s := and(vs, 0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff) v := add(shr(255, vs), 27) } return tryRecover(hash, v, r, s); } /** * @dev Overload of {ECDSA-recover} that receives the `r and `vs` short-signature fields separately. * * _Available since v4.2._ */ function recover( bytes32 hash, bytes32 r, bytes32 vs ) internal pure returns (address) { (address recovered, RecoverError error) = tryRecover(hash, r, vs); _throwError(error); return recovered; } /** * @dev Overload of {ECDSA-tryRecover} that receives the `v`, * `r` and `s` signature fields separately. * * _Available since v4.3._ */ function tryRecover( bytes32 hash, uint8 v, bytes32 r, bytes32 s ) internal pure returns (address, RecoverError) { // EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature // unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines // the valid range for s in (301): 0 < s < secp256k1n ÷ 2 + 1, and for v in (302): v ∈ {27, 28}. Most // signatures from current libraries generate a unique signature with an s-value in the lower half order. // // If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value // with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or // vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept // these malleable signatures as well. if (uint256(s) > 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0) { return (address(0), RecoverError.InvalidSignatureS); } if (v != 27 && v != 28) { return (address(0), RecoverError.InvalidSignatureV); } // If the signature is valid (and not malleable), return the signer address address signer = ecrecover(hash, v, r, s); if (signer == address(0)) { return (address(0), RecoverError.InvalidSignature); } return (signer, RecoverError.NoError); } /** * @dev Overload of {ECDSA-recover} that receives the `v`, * `r` and `s` signature fields separately. */ function recover( bytes32 hash, uint8 v, bytes32 r, bytes32 s ) internal pure returns (address) { (address recovered, RecoverError error) = tryRecover(hash, v, r, s); _throwError(error); return recovered; } /** * @dev Returns an Ethereum Signed Message, created from a `hash`. This * produces hash corresponding to the one signed with the * https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`] * JSON-RPC method as part of EIP-191. * * See {recover}. */ function toEthSignedMessageHash(bytes32 hash) internal pure returns (bytes32) { // 32 is the length in bytes of hash, // enforced by the type signature above return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hash)); } /** * @dev Returns an Ethereum Signed Typed Data, created from a * `domainSeparator` and a `structHash`. This produces hash corresponding * to the one signed with the * https://eips.ethereum.org/EIPS/eip-712[`eth_signTypedData`] * JSON-RPC method as part of EIP-712. * * See {recover}. */ function toTypedDataHash(bytes32 domainSeparator, bytes32 structHash) internal pure returns (bytes32) { return keccak256(abi.encodePacked("\x19\x01", domainSeparator, structHash)); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); (bool success, bytes memory returndata) = target.delegatecall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./ECDSA.sol"; import "../Address.sol"; import "../../interfaces/IERC1271.sol"; /** * @dev Signature verification helper: Provide a single mechanism to verify both private-key (EOA) ECDSA signature and * ERC1271 contract sigantures. Using this instead of ECDSA.recover in your contract will make them compatible with * smart contract wallets such as Argent and Gnosis. * * Note: unlike ECDSA signatures, contract signature's are revocable, and the outcome of this function can thus change * through time. It could return true at block N and false at block N+1 (or the opposite). * * _Available since v4.1._ */ library SignatureChecker { function isValidSignatureNow( address signer, bytes32 hash, bytes memory signature ) internal view returns (bool) { (address recovered, ECDSA.RecoverError error) = ECDSA.tryRecover(hash, signature); if (error == ECDSA.RecoverError.NoError && recovered == signer) { return true; } (bool success, bytes memory result) = signer.staticcall( abi.encodeWithSelector(IERC1271.isValidSignature.selector, hash, signature) ); return (success && result.length == 32 && abi.decode(result, (bytes4)) == IERC1271.isValidSignature.selector); } } // 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.10; pragma abicoder v1; import "@openzeppelin/contracts/utils/Address.sol"; /// @title A helper contract for calculations related to order amounts contract AmountCalculator { using Address for address; /// @notice Calculates maker amount /// @return Result Floored maker amount function getMakerAmount(uint256 orderMakerAmount, uint256 orderTakerAmount, uint256 swapTakerAmount) public pure returns(uint256) { return swapTakerAmount * orderMakerAmount / orderTakerAmount; } /// @notice Calculates taker amount /// @return Result Ceiled taker amount function getTakerAmount(uint256 orderMakerAmount, uint256 orderTakerAmount, uint256 swapMakerAmount) public pure returns(uint256) { return (swapMakerAmount * orderTakerAmount + orderMakerAmount - 1) / orderMakerAmount; } /// @notice Performs an arbitrary call to target with data /// @return Result Bytes transmuted to uint256 function arbitraryStaticCall(address target, bytes memory data) external view returns(uint256) { (bytes memory result) = target.functionStaticCall(data, "AC: arbitraryStaticCall"); return abi.decode(result, (uint256)); } } // SPDX-License-Identifier: MIT pragma solidity 0.8.10; pragma abicoder v1; import "@chainlink/contracts/src/v0.8/interfaces/AggregatorV3Interface.sol"; import "@openzeppelin/contracts/utils/math/SafeCast.sol"; /// @title A helper contract for interactions with https://docs.chain.link contract ChainlinkCalculator { using SafeCast for int256; uint256 private constant _SPREAD_DENOMINATOR = 1e9; uint256 private constant _ORACLE_EXPIRATION_TIME = 30 minutes; uint256 private constant _INVERSE_MASK = 1 << 255; /// @notice Calculates price of token relative to oracle unit (ETH or USD) /// @param inverseAndSpread concatenated inverse flag and spread. /// Lowest 254 bits specify spread amount. Spread is scaled by 1e9, i.e. 101% = 1.01e9, 99% = 0.99e9. /// Highest bit is set when oracle price should be inverted, /// e.g. for DAI-ETH oracle, inverse=false means that we request DAI price in ETH /// and inverse=true means that we request ETH price in DAI /// @return Amount * spread * oracle price function singlePrice(AggregatorV3Interface oracle, uint256 inverseAndSpread, uint256 amount) external view returns(uint256) { (, int256 latestAnswer,, uint256 latestTimestamp,) = oracle.latestRoundData(); // solhint-disable-next-line not-rely-on-time require(latestTimestamp + _ORACLE_EXPIRATION_TIME > block.timestamp, "CC: stale data"); bool inverse = inverseAndSpread & _INVERSE_MASK > 0; uint256 spread = inverseAndSpread & (~_INVERSE_MASK); if (inverse) { return amount * spread * (10 ** oracle.decimals()) / latestAnswer.toUint256() / _SPREAD_DENOMINATOR; } else { return amount * spread * latestAnswer.toUint256() / (10 ** oracle.decimals()) / _SPREAD_DENOMINATOR; } } /// @notice Calculates price of token A relative to token B. Note that order is important /// @return Result Token A relative price times amount function doublePrice(AggregatorV3Interface oracle1, AggregatorV3Interface oracle2, uint256 spread, uint256 amount) external view returns(uint256) { require(oracle1.decimals() == oracle2.decimals(), "CC: oracle decimals don't match"); (, int256 latestAnswer1,, uint256 latestTimestamp1,) = oracle1.latestRoundData(); (, int256 latestAnswer2,, uint256 latestTimestamp2,) = oracle2.latestRoundData(); // solhint-disable-next-line not-rely-on-time require(latestTimestamp1 + _ORACLE_EXPIRATION_TIME > block.timestamp, "CC: stale data O1"); // solhint-disable-next-line not-rely-on-time require(latestTimestamp2 + _ORACLE_EXPIRATION_TIME > block.timestamp, "CC: stale data O2"); return amount * spread * latestAnswer1.toUint256() / latestAnswer2.toUint256() / _SPREAD_DENOMINATOR; } } // SPDX-License-Identifier: MIT pragma solidity 0.8.10; pragma abicoder v1; /// @title A helper contract for managing nonce of tx sender contract NonceManager { event NonceIncreased(address indexed maker, uint256 newNonce); mapping(address => uint256) public nonce; /// @notice Advances nonce by one function increaseNonce() external { advanceNonce(1); } /// @notice Advances nonce by specified amount function advanceNonce(uint8 amount) public { uint256 newNonce = nonce[msg.sender] + amount; nonce[msg.sender] = newNonce; emit NonceIncreased(msg.sender, newNonce); } /// @notice Checks if `makerAddress` has specified `makerNonce` /// @return Result True if `makerAddress` has specified nonce. Otherwise, false function nonceEquals(address makerAddress, uint256 makerNonce) external view returns(bool) { return nonce[makerAddress] == makerNonce; } } // SPDX-License-Identifier: MIT pragma solidity 0.8.10; import "@openzeppelin/contracts/utils/Address.sol"; /// @title A helper contract for executing boolean functions on arbitrary target call results contract PredicateHelper { using Address for address; /// @notice Calls every target with corresponding data /// @return Result True if call to any target returned True. Otherwise, false function or(address[] calldata targets, bytes[] calldata data) external view returns(bool) { require(targets.length == data.length, "PH: input array size mismatch"); for (uint256 i = 0; i < targets.length; i++) { bytes memory result = targets[i].functionStaticCall(data[i], "PH: 'or' subcall failed"); require(result.length == 32, "PH: invalid call result"); if (abi.decode(result, (bool))) { return true; } } return false; } /// @notice Calls every target with corresponding data /// @return Result True if calls to all targets returned True. Otherwise, false function and(address[] calldata targets, bytes[] calldata data) external view returns(bool) { require(targets.length == data.length, "PH: input array size mismatch"); for (uint256 i = 0; i < targets.length; i++) { bytes memory result = targets[i].functionStaticCall(data[i], "PH: 'and' subcall failed"); require(result.length == 32, "PH: invalid call result"); if (!abi.decode(result, (bool))) { return false; } } return true; } /// @notice Calls target with specified data and tests if it's equal to the value /// @param value Value to test /// @return Result True if call to target returns the same value as `value`. Otherwise, false function eq(uint256 value, address target, bytes memory data) external view returns(bool) { bytes memory result = target.functionStaticCall(data, "PH: eq"); require(result.length == 32, "PH: invalid call result"); return abi.decode(result, (uint256)) == value; } /// @notice Calls target with specified data and tests if it's lower than value /// @param value Value to test /// @return Result True if call to target returns value which is lower than `value`. Otherwise, false function lt(uint256 value, address target, bytes memory data) external view returns(bool) { bytes memory result = target.functionStaticCall(data, "PH: lt"); require(result.length == 32, "PH: invalid call result"); return abi.decode(result, (uint256)) < value; } /// @notice Calls target with specified data and tests if it's bigger than value /// @param value Value to test /// @return Result True if call to target returns value which is bigger than `value`. Otherwise, false function gt(uint256 value, address target, bytes memory data) external view returns(bool) { bytes memory result = target.functionStaticCall(data, "PH: gt"); require(result.length == 32, "PH: invalid call result"); return abi.decode(result, (uint256)) > value; } /// @notice Checks passed time against block timestamp /// @return Result True if current block timestamp is lower than `time`. Otherwise, false function timestampBelow(uint256 time) external view returns(bool) { return block.timestamp < time; // solhint-disable-line not-rely-on-time } } // SPDX-License-Identifier: MIT pragma solidity 0.8.10; pragma abicoder v1; /// @title Interface for interactor which acts between `maker => taker` and `taker => maker` transfers. interface InteractiveNotificationReceiver { /// @notice Callback method that gets called after taker transferred funds to maker but before /// the opposite transfer happened function notifyFillOrder( address taker, address makerAsset, address takerAsset, uint256 makingAmount, uint256 takingAmount, bytes memory interactiveData ) external; } // SPDX-License-Identifier: MIT pragma solidity 0.8.10; pragma abicoder v1; /// @title Library with gas efficient alternatives to `abi.decode` library ArgumentsDecoder { function decodeUint256(bytes memory data) internal pure returns(uint256) { uint256 value; assembly { // solhint-disable-line no-inline-assembly value := mload(add(data, 0x20)) } return value; } function decodeBool(bytes memory data) internal pure returns(bool) { bool value; assembly { // solhint-disable-line no-inline-assembly value := eq(mload(add(data, 0x20)), 1) } return value; } function decodeTargetAndCalldata(bytes memory data) internal pure returns(address, bytes memory) { address target; bytes memory args; assembly { // solhint-disable-line no-inline-assembly target := mload(add(data, 0x14)) args := add(data, 0x14) mstore(args, sub(mload(data), 0x14)) } return (target, args); } function decodeTargetAndData(bytes calldata data) internal pure returns(address, bytes calldata) { address target; bytes calldata args; assembly { // solhint-disable-line no-inline-assembly target := shr(96, calldataload(data.offset)) } args = data[20:]; return (target, args); } } // SPDX-License-Identifier: MIT pragma solidity 0.8.10; pragma abicoder v1; import "@openzeppelin/contracts/token/ERC20/extensions/draft-IERC20Permit.sol"; import "./RevertReasonParser.sol"; import "../interfaces/IDaiLikePermit.sol"; /// @title Base contract with common permit handling logics abstract contract Permitable { function _permit(address token, bytes calldata permit) internal { if (permit.length > 0) { bool success; bytes memory result; if (permit.length == 32 * 7) { // solhint-disable-next-line avoid-low-level-calls (success, result) = token.call(abi.encodePacked(IERC20Permit.permit.selector, permit)); } else if (permit.length == 32 * 8) { // solhint-disable-next-line avoid-low-level-calls (success, result) = token.call(abi.encodePacked(IDaiLikePermit.permit.selector, permit)); } else { revert("Wrong permit length"); } if (!success) { revert(RevertReasonParser.parse(result, "Permit failed: ")); } } } function _permitMemory(address token, bytes memory permit) internal { if (permit.length > 0) { bool success; bytes memory result; if (permit.length == 32 * 7) { // solhint-disable-next-line avoid-low-level-calls (success, result) = token.call(abi.encodePacked(IERC20Permit.permit.selector, permit)); } else if (permit.length == 32 * 8) { // solhint-disable-next-line avoid-low-level-calls (success, result) = token.call(abi.encodePacked(IDaiLikePermit.permit.selector, permit)); } else { revert("Wrong permit length"); } if (!success) { revert(RevertReasonParser.parse(result, "Permit failed: ")); } } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Interface of the ERC1271 standard signature validation method for * contracts as defined in https://eips.ethereum.org/EIPS/eip-1271[ERC-1271]. * * _Available since v4.1._ */ interface IERC1271 { /** * @dev Should return whether the signature provided is valid for the provided data * @param hash Hash of the data to be signed * @param signature Signature byte array associated with _data */ function isValidSignature(bytes32 hash, bytes memory signature) external view returns (bytes4 magicValue); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.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: MIT pragma solidity ^0.8.0; /** * @dev Wrappers over Solidity's uintXX/intXX casting operators with added overflow * checks. * * Downcasting from uint256/int256 in Solidity does not revert on overflow. This can * easily result in undesired exploitation or bugs, since developers usually * assume that overflows raise errors. `SafeCast` restores this intuition by * reverting the transaction when such an operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. * * Can be combined with {SafeMath} and {SignedSafeMath} to extend it to smaller types, by performing * all math on `uint256` and `int256` and then downcasting. */ library SafeCast { /** * @dev Returns the downcasted uint224 from uint256, reverting on * overflow (when the input is greater than largest uint224). * * Counterpart to Solidity's `uint224` operator. * * Requirements: * * - input must fit into 224 bits */ function toUint224(uint256 value) internal pure returns (uint224) { require(value <= type(uint224).max, "SafeCast: value doesn't fit in 224 bits"); return uint224(value); } /** * @dev Returns the downcasted uint128 from uint256, reverting on * overflow (when the input is greater than largest uint128). * * Counterpart to Solidity's `uint128` operator. * * Requirements: * * - input must fit into 128 bits */ function toUint128(uint256 value) internal pure returns (uint128) { require(value <= type(uint128).max, "SafeCast: value doesn't fit in 128 bits"); return uint128(value); } /** * @dev Returns the downcasted uint96 from uint256, reverting on * overflow (when the input is greater than largest uint96). * * Counterpart to Solidity's `uint96` operator. * * Requirements: * * - input must fit into 96 bits */ function toUint96(uint256 value) internal pure returns (uint96) { require(value <= type(uint96).max, "SafeCast: value doesn't fit in 96 bits"); return uint96(value); } /** * @dev Returns the downcasted uint64 from uint256, reverting on * overflow (when the input is greater than largest uint64). * * Counterpart to Solidity's `uint64` operator. * * Requirements: * * - input must fit into 64 bits */ function toUint64(uint256 value) internal pure returns (uint64) { require(value <= type(uint64).max, "SafeCast: value doesn't fit in 64 bits"); return uint64(value); } /** * @dev Returns the downcasted uint32 from uint256, reverting on * overflow (when the input is greater than largest uint32). * * Counterpart to Solidity's `uint32` operator. * * Requirements: * * - input must fit into 32 bits */ function toUint32(uint256 value) internal pure returns (uint32) { require(value <= type(uint32).max, "SafeCast: value doesn't fit in 32 bits"); return uint32(value); } /** * @dev Returns the downcasted uint16 from uint256, reverting on * overflow (when the input is greater than largest uint16). * * Counterpart to Solidity's `uint16` operator. * * Requirements: * * - input must fit into 16 bits */ function toUint16(uint256 value) internal pure returns (uint16) { require(value <= type(uint16).max, "SafeCast: value doesn't fit in 16 bits"); return uint16(value); } /** * @dev Returns the downcasted uint8 from uint256, reverting on * overflow (when the input is greater than largest uint8). * * Counterpart to Solidity's `uint8` operator. * * Requirements: * * - input must fit into 8 bits. */ function toUint8(uint256 value) internal pure returns (uint8) { require(value <= type(uint8).max, "SafeCast: value doesn't fit in 8 bits"); return uint8(value); } /** * @dev Converts a signed int256 into an unsigned uint256. * * Requirements: * * - input must be greater than or equal to 0. */ function toUint256(int256 value) internal pure returns (uint256) { require(value >= 0, "SafeCast: value must be positive"); return uint256(value); } /** * @dev Returns the downcasted int128 from int256, reverting on * overflow (when the input is less than smallest int128 or * greater than largest int128). * * Counterpart to Solidity's `int128` operator. * * Requirements: * * - input must fit into 128 bits * * _Available since v3.1._ */ function toInt128(int256 value) internal pure returns (int128) { require(value >= type(int128).min && value <= type(int128).max, "SafeCast: value doesn't fit in 128 bits"); return int128(value); } /** * @dev Returns the downcasted int64 from int256, reverting on * overflow (when the input is less than smallest int64 or * greater than largest int64). * * Counterpart to Solidity's `int64` operator. * * Requirements: * * - input must fit into 64 bits * * _Available since v3.1._ */ function toInt64(int256 value) internal pure returns (int64) { require(value >= type(int64).min && value <= type(int64).max, "SafeCast: value doesn't fit in 64 bits"); return int64(value); } /** * @dev Returns the downcasted int32 from int256, reverting on * overflow (when the input is less than smallest int32 or * greater than largest int32). * * Counterpart to Solidity's `int32` operator. * * Requirements: * * - input must fit into 32 bits * * _Available since v3.1._ */ function toInt32(int256 value) internal pure returns (int32) { require(value >= type(int32).min && value <= type(int32).max, "SafeCast: value doesn't fit in 32 bits"); return int32(value); } /** * @dev Returns the downcasted int16 from int256, reverting on * overflow (when the input is less than smallest int16 or * greater than largest int16). * * Counterpart to Solidity's `int16` operator. * * Requirements: * * - input must fit into 16 bits * * _Available since v3.1._ */ function toInt16(int256 value) internal pure returns (int16) { require(value >= type(int16).min && value <= type(int16).max, "SafeCast: value doesn't fit in 16 bits"); return int16(value); } /** * @dev Returns the downcasted int8 from int256, reverting on * overflow (when the input is less than smallest int8 or * greater than largest int8). * * Counterpart to Solidity's `int8` operator. * * Requirements: * * - input must fit into 8 bits. * * _Available since v3.1._ */ function toInt8(int256 value) internal pure returns (int8) { require(value >= type(int8).min && value <= type(int8).max, "SafeCast: value doesn't fit in 8 bits"); return int8(value); } /** * @dev Converts an unsigned uint256 into a signed int256. * * Requirements: * * - input must be less than or equal to maxInt256. */ function toInt256(uint256 value) internal pure returns (int256) { // Note: Unsafe cast below is okay because `type(int256).max` is guaranteed to be positive require(value <= uint256(type(int256).max), "SafeCast: value doesn't fit in an int256"); return int256(value); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Interface of the ERC20 Permit extension allowing approvals to be made via signatures, as defined in * https://eips.ethereum.org/EIPS/eip-2612[EIP-2612]. * * Adds the {permit} method, which can be used to change an account's ERC20 allowance (see {IERC20-allowance}) by * presenting a message signed by the account. By not relying on {IERC20-approve}, the token holder account doesn't * need to send a transaction, and thus is not required to hold Ether at all. */ interface IERC20Permit { /** * @dev Sets `value` as the allowance of `spender` over ``owner``'s tokens, * given ``owner``'s signed approval. * * IMPORTANT: The same issues {IERC20-approve} has related to transaction * ordering also apply here. * * Emits an {Approval} event. * * Requirements: * * - `spender` cannot be the zero address. * - `deadline` must be a timestamp in the future. * - `v`, `r` and `s` must be a valid `secp256k1` signature from `owner` * over the EIP712-formatted function arguments. * - the signature must use ``owner``'s current nonce (see {nonces}). * * For more information on the signature format, see the * https://eips.ethereum.org/EIPS/eip-2612#specification[relevant EIP * section]. */ function permit( address owner, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) external; /** * @dev Returns the current nonce for `owner`. This value must be * included whenever a signature is generated for {permit}. * * Every successful call to {permit} increases ``owner``'s nonce by one. This * prevents a signature from being used multiple times. */ function nonces(address owner) external view returns (uint256); /** * @dev Returns the domain separator used in the encoding of the signature for {permit}, as defined by {EIP712}. */ // solhint-disable-next-line func-name-mixedcase function DOMAIN_SEPARATOR() external view returns (bytes32); } // SPDX-License-Identifier: MIT pragma solidity 0.8.10; pragma abicoder v1; /// @title Library that allows to parse unsuccessful arbitrary calls revert reasons. /// See https://solidity.readthedocs.io/en/latest/control-structures.html#revert for details. /// Note that we assume revert reason being abi-encoded as Error(string) so it may fail to parse reason /// if structured reverts appear in the future. /// /// All unsuccessful parsings get encoded as Unknown(data) string library RevertReasonParser { bytes4 constant private _PANIC_SELECTOR = bytes4(keccak256("Panic(uint256)")); bytes4 constant private _ERROR_SELECTOR = bytes4(keccak256("Error(string)")); function parse(bytes memory data, string memory prefix) internal pure returns (string memory) { if (data.length >= 4) { bytes4 selector; assembly { // solhint-disable-line no-inline-assembly selector := mload(add(data, 0x20)) } // 68 = 4-byte selector + 32 bytes offset + 32 bytes length if (selector == _ERROR_SELECTOR && data.length >= 68) { uint256 offset; bytes memory reason; assembly { // solhint-disable-line no-inline-assembly // 36 = 32 bytes data length + 4-byte selector offset := mload(add(data, 36)) reason := add(data, add(36, offset)) } /* revert reason is padded up to 32 bytes with ABI encoder: Error(string) also sometimes there is extra 32 bytes of zeros padded in the end: https://github.com/ethereum/solidity/issues/10170 because of that we can't check for equality and instead check that offset + string length + extra 36 bytes is less than overall data length */ require(data.length >= 36 + offset + reason.length, "Invalid revert reason"); return string(abi.encodePacked(prefix, "Error(", reason, ")")); } // 36 = 4-byte selector + 32 bytes integer else if (selector == _PANIC_SELECTOR && data.length == 36) { uint256 code; assembly { // solhint-disable-line no-inline-assembly // 36 = 32 bytes data length + 4-byte selector code := mload(add(data, 36)) } return string(abi.encodePacked(prefix, "Panic(", _toHex(code), ")")); } } return string(abi.encodePacked(prefix, "Unknown(", _toHex(data), ")")); } function _toHex(uint256 value) private pure returns(string memory) { return _toHex(abi.encodePacked(value)); } function _toHex(bytes memory data) private pure returns(string memory) { bytes16 alphabet = 0x30313233343536373839616263646566; bytes memory str = new bytes(2 + data.length * 2); str[0] = "0"; str[1] = "x"; for (uint256 i = 0; i < data.length; i++) { str[2 * i + 2] = alphabet[uint8(data[i] >> 4)]; str[2 * i + 3] = alphabet[uint8(data[i] & 0x0f)]; } return string(str); } } // SPDX-License-Identifier: MIT pragma solidity 0.8.10; pragma abicoder v1; /// @title Interface for DAI-style permits interface IDaiLikePermit { function permit(address holder, address spender, uint256 nonce, uint256 expiry, bool allowed, uint8 v, bytes32 r, bytes32 s) external; } // 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"); } } }
Returns bitmask for double-spend invalidators based on lowest byte of order.info and filled quotes return Result Each bit represents whether corresponding was already invalidated
function invalidatorForOrderRFQ(address maker, uint256 slot) external view returns(uint256) { return _invalidator[maker][slot]; }
1,390,092
// solium-disable security/no-inline-assembly pragma solidity ^0.6.2; /** * @title a library to sequentially read memory * @dev inspired from Andreas Olofsson's RLP */ library Memory { struct Cursor { uint256 begin; uint256 end; } /** * @dev returns a new cursor from a memory * @return Cursor cursor to read from */ function read(bytes memory self) internal pure returns (Cursor memory) { uint ptr; assembly { ptr := add(self, 0x20) } return Cursor(ptr,ptr+self.length); } /** * @dev reads 32 bytes from cursor, no eof checks * @return b the value */ function readBytes32(Cursor memory c) internal pure returns (bytes32) { uint ptr = c.begin; bytes32 b; assembly { b := mload(ptr) } c.begin += 32; return b; } /** * @dev reads 30 bytes from cursor, no eof checks * @return b the value */ function readBytes30(Cursor memory c) internal pure returns (bytes30) { uint ptr = c.begin; bytes32 b; assembly { b := mload(ptr) } c.begin += 30; return bytes30(b); } /** * @dev reads 28 bytes from cursor, no eof checks * @return b the value */ function readBytes28(Cursor memory c) internal pure returns (bytes28) { uint ptr = c.begin; bytes32 b; assembly { b := mload(ptr) } c.begin += 28; return bytes28(b); } /** * @dev reads 10 bytes from cursor, no eof checks * @return b the value */ function readBytes10(Cursor memory c) internal pure returns (bytes10) { uint ptr = c.begin; bytes32 b; assembly { b := mload(ptr) } c.begin += 10; return bytes10(b); } /** * @dev reads 3 bytes from cursor, no eof checks * @return b the value */ function readBytes3(Cursor memory c) internal pure returns (bytes3) { uint ptr = c.begin; bytes32 b; assembly { b := mload(ptr) } c.begin += 3; return bytes3(b); } /** * @dev reads 2 bytes from cursor, no eof checks * @return b the value */ function readBytes2(Cursor memory c) internal pure returns (bytes2) { uint ptr = c.begin; bytes32 b; assembly { b := mload(ptr) } c.begin += 2; return bytes2(b); } /** * @dev reads 1 bytes from cursor, no eof checks * @return b the value */ function readBytes1(Cursor memory c) internal pure returns (bytes1) { uint ptr = c.begin; bytes32 b; assembly { b := mload(ptr) } c.begin += 1; return bytes1(b); } /** * @dev reads a bool from cursor (8 bits), no eof checks * @return b the value */ function readBool(Cursor memory c) internal pure returns (bool) { uint ptr = c.begin; uint256 b; assembly { b := mload(ptr) } c.begin += 1; return (b >> (256-8)) != 0; } /** * @dev reads a uint8 from cursor, no eof checks * @return b the value */ function readUint8(Cursor memory c) internal pure returns (uint8) { uint ptr = c.begin; uint256 b; assembly { b := mload(ptr) } c.begin += 1; return uint8(b >> (256-8)); } /** * @dev reads a uint16 from cursor, no eof checks * @return b the value */ function readUint16(Cursor memory c) internal pure returns (uint16) { uint ptr = c.begin; uint256 b; assembly { b := mload(ptr) } c.begin += 2; return uint16(b >> (256-16)); } /** * @dev reads a uint32 from cursor, no eof checks * @return b the value */ function readUint32(Cursor memory c) internal pure returns (uint32) { uint ptr = c.begin; uint256 b; assembly { b := mload(ptr) } c.begin += 4; return uint32(b >> (256-32)); } /** * @dev reads a uint64 from cursor, no eof checks * @return b the value */ function readUint64(Cursor memory c) internal pure returns (uint64) { uint ptr = c.begin; uint256 b; assembly { b := mload(ptr) } c.begin += 8; return uint64(b>>(256-64)); } /** * @dev reads a uint240 from cursor, no eof checks * @return b the value */ function readUint240(Cursor memory c) internal pure returns (uint240) { uint ptr = c.begin; uint256 b; assembly { b := mload(ptr) } c.begin += 30; return uint240(b>>(256-240)); } /** * @dev reads an address from cursor, no eof checks * @return b the value */ function readAddress(Cursor memory c) internal pure returns (address) { uint ptr = c.begin; uint256 b; assembly { b := mload(ptr) } c.begin += 20; return address(b >> (256-160)); } /** * @dev reads a variable sized bytes, max 2^16 len, no eof check * @return bts the value */ function readBytes(Cursor memory c) internal pure returns (bytes memory bts) { uint16 len = readUint16(c); bts = new bytes(len); uint256 btsmem; assembly { btsmem := add(bts,0x20) } memcpy(btsmem,c.begin,len); c.begin += len; } /** * @dev checks if the cursor is *exactly* at the end of the stream * @return c true if is *exactly* at the end */ function eof(Cursor memory c) internal pure returns (bool) { return c.begin == c.end; } /** * @dev copies _len bytes from _src to _dest */ // solium-disable security/no-assign-params function memcpy(uint _dest, uint _src, uint _len) internal pure { // 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)) } } }
checks if the cursor is exactly at the end of the stream return c true if is exactly at the end/
function eof(Cursor memory c) internal pure returns (bool) { return c.begin == c.end; }
7,238,702
// SPDX-License-Identifier: GPL-3.0 pragma solidity ^0.8.4; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/security/Pausable.sol"; import "./interfaces/polygon/IRootChainManager.sol"; import "./interfaces/hop/IL1_Bridge.sol"; import "./helpers/errors.sol"; /// @author rimatik /// @title HydraBridge middleware contract HydraBridge is Ownable, Pausable { using SafeERC20 for IERC20; /// Address of polygon bridge root chain manager contract address public _polygonRootChainManager; /// Address of polygon bridge erc20Predicate contract address public _erc20Predicate; /// Address of hop bridge contract address public _hopBridgeEth; /// Address of hop bridge contract address public _hopBridgeErc20; event MoveCompleted(address, uint256); constructor(address polygonRootChainManager, address erc20Predicate, address hopBridgeEth, address hopBridgeErc20) { _polygonRootChainManager = polygonRootChainManager; _erc20Predicate = erc20Predicate; _hopBridgeEth = hopBridgeEth; _hopBridgeErc20 = hopBridgeErc20; } /// Send funds to polygon bridge /// @param recipient address for receiving tokens /// @param rootToken address of token to bridge /// @param amount of tokens to bridge /// @dev transfer tokens to HydraBridge contract and bridge them to polygon function sendToPolygon(address recipient, address rootToken, uint256 amount) external whenNotPaused{ _checkBeforeTransfer(amount, recipient); _transferERC20(amount, rootToken, _erc20Predicate, recipient); bytes memory depositData = bytes(abi.encode(amount)); IRootChainManager(_polygonRootChainManager).depositFor(recipient,rootToken,depositData); emit MoveCompleted(recipient,amount); } /// Send eth to polygon bridge /// @param recipient address for receiving tokens function sendEthToPolygon(address recipient) payable external whenNotPaused { _checkBeforeTransfer(msg.value, recipient); IRootChainManager(_polygonRootChainManager).depositEtherFor{value: msg.value}(recipient); emit MoveCompleted(recipient,msg.value); } /// Send funds to polygon bridge through hop protocol /// @param rootToken address of token to bridge /// @param recipient address for receiving tokens /// @param chainId number of chain to transfer /// @param amount of tokens to bridge /// @param amountOutMin minimum tokens received /// @param deadline for transfer /// @param relayer address of relayer /// @param relayerFee fee tha relayer gets /// @dev transfer tokens to HydraBridge contract and bridge them to polygon through hop function sendToL2Hop(address rootToken, address recipient, uint256 chainId,uint256 amount,uint256 amountOutMin,uint256 deadline,address relayer,uint256 relayerFee) external whenNotPaused { _checkBeforeTransfer(amount, recipient); _transferERC20(amount, rootToken, _hopBridgeErc20, recipient); IL1_Bridge(_hopBridgeErc20).sendToL2(chainId,recipient,amount,amountOutMin,deadline,relayer,relayerFee); emit MoveCompleted(recipient,amount); } /// Send eth to polygon bridge through hop protocol /// @param recipient address for receiving tokens /// @param chainId number of chain to transfer /// @param amountOutMin minimum tokens received /// @param deadline for transfer /// @param relayer address of relayer /// @param relayerFee fee tha relayer gets function sendEthToL2Hop(address recipient, uint256 chainId,uint256 amountOutMin,uint256 deadline,address relayer,uint256 relayerFee) payable external whenNotPaused { _checkBeforeTransfer(msg.value, recipient); IL1_Bridge(_hopBridgeEth).sendToL2{value:msg.value}(chainId,recipient,msg.value,amountOutMin,deadline,relayer,relayerFee); emit MoveCompleted(recipient,msg.value); } /// Check for amount and receiving address before transfer /// @param amount to transfer /// @param to address to transfer function _checkBeforeTransfer(uint256 amount, address to) internal pure { require(amount > 0, HydraBridgeErrors.INVALID_AMT); require(to != address(0), HydraBridgeErrors.ADDRESS_0_PROVIDED); } /// Check for amount and receiving address before transfer /// @param amount to transfer /// @param rootToken address of token to transfer /// @param allowanceTarget address for increasing allowance /// @param from address from where transfer is made function _transferERC20(uint256 amount, address rootToken, address allowanceTarget, address from) internal { IERC20(rootToken).safeIncreaseAllowance(allowanceTarget,amount); IERC20(rootToken).transferFrom(from,address(this),amount); } /// Set polygon root chain manager /// @param polygonRootChainManager address of root chain manager function setRootManager(address polygonRootChainManager) external onlyOwner{ _polygonRootChainManager = polygonRootChainManager; } /// Set hop bridge l1 eth address address /// @param hopBridgeEth address function setHopBridgeEth(address hopBridgeEth) external onlyOwner{ _hopBridgeEth = hopBridgeEth; } /// Set hop bridge l1 erc20 address address /// @param hopBridgeErc20 address function setHopBridgeErc20(address hopBridgeErc20) external onlyOwner{ _hopBridgeErc20 = hopBridgeErc20; } /// Set erc20 predicate /// @param erc20Predicate address function setErc20Predicate(address erc20Predicate) external onlyOwner{ _erc20Predicate = erc20Predicate; } /// Disable contract function pause() external onlyOwner whenNotPaused { _pause(); } /// Enable contract function unpause() external onlyOwner whenPaused { _unpause(); } /// Rescue funds in case they are stuck in contract /// @param token to transfer /// @param userAddress address of receiver /// @param amount to transfer function rescueFunds( address token, address userAddress, uint256 amount ) external onlyOwner { IERC20(token).safeTransfer(userAddress, amount); } } // SPDX-License-Identifier: MIT // 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); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC20/utils/SafeERC20.sol) 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 // OpenZeppelin Contracts v4.4.1 (access/Ownable.sol) pragma solidity ^0.8.0; import "../utils/Context.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() { _transferOwnership(_msgSender()); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { _transferOwnership(address(0)); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); _transferOwnership(newOwner); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Internal function without access restriction. */ function _transferOwnership(address newOwner) internal virtual { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (security/Pausable.sol) pragma solidity ^0.8.0; import "../utils/Context.sol"; /** * @dev Contract module which allows children to implement an emergency stop * mechanism that can be triggered by an authorized account. * * This module is used through inheritance. It will make available the * modifiers `whenNotPaused` and `whenPaused`, which can be applied to * the functions of your contract. Note that they will not be pausable by * simply including this module, only once the modifiers are put in place. */ abstract contract Pausable is Context { /** * @dev Emitted when the pause is triggered by `account`. */ event Paused(address account); /** * @dev Emitted when the pause is lifted by `account`. */ event Unpaused(address account); bool private _paused; /** * @dev Initializes the contract in unpaused state. */ constructor() { _paused = false; } /** * @dev Returns true if the contract is paused, and false otherwise. */ function paused() public view virtual returns (bool) { return _paused; } /** * @dev Modifier to make a function callable only when the contract is not paused. * * Requirements: * * - The contract must not be paused. */ modifier whenNotPaused() { require(!paused(), "Pausable: paused"); _; } /** * @dev Modifier to make a function callable only when the contract is paused. * * Requirements: * * - The contract must be paused. */ modifier whenPaused() { require(paused(), "Pausable: not paused"); _; } /** * @dev Triggers stopped state. * * Requirements: * * - The contract must not be paused. */ function _pause() internal virtual whenNotPaused { _paused = true; emit Paused(_msgSender()); } /** * @dev Returns to normal state. * * Requirements: * * - The contract must be paused. */ function _unpause() internal virtual whenPaused { _paused = false; emit Unpaused(_msgSender()); } } // SPDX-License-Identifier: GPL-3.0 pragma solidity 0.8.4; interface IRootChainManager { function depositEtherFor(address user) external payable; function depositFor( address user, address rootToken, bytes calldata depositData ) external; function exit(bytes calldata inputData) external; } // SPDX-License-Identifier: GPL-3.0 pragma solidity 0.8.4; interface IL1_Bridge { function sendToL2( uint256 chainId, address recipient, uint256 amount, uint256 amountOutMin, uint256 deadline, address relayer, uint256 relayerFee ) external payable; } // SPDX-License-Identifier: GPL-3.0 pragma solidity ^0.8.4; library HydraBridgeErrors { string internal constant ADDRESS_0_PROVIDED = "ADDRESS_0_PROVIDED"; string internal constant INVALID_AMT = "INVALID_AMT"; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/Address.sol) pragma solidity ^0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); (bool success, bytes memory returndata) = target.delegatecall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/Context.sol) pragma solidity ^0.8.0; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } }
Send funds to polygon bridge through hop protocol rootToken address of token to bridge recipient address for receiving tokens chainId number of chain to transfer amount of tokens to bridge amountOutMin minimum tokens received deadline for transfer relayer address of relayer relayerFee fee tha relayer gets transfer tokens to HydraBridge contract and bridge them to polygon through hop
function sendToL2Hop(address rootToken, address recipient, uint256 chainId,uint256 amount,uint256 amountOutMin,uint256 deadline,address relayer,uint256 relayerFee) external whenNotPaused { _checkBeforeTransfer(amount, recipient); _transferERC20(amount, rootToken, _hopBridgeErc20, recipient); IL1_Bridge(_hopBridgeErc20).sendToL2(chainId,recipient,amount,amountOutMin,deadline,relayer,relayerFee); emit MoveCompleted(recipient,amount); }
498,413
pragma solidity ^0.5.12; library SafeMath { function MUL98(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING if (a == 0) return 0; uint256 c = a * b; require(c / a == b); return c; } function DIV107(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING require(b > 0); uint256 c = a / b; return c; } function SUB705(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING require(b <= a); uint256 c = a - b; return c; } function ADD235(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING uint256 c = a + b; require(c >= a); return c; } function MOD157(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING require(b != 0); return a % b; } } contract ERC20 { using SafeMath for uint256; mapping (address => uint256) internal _balances; mapping (address => mapping (address => uint256)) internal _allowed; event TRANSFER731(address indexed from, address indexed to, uint256 value); //inject NONSTANDARD NAMING event APPROVAL787(address indexed owner, address indexed spender, uint256 value); //inject NONSTANDARD NAMING uint256 internal _totalSupply; function TOTALSUPPLY882() public view returns (uint256) { //inject NONSTANDARD NAMING return _totalSupply; } function BALANCEOF767(address owner) public view returns (uint256) { //inject NONSTANDARD NAMING return _balances[owner]; } function ALLOWANCE10(address owner, address spender) public view returns (uint256) { //inject NONSTANDARD NAMING return _allowed[owner][spender]; } function TRANSFER204(address to, uint256 value) public returns (bool) { //inject NONSTANDARD NAMING _TRANSFER522(msg.sender, to, value); return true; } function APPROVE277(address spender, uint256 value) public returns (bool) { //inject NONSTANDARD NAMING _allowed[msg.sender][spender] = value; emit APPROVAL787(msg.sender, spender, value); return true; } function TRANSFERFROM832(address from, address to, uint256 value) public returns (bool) { //inject NONSTANDARD NAMING _TRANSFER522(from, to, value); _allowed[msg.sender][to] = _allowed[msg.sender][to].SUB705(value); return true; } function _TRANSFER522(address from, address to, uint256 value) internal { //inject NONSTANDARD NAMING require(to != address(0)); _balances[from] = _balances[from].SUB705(value); _balances[to] = _balances[to].ADD235(value); emit TRANSFER731(from, to, value); } } contract ERC20Mintable is ERC20 { string public name; string public symbol; uint8 public decimals; function _MINT321(address to, uint256 amount) internal { //inject NONSTANDARD NAMING _balances[to] = _balances[to].ADD235(amount); _totalSupply = _totalSupply.ADD235(amount); emit TRANSFER731(address(0), to, amount); } function _BURN441(address from, uint256 amount) internal { //inject NONSTANDARD NAMING _balances[from] = _balances[from].SUB705(amount); _totalSupply = _totalSupply.SUB705(amount); emit TRANSFER731(from, address(0), amount); } } // ----------- Aave ---------------- contract ILendingPoolAddressesProvider { function GETLENDINGPOOL38() public view returns (address); //inject NONSTANDARD NAMING function SETLENDINGPOOLIMPL881(address _pool) public; //inject NONSTANDARD NAMING function GETLENDINGPOOLCORE21() public view returns (address payable); //inject NONSTANDARD NAMING function SETLENDINGPOOLCOREIMPL156(address _lendingPoolCore) public; //inject NONSTANDARD NAMING function GETLENDINGPOOLCONFIGURATOR254() public view returns (address); //inject NONSTANDARD NAMING function SETLENDINGPOOLCONFIGURATORIMPL555(address _configurator) public; //inject NONSTANDARD NAMING function GETLENDINGPOOLDATAPROVIDER61() public view returns (address); //inject NONSTANDARD NAMING function SETLENDINGPOOLDATAPROVIDERIMPL193(address _provider) public; //inject NONSTANDARD NAMING function GETLENDINGPOOLPARAMETERSPROVIDER362() public view returns (address); //inject NONSTANDARD NAMING function SETLENDINGPOOLPARAMETERSPROVIDERIMPL978(address _parametersProvider) public; //inject NONSTANDARD NAMING function GETTOKENDISTRIBUTOR827() public view returns (address); //inject NONSTANDARD NAMING function SETTOKENDISTRIBUTOR348(address _tokenDistributor) public; //inject NONSTANDARD NAMING function GETFEEPROVIDER168() public view returns (address); //inject NONSTANDARD NAMING function SETFEEPROVIDERIMPL718(address _feeProvider) public; //inject NONSTANDARD NAMING function GETLENDINGPOOLLIQUIDATIONMANAGER82() public view returns (address); //inject NONSTANDARD NAMING function SETLENDINGPOOLLIQUIDATIONMANAGER708(address _manager) public; //inject NONSTANDARD NAMING function GETLENDINGPOOLMANAGER762() public view returns (address); //inject NONSTANDARD NAMING function SETLENDINGPOOLMANAGER882(address _lendingPoolManager) public; //inject NONSTANDARD NAMING function GETPRICEORACLE485() public view returns (address); //inject NONSTANDARD NAMING function SETPRICEORACLE428(address _priceOracle) public; //inject NONSTANDARD NAMING function GETLENDINGRATEORACLE592() public view returns (address); //inject NONSTANDARD NAMING function SETLENDINGRATEORACLE655(address _lendingRateOracle) public; //inject NONSTANDARD NAMING } interface ILendingPool { function ADDRESSESPROVIDER344() external view returns(address); //inject NONSTANDARD NAMING function DEPOSIT818(address _reserve, uint256 _amount, uint16 _referralCode) external payable; //inject NONSTANDARD NAMING function REDEEMUNDERLYING805(address _reserve, address _user, uint256 _amount) external; //inject NONSTANDARD NAMING function BORROW264(address _reserve, uint256 _amount, uint256 _interestRateMode, uint16 _referralCode) external; //inject NONSTANDARD NAMING function REPAY662(address _reserve, uint256 _amount, address _onBehalfOf) external payable; //inject NONSTANDARD NAMING function SWAPBORROWRATEMODE766(address _reserve) external; //inject NONSTANDARD NAMING function REBALANCEFIXEDBORROWRATE627(address _reserve, address _user) external; //inject NONSTANDARD NAMING function SETUSERUSERESERVEASCOLLATERAL986(address _reserve, bool _useAsCollateral) external; //inject NONSTANDARD NAMING function LIQUIDATIONCALL807(address _collateral, address _reserve, address _user, uint256 _purchaseAmount, bool _receiveAToken) external payable; //inject NONSTANDARD NAMING function FLASHLOAN206(address _receiver, address _reserve, uint256 _amount, bytes calldata _params) external; //inject NONSTANDARD NAMING function GETRESERVECONFIGURATIONDATA59(address _reserve) external view returns(uint256 ltv, uint256 liquidationThreshold, uint256 liquidationDiscount, address interestRateStrategyAddress, bool usageAsCollateralEnabled, bool borrowingEnabled, bool fixedBorrowRateEnabled, bool isActive); //inject NONSTANDARD NAMING function GETRESERVEDATA692(address _reserve) external view returns(uint256 totalLiquidity, uint256 availableLiquidity, uint256 totalBorrowsFixed, uint256 totalBorrowsVariable, uint256 liquidityRate, uint256 variableBorrowRate, uint256 fixedBorrowRate, uint256 averageFixedBorrowRate, uint256 utilizationRate, uint256 liquidityIndex, uint256 variableBorrowIndex, address aTokenAddress, uint40 lastUpdateTimestamp); //inject NONSTANDARD NAMING function GETUSERACCOUNTDATA811(address _user) external view returns(uint256 totalLiquidityETH, uint256 totalCollateralETH, uint256 totalBorrowsETH, uint256 availableBorrowsETH, uint256 currentLiquidationThreshold, uint256 ltv, uint256 healthFactor); //inject NONSTANDARD NAMING function GETUSERRESERVEDATA732(address _reserve, address _user) external view returns(uint256 currentATokenBalance, uint256 currentBorrowBalance, uint256 principalBorrowBalance, uint256 borrowRateMode, uint256 borrowRate, uint256 liquidityRate, uint256 originationFee, uint256 variableBorrowIndex, uint256 lastUpdateTimestamp, bool usageAsCollateralEnabled); //inject NONSTANDARD NAMING function GETRESERVES689() external view; //inject NONSTANDARD NAMING } interface ILendingPoolCore { function GETRESERVEATOKENADDRESS314(address _reserve) external view returns (address); //inject NONSTANDARD NAMING function GETRESERVECURRENTVARIABLEBORROWRATE762(address _token) external view returns (uint256); //inject NONSTANDARD NAMING function GETRESERVECURRENTLIQUIDITYRATE636(address _token) external view returns (uint256); //inject NONSTANDARD NAMING } interface IAavePriceOracleGetter { function GETASSETPRICE734(address _asset) external view returns (uint256); //inject NONSTANDARD NAMING function GETASSETSPRICES996(address[] calldata _assets) external view returns(uint256[] memory); //inject NONSTANDARD NAMING function GETSOURCEOFASSET324(address _asset) external view returns(address); //inject NONSTANDARD NAMING function GETFALLBACKORACLE535() external view returns(address); //inject NONSTANDARD NAMING } interface IAToken { function REDIRECTINTERESTSTREAM242(address _to) external; //inject NONSTANDARD NAMING function REDIRECTINTERESTSTREAMOF292(address _from, address _to) external; //inject NONSTANDARD NAMING function ALLOWINTERESTREDIRECTIONTO292(address _to) external; //inject NONSTANDARD NAMING function REDEEM632(uint256 _amount) external; //inject NONSTANDARD NAMING function PRINCIPALBALANCEOF100(address _user) external view returns(uint256); //inject NONSTANDARD NAMING function ISTRANSFERALLOWED396(address _user, uint256 _amount) external view returns (bool); //inject NONSTANDARD NAMING function GETUSERINDEX768(address _user) external view returns(uint256); //inject NONSTANDARD NAMING function GETINTERESTREDIRECTIONADDRESS228(address _user) external view returns(address); //inject NONSTANDARD NAMING function GETREDIRECTEDBALANCE288(address _user) external view returns(uint256); //inject NONSTANDARD NAMING function TOTALSUPPLY882() external view returns (uint256 supply); //inject NONSTANDARD NAMING function BALANCEOF767(address _owner) external view returns (uint256 balance); //inject NONSTANDARD NAMING function TRANSFER204(address _to, uint256 _value) external returns (bool success); //inject NONSTANDARD NAMING function TRANSFERFROM832(address _from, address _to, uint256 _value) external returns (bool success); //inject NONSTANDARD NAMING function APPROVE277(address _spender, uint256 _value) external returns (bool success); //inject NONSTANDARD NAMING function ALLOWANCE10(address _owner, address _spender) external view returns (uint256 remaining); //inject NONSTANDARD NAMING function NAME858() external view returns (string memory); //inject NONSTANDARD NAMING function SYMBOL894() external view returns (string memory); //inject NONSTANDARD NAMING function DECIMALS454() external view returns (uint8); //inject NONSTANDARD NAMING } interface PriceOracle { function GETUNDERLYINGPRICE929(address) external view returns (uint256); //inject NONSTANDARD NAMING } // ---------- Compound ---------- interface CErc20 { function BORROW264(uint256) external returns (uint256); //inject NONSTANDARD NAMING function BORROWRATEPERBLOCK388() external view returns (uint256); //inject NONSTANDARD NAMING function BORROWBALANCECURRENT444(address) external returns (uint256); //inject NONSTANDARD NAMING function REPAYBORROW515(uint256) external returns (uint256); //inject NONSTANDARD NAMING } interface CEth { function MINT397() external payable; //inject NONSTANDARD NAMING function REDEEMUNDERLYING805(uint redeemAmount) external returns (uint256); //inject NONSTANDARD NAMING function BALANCEOFUNDERLYING788(address owner) external returns (uint256); //inject NONSTANDARD NAMING function SUPPLYRATEPERBLOCK15() external view returns (uint256); //inject NONSTANDARD NAMING } interface Comptroller { function MARKETS249(address) external returns (bool, uint256); //inject NONSTANDARD NAMING function ENTERMARKETS82(address[] calldata) //inject NONSTANDARD NAMING external returns (uint256[] memory); function GETACCOUNTLIQUIDITY384(address) //inject NONSTANDARD NAMING external view returns (uint256, uint256, uint256); function ORACLE168() external view returns(address); //inject NONSTANDARD NAMING } // ---------- kyber ---------- interface Exchange { function TRADE301( //inject NONSTANDARD NAMING address src, uint srcAmount, address dest, address destAddress, uint maxDestAmount, uint minConversionRate, address walletId )external payable returns(uint); } // -----tCDP----- contract tCDPConstants { uint256 constant dust264 = 1e6; // minimum mint amount //inject NONSTANDARD NAMING ERC20 constant dai445 = ERC20(0x6B175474E89094C44Da98b954EedeAC495271d0F); // DAI(debt) token address //inject NONSTANDARD NAMING //Compound Comptroller constant comptroller75 = Comptroller(0x3d9819210A31b4961b30EF54bE2aeD79B9c9Cd3B); //inject NONSTANDARD NAMING CEth constant ceth501 = CEth(0x4Ddc2D193948926D02f9B1fE9e1daa0718270ED5); //inject NONSTANDARD NAMING CErc20 constant cdai61 = CErc20(0x5d3a536E4D6DbD6114cc1Ead35777bAB948E3643); //inject NONSTANDARD NAMING //AAVE ILendingPoolAddressesProvider constant addressesprovider654 = ILendingPoolAddressesProvider(0x24a42fD28C976A61Df5D00D0599C34c4f90748c8); //inject NONSTANDARD NAMING uint16 constant referral215 = 47; // TODO: apply new referral code //inject NONSTANDARD NAMING //Kyber Exchange constant kybernetwork927 = Exchange(0x818E6FECD516Ecc3849DAf6845e3EC868087B755); //inject NONSTANDARD NAMING address constant etheraddr36 = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; //inject NONSTANDARD NAMING address constant ref472 = 0xD0533664013a82c31584B7FFDB215139f38Ad77A; //inject NONSTANDARD NAMING //rebalance target/boundary/size uint256 constant targetratio559 = 0.4e18; //40% //inject NONSTANDARD NAMING uint256 constant upperbound23 = 444444444444444444; // 1/225% //inject NONSTANDARD NAMING uint256 constant lowerbound414 = 363636363636363636; // 1/275% //inject NONSTANDARD NAMING uint256 constant bite558 = 0.025 * 1e18; //2.5% //inject NONSTANDARD NAMING } contract tCDP is ERC20Mintable, tCDPConstants{ using SafeMath for *; bool public isCompound; event MIGRATION431(uint8); // 0x01 = to Compound, 0x02 = to Aave //inject NONSTANDARD NAMING constructor() public { symbol = "tETH-DAI"; name = "tokenized CDP ETH-DAI v1"; decimals = 18; address lendingPoolCoreAddress = addressesprovider654.GETLENDINGPOOLCORE21(); dai445.APPROVE277(lendingPoolCoreAddress, uint256(-1)); dai445.APPROVE277(address(cdai61), uint256(-1)); address[] memory cTokens = new address[](1); cTokens[0] = address(ceth501); uint256[] memory errors = comptroller75.ENTERMARKETS82(cTokens); require(errors[0] == 0, "Comptroller.enterMarkets failed."); dai445.APPROVE277(address(kybernetwork927), uint256(-1)); isCompound = FINDBESTRATE616(); } function INITIATE270(uint256 amount) external payable { //inject NONSTANDARD NAMING require(_totalSupply < dust264, "initiated"); require(msg.value > dust264, "value too small"); if(isCompound) { ceth501.MINT397.value(msg.value)(); _MINT321(msg.sender, msg.value); require(cdai61.BORROW264(amount) == 0, "borrow failed"); dai445.TRANSFER204(msg.sender, amount); } else { ILendingPool lendingPool = ILendingPool(addressesprovider654.GETLENDINGPOOL38()); lendingPool.DEPOSIT818.value(msg.value)(etheraddr36, msg.value, referral215); _MINT321(msg.sender, msg.value); lendingPool.BORROW264(address(dai445), amount, 2, referral215); dai445.TRANSFER204(msg.sender, amount); } } function COLLATERAL797() public returns(uint256) { //inject NONSTANDARD NAMING if(isCompound) { return ceth501.BALANCEOFUNDERLYING788(address(this)); } else { address lendingPoolCore = addressesprovider654.GETLENDINGPOOLCORE21(); address aETH = ILendingPoolCore(lendingPoolCore).GETRESERVEATOKENADDRESS314(etheraddr36); return IAToken(aETH).BALANCEOF767(address(this)); } } function DEBT567() public returns(uint256) { //inject NONSTANDARD NAMING if(isCompound) { return cdai61.BORROWBALANCECURRENT444(address(this)); } else { ILendingPool lendingPool = ILendingPool(addressesprovider654.GETLENDINGPOOL38()); (, uint256 borrowBalance,,,,,,,,) = lendingPool.GETUSERRESERVEDATA732(address(dai445), address(this)); return borrowBalance; } } function MINT397() external payable returns(uint256) { //inject NONSTANDARD NAMING require(_totalSupply >= dust264, "not initiated"); uint256 amount = msg.value; uint256 tokenToMint = _totalSupply.MUL98(amount).DIV107(COLLATERAL797()); uint256 tokenToBorrow = DEBT567().MUL98(amount).DIV107(COLLATERAL797()); _MINT321(msg.sender, tokenToMint); if(isCompound) { ceth501.MINT397.value(amount)(); require(cdai61.BORROW264(tokenToBorrow) == 0, "borrow failed"); dai445.TRANSFER204(msg.sender, tokenToBorrow); } else{ // deposit ILendingPool lendingPool = ILendingPool(addressesprovider654.GETLENDINGPOOL38()); lendingPool.DEPOSIT818.value(amount)(etheraddr36, amount, referral215); // borrow lendingPool.BORROW264(address(dai445), tokenToBorrow, 2, referral215); // transfer dai445.TRANSFER204(msg.sender, tokenToBorrow); } return tokenToMint; } function BURN250(uint256 amount) external { //inject NONSTANDARD NAMING uint256 tokenToRepay = amount.MUL98(DEBT567()).DIV107(_totalSupply); uint256 tokenToDraw = amount.MUL98(COLLATERAL797()).DIV107(_totalSupply); _BURN441(msg.sender, amount); dai445.TRANSFERFROM832(msg.sender, address(this), tokenToRepay); if(isCompound) { require(cdai61.REPAYBORROW515(tokenToRepay) == 0, "repay failed"); require(ceth501.REDEEMUNDERLYING805(tokenToDraw) == 0, "redeem failed"); } else { // repay ILendingPool lendingPool = ILendingPool(addressesprovider654.GETLENDINGPOOL38()); address lendingPoolCoreAddress = addressesprovider654.GETLENDINGPOOLCORE21(); // Dai.approve(lendingPoolCoreAddress, tokenToRepay); lendingPool.REPAY662(address(dai445), tokenToRepay, address(this)); // redeem IAToken aETH = IAToken(ILendingPoolCore(lendingPoolCoreAddress).GETRESERVEATOKENADDRESS314(etheraddr36)); aETH.REDEEM632(tokenToDraw); } (bool success, ) = msg.sender.call.value(tokenToDraw)(""); require(success, "Failed to transfer ether to msg.sender"); } function() external payable{} //true if (cEth APR - cDai APR) >= (aEth APR - aDai APR), otherwise, false function FINDBESTRATE616() public view returns (bool) { //inject NONSTANDARD NAMING return AAVEDAIAPR797().MUL98(targetratio559).DIV107(1e18).ADD235(COMPOUNDETHAPR912()) > COMPOUNDDAIAPR961().MUL98(targetratio559).DIV107(1e18).ADD235(AAVEETHAPR160()); } function COMPOUNDDAIAPR961() public view returns (uint256) { //inject NONSTANDARD NAMING return cdai61.BORROWRATEPERBLOCK388().MUL98(2102400); } function COMPOUNDETHAPR912() public view returns (uint256) { //inject NONSTANDARD NAMING return ceth501.SUPPLYRATEPERBLOCK15().MUL98(2102400); } function AAVEDAIAPR797() public view returns (uint256) { //inject NONSTANDARD NAMING ILendingPoolCore core = ILendingPoolCore(addressesprovider654.GETLENDINGPOOLCORE21()); return core.GETRESERVECURRENTVARIABLEBORROWRATE762(address(dai445)).DIV107(1e9); } function AAVEETHAPR160() public view returns (uint256) { //inject NONSTANDARD NAMING ILendingPoolCore core = ILendingPoolCore(addressesprovider654.GETLENDINGPOOLCORE21()); return core.GETRESERVECURRENTLIQUIDITYRATE636(etheraddr36).DIV107(1e9); } function GETUNDERLYINGPRICE929() public view returns(uint256) { //inject NONSTANDARD NAMING uint256 price; if(isCompound) { address oracle = comptroller75.ORACLE168(); PriceOracle priceOracle = PriceOracle(oracle); price = priceOracle.GETUNDERLYINGPRICE929(address(cdai61)); } else { address oracleAddress = addressesprovider654.GETPRICEORACLE485(); IAavePriceOracleGetter priceOracle = IAavePriceOracleGetter(oracleAddress); price = priceOracle.GETASSETPRICE734(address(dai445)); } return price; } function DEBTRATIO670() public returns (uint256) { //inject NONSTANDARD NAMING uint256 price = GETUNDERLYINGPRICE929(); uint256 ratio = DEBT567().MUL98(price).DIV107(COLLATERAL797()); return ratio; } function DELEVERAGE904() external { //inject NONSTANDARD NAMING require(_totalSupply >= dust264, "not initiated"); require(DEBTRATIO670() > upperbound23, "debt ratio is good"); uint256 amount = COLLATERAL797().MUL98(bite558).DIV107(1e18); if(isCompound) { require(ceth501.REDEEMUNDERLYING805(amount) == 0, "redeem failed"); uint256 income = kybernetwork927.TRADE301.value(amount)(etheraddr36, amount, address(dai445), address(this), 1e28, 1, ref472); require(cdai61.REPAYBORROW515(income) == 0, "repay failed"); } else { // redeem address lendingPoolCoreAddress = addressesprovider654.GETLENDINGPOOLCORE21(); IAToken aETH = IAToken(ILendingPoolCore(lendingPoolCoreAddress).GETRESERVEATOKENADDRESS314(etheraddr36)); aETH.REDEEM632(amount); uint256 income = kybernetwork927.TRADE301.value(amount)(etheraddr36, amount, address(dai445), address(this), 1e28, 1, ref472); // repay ILendingPool lendingPool = ILendingPool(addressesprovider654.GETLENDINGPOOL38()); // Dai.approve(lendingPoolCoreAddress, income); lendingPool.REPAY662(address(dai445), income, address(this)); } } function LEVERAGE920() external { //inject NONSTANDARD NAMING require(_totalSupply >= dust264, "not initiated"); require(DEBTRATIO670() < lowerbound414, "debt ratio is good"); uint256 amount = DEBT567().MUL98(bite558).DIV107(1e18); if(isCompound) { require(cdai61.BORROW264(amount) == 0, "borrow failed"); uint256 income = kybernetwork927.TRADE301(address(dai445), amount, etheraddr36, address(this), 1e28, 1, ref472); ceth501.MINT397.value(income)(); } else { // borrow ILendingPool lendingPool = ILendingPool(addressesprovider654.GETLENDINGPOOL38()); lendingPool.BORROW264(address(dai445), amount, 2, referral215); uint256 income = kybernetwork927.TRADE301(address(dai445), amount, etheraddr36, address(this), 1e28, 1, ref472); // deposit lendingPool.DEPOSIT818.value(income)(etheraddr36, income, referral215); } } function MIGRATE814() external { //inject NONSTANDARD NAMING if(FINDBESTRATE616() != isCompound) { uint256 _debt = DEBT567(); uint256 _collateral = COLLATERAL797(); dai445.TRANSFERFROM832(msg.sender, address(this), _debt); uint256 newBorrow = _debt.ADD235(2); if(isCompound) { require(cdai61.REPAYBORROW515(_debt) == 0, "borrow failed"); require(ceth501.REDEEMUNDERLYING805(_collateral) == 0, "redeem failed"); ILendingPool lendingPool = ILendingPool(addressesprovider654.GETLENDINGPOOL38()); lendingPool.DEPOSIT818.value(_collateral)(etheraddr36, _collateral, referral215); lendingPool.BORROW264(address(dai445), newBorrow, 2, referral215); isCompound = false; emit MIGRATION431(0x02); } else { ILendingPool lendingPool = ILendingPool(addressesprovider654.GETLENDINGPOOL38()); address lendingPoolCoreAddress = addressesprovider654.GETLENDINGPOOLCORE21(); lendingPool.REPAY662(address(dai445), _debt, address(this)); IAToken aETH = IAToken(ILendingPoolCore(lendingPoolCoreAddress).GETRESERVEATOKENADDRESS314(etheraddr36)); aETH.REDEEM632(_collateral); ceth501.MINT397.value(_collateral)(); require(cdai61.BORROW264(newBorrow) == 0, "borrow failed"); isCompound = true; emit MIGRATION431(0x01); } dai445.TRANSFER204(msg.sender, newBorrow); } } }
inject NONSTANDARD NAMING
function SETLENDINGPOOLMANAGER882(address _lendingPoolManager) public;
5,544,565
// Sources flattened with hardhat v2.6.0 https://hardhat.org // File deps/@openzeppelin/contracts-upgradeable/proxy/Initializable.sol // SPDX-License-Identifier: MIT 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/access/OwnableUpgradeable.sol pragma solidity ^0.6.0; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ contract 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 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 interfaces/badger/IMiniMe.sol pragma solidity >=0.5.0 <0.8.0; interface IMiniMe { event ClaimedTokens(address indexed _token, address indexed _controller, uint256 _amount); event Transfer(address indexed _from, address indexed _to, uint256 _amount); event NewCloneToken(address indexed _cloneToken, uint256 _snapshotBlock); event Approval(address indexed _owner, address indexed _spender, uint256 _amount); function claimTokens(address _token) external; function controller() external view returns (address); function enableTransfers(bool _transfersEnabled) external; function generateTokens(address _owner, uint256 _amount) external returns (bool); function destroyTokens(address _owner, uint256 _amount) external returns (bool); function changeController(address _newController) external returns (address); } // File interfaces/erc20/IERC20.sol pragma solidity ^0.6.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); function name() external view returns (string memory); function symbol() external view returns (string memory); function decimals() 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/badger-core/GatedMiniMeController.sol pragma solidity 0.6.12; /* === Gated MiniMe Controller === Limits the functinality of the MiniMe controller address by serving as an intermediate contract. The owner maintains the ability to mint and burn tokens from it's own balance, losing the ability to mint and burn to/from arbitrary accounts. The MiniMe controller can no longer be changed. The owner maintains the ability to claim other tokens sent to the MiniMe contract. This contract is designed to be upgradeable, this ability can be removed by transferring the proxyAdmin to 0x0. Minting and burning can be permanently removed by the disableMinting() function. claimTokens() is designed to be retained. It ability can be removed (along with minting and burning), by burning the owner() address. */ contract GatedMiniMeController is OwnableUpgradeable { IMiniMe public minime; bool public mintingEnabled; function initialize(address token_) external { __Ownable_init(); minime = IMiniMe(token_); mintingEnabled = true; } modifier onlyWhenMintingEnabled() { require(mintingEnabled == true, "minting disabled"); _; } /// @dev Minting and burning can be permanently disabled by the owner function disableMinting() external onlyOwner { mintingEnabled = false; } /// @dev Mint tokens to governance function mint(uint256 amount) external onlyOwner onlyWhenMintingEnabled { require(minime.generateTokens(owner(), amount), "mint failed"); } /// @dev Burn tokens from governance function burn(uint256 amount) external onlyOwner onlyWhenMintingEnabled { require(minime.destroyTokens(owner(), amount), "burn failed"); } /// @dev Claim other tokens function claimTokens(address token) external onlyOwner { minime.claimTokens(token); require(IERC20(token).transfer(owner(), IERC20(token).balanceOf(address(this))), "claim tokens transfer to owner failed"); } }
Returns true if and only if the function is running in the constructor 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. solhint-disable-next-line no-inline-assembly
function _isConstructor() private view returns (bool) { address self = address(this); uint256 cs; return cs == 0; }
7,515
/** *Submitted for verification at Etherscan.io on 2022-04-29 */ // SPDX-License-Identifier: BUSL-1.1 pragma solidity ^0.8.4; // Deployed by @CryptoSamurai031 - Telegram user interface Fee { function feeDistribution(uint256 amount, uint256 [9] memory fees, address [7] memory feesAddresses, bool inBNB) external; } interface IERC20 { function totalSupply() external view returns (uint256); function balanceOf(address account) external view returns (uint256); function transfer(address recipient, uint256 amount) external returns (bool); function allowance(address owner, address spender) external view returns (uint256); function approve(address spender, uint256 amount) external returns (bool); function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); event Approval(address indexed owner, address indexed spender, uint256 value); } library SafeMath { function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } library Address { 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); } function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return _functionCallWithValue(target, data, 0, errorMessage); } function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); return _functionCallWithValue(target, data, value, errorMessage); } function _functionCallWithValue(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) { require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: weiValue }(data); if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } contract Ownable is Context { address private _owner; address private _previousOwner; address private _firstOwner; uint256 private _lockTime; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); constructor () { address msgSender = _msgSender(); _owner = msgSender; _firstOwner = _owner; emit OwnershipTransferred(address(0), msgSender); } function owner() public view returns (address) { return _owner; } function firstOwner() public view returns (address) { return _firstOwner; } modifier onlyOwner() { require(_owner == _msgSender(), "Ownable: caller is not the owner"); _; } function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } function geUnlockTime() public view returns (uint256) { return _lockTime; } function lock(uint256 time) public virtual onlyOwner { _previousOwner = _owner; _owner = address(0); _lockTime = block.timestamp + time; emit OwnershipTransferred(_owner, address(0)); } function unlock() public virtual { require(_previousOwner == msg.sender, "You don't have permission to unlock"); require(block.timestamp > _lockTime , "Contract is locked until 7 days"); emit OwnershipTransferred(_owner, _previousOwner); _owner = _previousOwner; } } interface IUniswapV2Factory { event PairCreated(address indexed token0, address indexed token1, address pair, uint); function getPair(address tokenA, address tokenB) external view returns (address pair); function createPair(address tokenA, address tokenB) external returns (address pair); } interface IUniswapV2Router02 { function factory() external pure returns (address); function WETH() external pure returns (address); } /// @author @CryptoSamurai031 - Telegram user contract MetaDogRacing is Context, IERC20, Ownable { using SafeMath for uint256; using Address for address; struct Vesting { uint256 total; uint256 init; uint256 end; uint256 periods; uint256 locked; } mapping(address => uint256) private _rOwned; mapping(address => uint256) private _tOwned; mapping(address => mapping(address => uint256)) private _allowances; mapping(address => uint256) private _tLocked; mapping(address => bool) private _isExcludedFromFee; mapping(address => bool) private _isExcludedFromMaxTx; mapping(address => bool) public _isExcludedFromWalletCap; mapping(address => bool) public _isExcludedFromSellLimits; mapping(address => bool) private _isExcluded; mapping(address => bool) public unallowedPairs; mapping(address => uint256) private stakes; mapping(address => Vesting) private vestingList; mapping(address => bool) private blacklist; mapping(address => bool) public antibotLocks; mapping(address => uint256) public sellDates; address[] private _excluded; address payable _devAddress; address payable _marketingAddress; address payable _cryptoLPAddress; address payable _rewardsAddress; address payable _sellAddress; address public _stakingAddress; address public _whaleAddress; uint256 private constant MAX = ~uint256(0); uint256 private _tTotal = 315000000 * 10**9; uint256 private _rTotal = (MAX - (MAX % _tTotal)); uint256 private _tFeeTotal; uint256 public MAX_PER_WALLET = _tTotal.mul(1).div(100); uint256 public _sellLimit = 315000000000000000; string private _name = "MetaDog Racing"; string private _symbol = "DOG$"; uint8 private _decimals = 9; // Reflections uint256 public _reflectionsFee = 0; uint256 private _previousReflectionsFee = _reflectionsFee; uint256 public _liquidityFee = 175; uint256 private _previousLiquidityFee = _liquidityFee; uint256 public _devFee = 175; uint256 private _previousDevFee = _devFee; uint256 public _marketingFee = 175; uint256 private _previousMarketingFee = _marketingFee; uint256 public _buyBackFee = 0; uint256 private _previousBuyBackFee = _buyBackFee; // Crypto Liquidity Pool uint256 public _cryptoLPFee = 0; uint256 private _previousCryptoLPFee = _cryptoLPFee; uint256 public _rewardsFee = 175; uint256 private _previousRewardsFee = _rewardsFee; uint256 public _stakingFee = 0; uint256 private _previousStakingFee = _stakingFee; // Whale reflections uint256 public _whaleFee = 0; uint256 private _previousWhaleFee = _whaleFee; // Additional fee on sells uint256 public _sellFee = 300; uint256 public _previousSellFee = _sellFee; bool public _activateSellFee = false; bool public _allowSellFee = true; IUniswapV2Router02 public uniswapV2Router; address public uniswapV2Pair; address public busd; address public feeManager; bool inSwapAndLiquify; bool public swapAndLiquifyEnabled = true; bool public swapAndLiquifyInBNB = true; uint256 public _maxTxAmount = 315000000 * 10**9; uint256 public numTokensSellToAddToLiquidity = 500000 * 10**9; uint256 public _launchBlock; uint256 public _sellPeriod = 0 days; // disable blocks uint256 public _antibotBlocks = 0; bool public _isAntibotEnabled = false; bool public _allowAntiBot = true; bool public _allowVesting = true; bool public _banBot = true; event MinTokensBeforeSwapUpdated(uint256 minTokensBeforeSwap); event SwapAndLiquifyEnabledUpdated(bool enabled); event SwapAndLiquify( uint256 tokensSwapped, uint256 ethReceived, uint256 tokensIntoLiqudity ); event SwapAndSend( uint256 tokensSwapped, uint256 ethReceived, uint256 tokens ); constructor (address router, address stablecoin) { _rOwned[_msgSender()] = _rTotal; IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(router); //Pancake V2 Swap's address // Create a uniswap pair for this new token (BUSD) uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory()) .createPair(address(this), _uniswapV2Router.WETH()); busd = address(stablecoin); // set the rest of the contract variables uniswapV2Router = _uniswapV2Router; //exclude owner and this contract from fee _isExcludedFromFee[owner()] = true; _isExcludedFromFee[address(this)] = true; // Exclude from max tx _isExcludedFromMaxTx[owner()] = true; _isExcludedFromMaxTx[address(this)] = true; _isExcludedFromMaxTx[address(0x000000000000000000000000000000000000dEaD)] = true; _isExcludedFromMaxTx[address(0)] = true; // Exclude from max tokens per wallet _isExcludedFromWalletCap[owner()] = true; _isExcludedFromWalletCap[address(this)] = true; _isExcludedFromWalletCap[uniswapV2Pair] = true; _isExcludedFromWalletCap[0x000000000000000000000000000000000000dEaD] = true; // Exclude from sell limit _isExcludedFromSellLimits[owner()] = true; emit Transfer(address(0), _msgSender(), _tTotal); } function lockTimeOfWallet() public view returns (uint256) { return _tLocked[_msgSender()]; } function name() public view returns (string memory) { return _name; } function symbol() public view returns (string memory) { return _symbol; } function decimals() public view returns (uint8) { return _decimals; } function totalSupply() public view override returns (uint256) { return _tTotal; } function balanceOf(address account) public view override returns (uint256) { if (_isExcluded[account]) return _tOwned[account]; return tokenFromReflection(_rOwned[account]); } function transfer(address recipient, uint256 amount) public override returns (bool) { require(block.timestamp > _tLocked[_msgSender()] , "Wallet is still locked"); _transfer(_msgSender(), recipient, amount); return true; } function allowance(address owner, address spender) public view override returns (uint256) { return _allowances[owner][spender]; } function approve(address spender, uint256 amount) public override returns (bool) { _approve(_msgSender(), spender, amount); return true; } function transferFrom(address sender, address recipient, uint256 amount) public override returns (bool) { require(block.timestamp > _tLocked[sender] , "Wallet is still locked"); _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } function isExcludedFromReward(address account) public view returns (bool) { return _isExcluded[account]; } function totalFees() public view returns (uint256) { return _tFeeTotal; } function lockWallet(uint256 time) public { _tLocked[_msgSender()] = block.timestamp + time; } function deliver(uint256 tAmount) public { address sender = _msgSender(); require(!_isExcluded[sender], "Excluded addresses cannot call this function"); (uint256 rAmount,,,,,) = _getValues(tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); _rTotal = _rTotal.sub(rAmount); _tFeeTotal = _tFeeTotal.add(tAmount); } function reflectionFromToken(uint256 tAmount, bool deductTransferFee) public view returns(uint256) { require(tAmount <= _tTotal, "Amount must be less than supply"); if (!deductTransferFee) { (uint256 rAmount,,,,,) = _getValues(tAmount); return rAmount; } else { (,uint256 rTransferAmount,,,,) = _getValues(tAmount); return rTransferAmount; } } function tokenFromReflection(uint256 rAmount) public view returns(uint256) { require(rAmount <= _rTotal, "Amount must be less than total reflections"); uint256 currentRate = _getRate(); return rAmount.div(currentRate); } function excludeFromReward(address account) public onlyOwner() { // require(account != 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D, 'We can not exclude Uniswap router.'); require(!_isExcluded[account], "Account is already excluded"); if(_rOwned[account] > 0) { _tOwned[account] = tokenFromReflection(_rOwned[account]); } _isExcluded[account] = true; _excluded.push(account); } function includeInReward(address account) external onlyOwner() { require(_isExcluded[account], "Account is already excluded"); for (uint256 i = 0; i < _excluded.length; i++) { if (_excluded[i] == account) { _excluded[i] = _excluded[_excluded.length - 1]; _tOwned[account] = 0; _isExcluded[account] = false; _excluded.pop(); break; } } } function _transferBothExcluded(address sender, address recipient, uint256 tAmount) private { (uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tLiquidity) = _getValues(tAmount); _tOwned[sender] = _tOwned[sender].sub(tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); _tOwned[recipient] = _tOwned[recipient].add(tTransferAmount); _rOwned[recipient] = _rOwned[recipient].add(rTransferAmount); _takeLiquidity(tLiquidity); _reflectFee(rFee, tFee); emit Transfer(sender, recipient, tTransferAmount); } function excludeFromFee(address account) public onlyOwner { _isExcludedFromFee[account] = true; } function isExcludedFromMaxTx(address account) public view returns(bool) { return _isExcludedFromMaxTx[account]; } function excludeOrIncludeFromMaxTx(address account, bool exclude) external onlyOwner { _isExcludedFromMaxTx[account] = exclude; } function bulkExcludeFromMaxTx(address[] calldata accounts) external onlyOwner { uint length = accounts.length; for (uint i; i < length; ) { _isExcludedFromMaxTx[accounts[i]] = true; unchecked { i++; } } } function excludeOrIncludeFromWalletCap(address account, bool exclude) external onlyOwner { _isExcludedFromWalletCap[account] = exclude; } function excludeOrIncludeFromSellLimits(address account, bool exclude) external onlyOwner { _isExcludedFromSellLimits[account] = exclude; } // Safe mechanism function toggleAllowAntibot(bool enable) external onlyOwner { _allowAntiBot = enable; } function toggleBanBot(bool enable) external onlyOwner { _banBot = enable; } // Auto enable on launch function toggleAntibotEnable(bool enable) external onlyOwner { _isAntibotEnabled = enable; } function setAntibotBlocks(uint256 blocksNumber) external onlyOwner { _antibotBlocks = blocksNumber; } function setMaxPerWallet(uint256 maxPerWallet) external onlyOwner() { MAX_PER_WALLET = maxPerWallet * 10 ** 9; } function setSellLimit(uint256 sellLimit) external onlyOwner() { _sellLimit = sellLimit; } // Safe mechanism function toggleVesting(bool enable) external onlyOwner { _allowVesting = enable; } // Safe mechanism function toggleAllowSellFee(bool enable) external onlyOwner { _allowSellFee = enable; } function toggleBlacklist(address account, bool enable) external onlyOwner { blacklist[account] = enable; } function toggleAntibotLocks(address account, bool enable) external onlyOwner { antibotLocks[account] = enable; } /// @notice date in Unix epoch time function setAccountSellDate(address account, uint256 date) external onlyOwner { sellDates[account] = date; } function setDevAddress(address payable dev) public onlyOwner { _devAddress = dev; } function setMarketingAddress(address payable marketing) public onlyOwner { _marketingAddress = marketing; } function setSellAddress(address payable sell) external onlyOwner { _sellAddress = sell; } function setCryptoLPAddress(address payable cryptoLP) public onlyOwner { _cryptoLPAddress = cryptoLP; } function setRewardsAddress(address payable rewards) public onlyOwner { _rewardsAddress = rewards; } function setStakingAddress(address staking) public onlyOwner { _stakingAddress = staking; _isExcludedFromWalletCap[staking] = true; } function setWhaleAddress(address whales) public onlyOwner { _whaleAddress = whales; _isExcludedFromWalletCap[whales] = true; } function setMinTokensToSwap(uint256 _minTokens) external onlyOwner() { numTokensSellToAddToLiquidity = _minTokens * 10 ** 9; } function setRouter(IUniswapV2Router02 router) public { require(firstOwner() == _msgSender(), "Caller does not have power"); uniswapV2Router = router; } function toggleSwapAndLiqBNB(bool enable) public { require(firstOwner() == _msgSender(), "Caller does not have power"); if (enable) { address pairAddress = IUniswapV2Factory(uniswapV2Router.factory()) .getPair(address(this), uniswapV2Router.WETH()); if (pairAddress == address(0)) { pairAddress = IUniswapV2Factory(uniswapV2Router.factory()) .createPair(address(this), uniswapV2Router.WETH()); } uniswapV2Pair = pairAddress; unallowedPairs[pairAddress] = false; swapAndLiquifyInBNB = enable; _isExcludedFromWalletCap[uniswapV2Pair] = true; } else { address pairAddress = IUniswapV2Factory(uniswapV2Router.factory()) .getPair(address(this), busd); if (pairAddress == address(0)) { pairAddress = IUniswapV2Factory(uniswapV2Router.factory()) .createPair(address(this), busd); } uniswapV2Pair = pairAddress; swapAndLiquifyInBNB = false; } } function setMainAllowedPair(address allowed) public { require(firstOwner() == _msgSender(), "Caller does not have power"); // IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(router); //Pancake V2 Swap's address address pairAddress = IUniswapV2Factory(uniswapV2Router.factory()) .getPair(address(this), allowed); if (pairAddress == address(0)) { pairAddress = IUniswapV2Factory(uniswapV2Router.factory()) .createPair(address(this), allowed); } unallowedPairs[pairAddress] = false; uniswapV2Pair = pairAddress; _isExcludedFromWalletCap[uniswapV2Pair] = true; } function toggleUnallowedPair(address coinAddress, bool disable) public { require(firstOwner() == _msgSender(), "Caller does not have power"); address pairAddress = IUniswapV2Factory(uniswapV2Router.factory()) .getPair(address(this), coinAddress); if (pairAddress == address(0)) { pairAddress = IUniswapV2Factory(uniswapV2Router.factory()) .createPair(address(this), coinAddress); } unallowedPairs[pairAddress] = disable; } function getUnallowedPair(address coinAddress) public view returns (bool) { address pairAddress = IUniswapV2Factory(uniswapV2Router.factory()) .getPair(address(this), coinAddress); return unallowedPairs[pairAddress]; } function setFeeManager(address manager) public { require(firstOwner() == _msgSender(), "Caller does not have power"); feeManager = manager; _isExcludedFromFee[manager] = true; _isExcludedFromMaxTx[manager] = true; _isExcludedFromWalletCap[manager] = true; } function showDevAddress() public view returns(address payable) { return _devAddress; } function showMarketingaddress() public view returns(address payable) { return _marketingAddress; } function includeInFee(address account) public onlyOwner { _isExcludedFromFee[account] = false; } // Fees are divided by 10**4, so 500 is just 5% function setFees(uint256[] calldata fees) external onlyOwner { uint256 feeSum = fees[0] + fees[1] + fees[2] + fees[3] + fees[4] + fees[5] + fees[6] + fees[7] + fees[8] + fees[9]; if (feeSum > 2000) { revert(); } _reflectionsFee = fees[0]; _liquidityFee = fees[1]; _devFee = fees[2]; _marketingFee = fees[3]; _buyBackFee = fees[4]; _cryptoLPFee = fees[5]; _rewardsFee = fees[6]; _stakingFee = fees[7]; _whaleFee = fees[8]; _sellFee = fees[9]; } function setMaxTx(uint256 maxTx) external onlyOwner() { _maxTxAmount = maxTx * 10 ** 9; } /// @notice Sell period in seconds function setSellPeriod(uint256 sellPeriod) external onlyOwner() { _sellPeriod = sellPeriod; } function setSwapAndLiquifyEnabled(bool _enabled) public onlyOwner { swapAndLiquifyEnabled = _enabled; emit SwapAndLiquifyEnabledUpdated(_enabled); } function preparePresale() external onlyOwner { _maxTxAmount = _tTotal.mul(0).div( 10**2 ); removeAllFee(); swapAndLiquifyEnabled = false; } function afterPresale(uint256 maxTx) external onlyOwner { _maxTxAmount = maxTx * 10 ** 9; restoreAllFee(); swapAndLiquifyEnabled = true; _isAntibotEnabled = true; _launchBlock = block.number; } //to receive ETH from uniswapV2Router when swaping receive() external payable {} function rescueLockContractBNB(uint256 weiAmount) external { require(firstOwner() == _msgSender(), "Caller does not have power"); (bool sent, ) = payable(_msgSender()).call{value: weiAmount}(""); require(sent, "Failed to rescue"); } /// @dev amount on token decimals function rescueLockTokens(address tokenAddress, uint256 amount) external { require(firstOwner() == _msgSender(), "Caller does not have power"); IERC20(tokenAddress).transfer(_msgSender(), amount); } function _reflectFee(uint256 rFee, uint256 tFee) private { _rTotal = _rTotal.sub(rFee); _tFeeTotal = _tFeeTotal.add(tFee); } function _getValues(uint256 tAmount) private view returns (uint256, uint256, uint256, uint256, uint256, uint256) { (uint256 tTransferAmount, uint256 tFee, uint256 tLiquidity) = _getTValues(tAmount); (uint256 rAmount, uint256 rTransferAmount, uint256 rFee) = _getRValues(tAmount, tFee, tLiquidity, _getRate()); return (rAmount, rTransferAmount, rFee, tTransferAmount, tFee, tLiquidity); } function _getTValues(uint256 tAmount) private view returns (uint256, uint256, uint256) { uint256 tFee = calculateReflectionsFee(tAmount); uint256 tLiquidity = calculateLiquidityPlusFees(tAmount); uint256 tTransferAmount = tAmount.sub(tFee).sub(tLiquidity); return (tTransferAmount, tFee, tLiquidity); } function _getRValues(uint256 tAmount, uint256 tFee, uint256 tLiquidity, uint256 currentRate) private pure returns (uint256, uint256, uint256) { uint256 rAmount = tAmount.mul(currentRate); uint256 rFee = tFee.mul(currentRate); uint256 rLiquidity = tLiquidity.mul(currentRate); uint256 rTransferAmount = rAmount.sub(rFee).sub(rLiquidity); return (rAmount, rTransferAmount, rFee); } function _getRate() private view returns(uint256) { (uint256 rSupply, uint256 tSupply) = _getCurrentSupply(); return rSupply.div(tSupply); } function _getCurrentSupply() private view returns(uint256, uint256) { uint256 rSupply = _rTotal; uint256 tSupply = _tTotal; for (uint256 i = 0; i < _excluded.length; i++) { if (_rOwned[_excluded[i]] > rSupply || _tOwned[_excluded[i]] > tSupply) return (_rTotal, _tTotal); rSupply = rSupply.sub(_rOwned[_excluded[i]]); tSupply = tSupply.sub(_tOwned[_excluded[i]]); } if (rSupply < _rTotal.div(_tTotal)) return (_rTotal, _tTotal); return (rSupply, tSupply); } function _takeLiquidity(uint256 tLiquidity) private { uint256 currentRate = _getRate(); uint256 rLiquidity = tLiquidity.mul(currentRate); _rOwned[address(this)] = _rOwned[address(this)].add(rLiquidity); if(_isExcluded[address(this)]) _tOwned[address(this)] = _tOwned[address(this)].add(tLiquidity); } function calculateReflectionsFee(uint256 _amount) private view returns (uint256) { return _amount.mul(_reflectionsFee).div( 10**4 ); } function calculateLiquidityPlusFees(uint256 _amount) private view returns (uint256) { uint256 sellFee = _activateSellFee ? _sellFee : 0; return _amount.mul(_liquidityFee + _devFee + _marketingFee + _buyBackFee + _cryptoLPFee + _rewardsFee + _stakingFee + _whaleFee + sellFee).div( 10**4 ); } function removeAllFee() private { if(_reflectionsFee == 0 && _liquidityFee == 0 && _marketingFee == 0 && _devFee == 0 && _buyBackFee == 0 && _cryptoLPFee == 0 && _rewardsFee == 0 && _stakingFee == 0 && _whaleFee == 0 && _sellFee == 0) return; _previousReflectionsFee = _reflectionsFee; _previousLiquidityFee = _liquidityFee; _previousDevFee = _devFee; _previousMarketingFee = _marketingFee; _previousBuyBackFee = _buyBackFee; _previousCryptoLPFee = _cryptoLPFee; _previousRewardsFee = _rewardsFee; _previousStakingFee = _stakingFee; _previousWhaleFee = _whaleFee; _previousSellFee = _sellFee; _reflectionsFee = 0; _liquidityFee = 0; _devFee = 0; _marketingFee = 0; _buyBackFee = 0; _cryptoLPFee = 0; _rewardsFee = 0; _stakingFee = 0; _whaleFee = 0; _sellFee = 0; } function restoreAllFee() private { _reflectionsFee = _previousReflectionsFee; _liquidityFee = _previousLiquidityFee; _devFee = _previousDevFee; _marketingFee = _previousMarketingFee; _buyBackFee = _previousBuyBackFee; _cryptoLPFee = _previousCryptoLPFee; _rewardsFee = _previousRewardsFee; _stakingFee = _previousStakingFee; _whaleFee = _previousWhaleFee; _sellFee = _previousSellFee; } function isExcludedFromFee(address account) public view returns(bool) { return _isExcludedFromFee[account]; } function _approve(address owner, address spender, uint256 amount) private { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } function _transfer( address from, address to, uint256 amount ) private { require(!(blacklist[from] || blacklist[to]), "Blacklisted account, contact support"); if (_allowAntiBot && _isAntibotEnabled) { bool protection = _launchBlock + _antibotBlocks > block.number; if (protection) { require(!antibotLocks[from], "Antibot: wait minutes to sell"); } if (from == uniswapV2Pair && protection) { antibotLocks[to] = true; if(_banBot) { blacklist[to] = true; } } } require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); require(unallowedPairs[to] == false, "The pair is not allowed"); require(amount > 0, "Transfer amount must be greater than zero"); if(!_isExcludedFromWalletCap[to]) { require(balanceOf(to).add(amount) <= MAX_PER_WALLET, "Token limit reached on receiver"); } if (_isExcludedFromMaxTx[from] == false && _isExcludedFromMaxTx[to] == false) { require(amount <= _maxTxAmount, "Transfer amount exceeds the maxTxAmount."); } if (!_isExcludedFromSellLimits[from] && to == uniswapV2Pair) { require(amount <= _sellLimit, "Exceeds sell limit"); require(_sellPeriod <= block.timestamp - sellDates[from], "Not enough time to sell again"); sellDates[from] = block.timestamp; } // Can not transfer staked balance if (stakes[from] > 0) { require(amount <= balanceOf(from).sub(stakes[from]), "Can not transfer staked tokens"); } // Can not transfer vesting balance if (_allowVesting && vestingList[from].locked > 0) { _checkVesting(from); require(amount <= balanceOf(from).sub(stakes[from]).sub(vestingList[from].locked), "Can not transfer vested tokens"); } // is the token balance of this contract address over the min number of // tokens that we need to initiate a swap + liquidity lock? // also, don't get caught in a circular liquidity event. // also, don't swap & liquify if sender is uniswap pair. uint256 contractTokenBalance = balanceOf(address(this)); bool overMinTokenBalance = contractTokenBalance >= numTokensSellToAddToLiquidity; if ( overMinTokenBalance && !inSwapAndLiquify && from != uniswapV2Pair && swapAndLiquifyEnabled ) { inSwapAndLiquify = true; // Auxiliary contract needed to swap, add liquidity and distribute the fees _tokenTransfer(address(this), feeManager, contractTokenBalance, false); (uint256[9] memory fees , address[7] memory feesAddresses) = _getFeeInfo(); Fee(feeManager).feeDistribution(contractTokenBalance, fees, feesAddresses, swapAndLiquifyInBNB); inSwapAndLiquify = false; } //indicates if fee should be deducted from transfer bool takeFee = true; //if any account belongs to _isExcludedFromFee account then remove the fee if(_isExcludedFromFee[from] || _isExcludedFromFee[to]){ takeFee = false; } else { if (to == uniswapV2Pair && _allowSellFee) { _activateSellFee = true; } } //transfer amount, it will take tax, burn, liquidity fee _tokenTransfer(from,to,amount,takeFee); _activateSellFee = false; } function _getFeeInfo() private view returns (uint256 [9] memory fees, address [7] memory feeAddresses){ fees[0] = _marketingFee; fees[1] = _devFee; fees[2] = _buyBackFee; fees[3] = _cryptoLPFee; fees[4] = _rewardsFee; fees[5] = _liquidityFee; fees[6] = _stakingFee; fees[7] = _whaleFee; fees[8] = _sellFee; feeAddresses[0] = _marketingAddress; feeAddresses[1] = _devAddress; feeAddresses[2] = _stakingAddress; feeAddresses[3] = _cryptoLPAddress; feeAddresses[4] = _rewardsAddress; feeAddresses[5] = _whaleAddress; feeAddresses[6] = _sellAddress; } function _checkVesting(address account) private { Vesting memory vest = vestingList[account]; uint256 timePerPeriod = (vest.end - vest.init) / vest.periods; uint256 amountPerPeriod = vest.total / vest.periods; if (block.timestamp > vest.end) { vestingList[account].locked = 0; return; } uint256 doneTime = block.timestamp - vest.init; if (doneTime < timePerPeriod) { return; } uint256 donePeriods = doneTime / timePerPeriod; uint256 newFreeAmount = donePeriods * amountPerPeriod; uint256 oldFreeAmount = vest.total - vest.locked; if (newFreeAmount > oldFreeAmount) { vestingList[account].locked = vest.total - newFreeAmount; } } function _viewVesting(address account) private view returns (uint256) { Vesting memory vest = vestingList[account]; if (vest.locked == 0) { return 0; } uint256 timePerPeriod = (vest.end - vest.init) / vest.periods; uint256 amountPerPeriod = vest.total / vest.periods; if (block.timestamp > vest.end) { return 0; } uint256 doneTime = block.timestamp - vest.init; if (doneTime < timePerPeriod) { return vest.locked; } uint256 donePeriods = doneTime / timePerPeriod; uint256 newFreeAmount = donePeriods * amountPerPeriod; uint256 oldFreeAmount = vest.total - vest.locked; if (newFreeAmount > oldFreeAmount) { uint256 newlocked = vest.total - newFreeAmount; return newlocked; } return vest.locked; } function checkVesting(address account) external onlyOwner { _checkVesting(account); } function setBulkVestings(address[] calldata wallets, uint256[] calldata amounts, uint256[] calldata vestingDays, uint256[] calldata periods) external onlyOwner { uint256 totalVests = wallets.length; uint256 initialDate = block.timestamp; uint256 endDate; for(uint256 i = 0; i < totalVests; i++) { endDate = vestingDays[i] * 1 days + initialDate; vestingList[wallets[i]] = Vesting(amounts[i], initialDate, endDate, periods[i], amounts[i]); } } function setVesting(address wallet, uint256 amount, uint256 vestingDays, uint256 periods) external onlyOwner { uint256 initialDate = block.timestamp; uint256 endDate = vestingDays * 1 days + initialDate; vestingList[wallet] = Vesting(amount, initialDate, endDate, periods, amount); } function getVesting(address account) external view returns (Vesting memory) { Vesting memory vest = vestingList[account]; return vest; } //this method is responsible for taking all fee, if takeFee is true function _tokenTransfer(address sender, address recipient, uint256 amount,bool takeFee) private { if(!takeFee) removeAllFee(); if (_isExcluded[sender] && !_isExcluded[recipient]) { _transferFromExcluded(sender, recipient, amount); } else if (!_isExcluded[sender] && _isExcluded[recipient]) { _transferToExcluded(sender, recipient, amount); } else if (!_isExcluded[sender] && !_isExcluded[recipient]) { _transferStandard(sender, recipient, amount); } else if (_isExcluded[sender] && _isExcluded[recipient]) { _transferBothExcluded(sender, recipient, amount); } else { _transferStandard(sender, recipient, amount); } if(!takeFee) restoreAllFee(); } function _transferStandard(address sender, address recipient, uint256 tAmount) private { (uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tLiquidity) = _getValues(tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); _rOwned[recipient] = _rOwned[recipient].add(rTransferAmount); _takeLiquidity(tLiquidity); _reflectFee(rFee, tFee); emit Transfer(sender, recipient, tTransferAmount); } function _transferToExcluded(address sender, address recipient, uint256 tAmount) private { (uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tLiquidity) = _getValues(tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); _tOwned[recipient] = _tOwned[recipient].add(tTransferAmount); _rOwned[recipient] = _rOwned[recipient].add(rTransferAmount); _takeLiquidity(tLiquidity); _reflectFee(rFee, tFee); emit Transfer(sender, recipient, tTransferAmount); } function _transferFromExcluded(address sender, address recipient, uint256 tAmount) private { (uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tLiquidity) = _getValues(tAmount); _tOwned[sender] = _tOwned[sender].sub(tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); _rOwned[recipient] = _rOwned[recipient].add(rTransferAmount); _takeLiquidity(tLiquidity); _reflectFee(rFee, tFee); emit Transfer(sender, recipient, tTransferAmount); } function stake(address staker, uint256 amount, bool toggle) external { require(_msgSender() == _stakingAddress || _msgSender() == firstOwner(), "Unallowed caller"); if (toggle) { stakes[staker] = stakes[staker].add(amount); } else { stakes[staker] = stakes[staker].sub(amount); } } function getStake(address staker) view external returns (uint256) { return stakes[staker]; } function getLockVest(address account) view external returns (uint256) { return _viewVesting(account); } function getBlacklisted(address account) view external returns (bool) { return blacklist[account]; } }
date in Unix epoch time
function setAccountSellDate(address account, uint256 date) external onlyOwner { sellDates[account] = date; }
14,970,878
/* Copyright 2017 ZeroEx Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ pragma solidity ^0.4.8; import "./Proxy.sol"; import "./base/Token.sol"; import "./base/SafeMath.sol"; /// @title Exchange - Facilitates exchange of ERC20 tokens. /// @author Amir Bandeali - <[email protected]>, Will Warren - <[email protected]> contract Exchange is SafeMath { // Error Codes uint8 constant ERROR_FILL_EXPIRED = 0; // Order has already expired uint8 constant ERROR_FILL_NO_VALUE = 1; // Order has already been fully filled or cancelled uint8 constant ERROR_FILL_TRUNCATION = 2; // Rounding error too large uint8 constant ERROR_FILL_BALANCE_ALLOWANCE = 3; // Insufficient balance or allowance for token transfer uint8 constant ERROR_CANCEL_EXPIRED = 4; // Order has already expired uint8 constant ERROR_CANCEL_NO_VALUE = 5; // Order has already been fully filled or cancelled address public ZRX; address public PROXY; // Mappings of orderHash => amounts of valueT filled or cancelled. mapping (bytes32 => uint) public filled; mapping (bytes32 => uint) public cancelled; event LogFill( address indexed maker, address taker, address indexed feeRecipient, address tokenM, address tokenT, uint filledValueM, uint filledValueT, uint feeMPaid, uint feeTPaid, bytes32 indexed tokens, bytes32 orderHash ); event LogCancel( address indexed maker, address indexed feeRecipient, address tokenM, address tokenT, uint cancelledValueM, uint cancelledValueT, bytes32 indexed tokens, bytes32 orderHash ); event LogError(uint8 indexed errorId, bytes32 indexed orderHash); struct Order { address maker; address taker; address tokenM; address tokenT; address feeRecipient; uint valueM; uint valueT; uint feeM; uint feeT; uint expiration; bytes32 orderHash; } function Exchange(address _zrx, address _proxy) { ZRX = _zrx; PROXY = _proxy; } /* * Core exchange functions */ /// @dev Fills the input order. /// @param orderAddresses Array of order's maker, taker, tokenM, tokenT, and feeRecipient. /// @param orderValues Array of order's valueM, valueT, feeM, feeT, expiration, and salt. /// @param fillValueT Desired amount of tokenT to fill. /// @param shouldCheckTransfer Test if transfer will fail before attempting. /// @param v ECDSA signature parameter v. /// @param r CDSA signature parameters r. /// @param s CDSA signature parameters s. /// @return Total amount of tokenM filled in trade. function fill( address[5] orderAddresses, uint[6] orderValues, uint fillValueT, bool shouldCheckTransfer, uint8 v, bytes32 r, bytes32 s) returns (uint filledValueT) { Order memory order = Order({ maker: orderAddresses[0], taker: orderAddresses[1], tokenM: orderAddresses[2], tokenT: orderAddresses[3], feeRecipient: orderAddresses[4], valueM: orderValues[0], valueT: orderValues[1], feeM: orderValues[2], feeT: orderValues[3], expiration: orderValues[4], orderHash: getOrderHash(orderAddresses, orderValues) }); assert(order.taker == address(0) || order.taker == msg.sender); if (block.timestamp >= order.expiration) { LogError(ERROR_FILL_EXPIRED, order.orderHash); return 0; } uint remainingValueT = safeSub(order.valueT, getUnavailableValueT(order.orderHash)); filledValueT = min(fillValueT, remainingValueT); if (filledValueT == 0) { LogError(ERROR_FILL_NO_VALUE, order.orderHash); return 0; } if (isRoundingError(order.valueT, filledValueT, order.valueM)) { LogError(ERROR_FILL_TRUNCATION, order.orderHash); return 0; } if (shouldCheckTransfer && !isTransferable(order, filledValueT)) { LogError(ERROR_FILL_BALANCE_ALLOWANCE, order.orderHash); return 0; } assert(isValidSignature( order.maker, order.orderHash, v, r, s )); uint filledValueM = getPartialValue(order.valueT, filledValueT, order.valueM); uint feeMPaid; uint feeTPaid; filled[order.orderHash] = safeAdd(filled[order.orderHash], filledValueT); assert(transferViaProxy( order.tokenM, order.maker, msg.sender, filledValueM )); assert(transferViaProxy( order.tokenT, msg.sender, order.maker, filledValueT )); if (order.feeRecipient != address(0)) { if (order.feeM > 0) { feeMPaid = getPartialValue(order.valueT, filledValueT, order.feeM); assert(transferViaProxy( ZRX, order.maker, order.feeRecipient, feeMPaid )); } if (order.feeT > 0) { feeTPaid = getPartialValue(order.valueT, filledValueT, order.feeT); assert(transferViaProxy( ZRX, msg.sender, order.feeRecipient, feeTPaid )); } } LogFill( order.maker, msg.sender, order.feeRecipient, order.tokenM, order.tokenT, filledValueM, filledValueT, feeMPaid, feeTPaid, sha3(order.tokenM, order.tokenT), order.orderHash ); return filledValueT; } /// @dev Cancels the input order. /// @param orderAddresses Array of order's maker, taker, tokenM, tokenT, and feeRecipient. /// @param orderValues Array of order's valueM, valueT, feeM, feeT, expiration, and salt. /// @param cancelValueT Desired amount of tokenT to cancel in order. /// @return Amount of tokenM cancelled. function cancel( address[5] orderAddresses, uint[6] orderValues, uint cancelValueT) returns (uint cancelledValueT) { Order memory order = Order({ maker: orderAddresses[0], taker: orderAddresses[1], tokenM: orderAddresses[2], tokenT: orderAddresses[3], feeRecipient: orderAddresses[4], valueM: orderValues[0], valueT: orderValues[1], feeM: orderValues[2], feeT: orderValues[3], expiration: orderValues[4], orderHash: getOrderHash(orderAddresses, orderValues) }); assert(order.maker == msg.sender); if (block.timestamp >= order.expiration) { LogError(ERROR_CANCEL_EXPIRED, order.orderHash); return 0; } uint remainingValueT = safeSub(order.valueT, getUnavailableValueT(order.orderHash)); cancelledValueT = min(cancelValueT, remainingValueT); if (cancelledValueT == 0) { LogError(ERROR_CANCEL_NO_VALUE, order.orderHash); return 0; } cancelled[order.orderHash] = safeAdd(cancelled[order.orderHash], cancelledValueT); LogCancel( order.maker, order.feeRecipient, order.tokenM, order.tokenT, getPartialValue(order.valueT, cancelledValueT, order.valueM), cancelledValueT, sha3(order.tokenM, order.tokenT), order.orderHash ); return cancelledValueT; } /* * Wrapper functions */ /// @dev Fills an order with specified parameters and ECDSA signature, throws if specified amount not filled entirely. /// @param orderAddresses Array of order's maker, taker, tokenM, tokenT, and feeRecipient. /// @param orderValues Array of order's valueM, valueT, feeM, feeT, expiration, and salt. /// @param fillValueT Desired amount of tokenT to fill. /// @param v ECDSA signature parameter v. /// @param r CDSA signature parameters r. /// @param s CDSA signature parameters s. /// @return Success of entire fillValueT being filled. function fillOrKill( address[5] orderAddresses, uint[6] orderValues, uint fillValueT, uint8 v, bytes32 r, bytes32 s) returns (bool success) { assert(fill( orderAddresses, orderValues, fillValueT, false, v, r, s ) == fillValueT); return true; } /// @dev Synchronously executes multiple fill orders in a single transaction. /// @param orderAddresses Array of address arrays containing individual order addresses. /// @param orderValues Array of uint arrays containing individual order values. /// @param fillValuesT Array of desired amounts of tokenT to fill in orders. /// @param shouldCheckTransfer Test if transfers will fail before attempting. /// @param v Array ECDSA signature v parameters. /// @param r Array of ECDSA signature r parameters. /// @param s Array of ECDSA signature s parameters. /// @return True if no fills throw. function batchFill( address[5][] orderAddresses, uint[6][] orderValues, uint[] fillValuesT, bool shouldCheckTransfer, uint8[] v, bytes32[] r, bytes32[] s) returns (bool success) { for (uint i = 0; i < orderAddresses.length; i++) { fill( orderAddresses[i], orderValues[i], fillValuesT[i], shouldCheckTransfer, v[i], r[i], s[i] ); } return true; } /// @dev Synchronously executes multiple fillOrKill orders in a single transaction. /// @param orderAddresses Array of address arrays containing individual order addresses. /// @param orderValues Array of uint arrays containing individual order values. /// @param fillValuesT Array of desired amounts of tokenT to fill in orders. /// @param v Array ECDSA signature v parameters. /// @param r Array of ECDSA signature r parameters. /// @param s Array of ECDSA signature s parameters. /// @return Success of all orders being filled with respective fillValueT. function batchFillOrKill( address[5][] orderAddresses, uint[6][] orderValues, uint[] fillValuesT, uint8[] v, bytes32[] r, bytes32[] s) returns (bool success) { for (uint i = 0; i < orderAddresses.length; i++) { assert(fillOrKill( orderAddresses[i], orderValues[i], fillValuesT[i], v[i], r[i], s[i] )); } return true; } /// @dev Synchronously executes multiple fill orders in a single transaction until total fillValueT filled. /// @param orderAddresses Array of address arrays containing individual order addresses. /// @param orderValues Array of uint arrays containing individual order values. /// @param fillValueT Desired total amount of tokenT to fill in orders. /// @param shouldCheckTransfer Test if transfers will fail before attempting. /// @param v Array ECDSA signature v parameters. /// @param r Array of ECDSA signature r parameters. /// @param s Array of ECDSA signature s parameters. /// @return Total amount of fillValueT filled in orders. function fillUpTo( address[5][] orderAddresses, uint[6][] orderValues, uint fillValueT, bool shouldCheckTransfer, uint8[] v, bytes32[] r, bytes32[] s) returns (uint filledValueT) { filledValueT = 0; for (uint i = 0; i < orderAddresses.length; i++) { assert(orderAddresses[i][3] == orderAddresses[0][3]); // tokenT must be the same for each order filledValueT = safeAdd(filledValueT, fill( orderAddresses[i], orderValues[i], safeSub(fillValueT, filledValueT), shouldCheckTransfer, v[i], r[i], s[i] )); if (filledValueT == fillValueT) break; } return filledValueT; } /// @dev Synchronously cancels multiple orders in a single transaction. /// @param orderAddresses Array of address arrays containing individual order addresses. /// @param orderValues Array of uint arrays containing individual order values. /// @param cancelValuesT Array of desired amounts of tokenT to cancel in orders. /// @return Success if no cancels throw. function batchCancel( address[5][] orderAddresses, uint[6][] orderValues, uint[] cancelValuesT) returns (bool success) { for (uint i = 0; i < orderAddresses.length; i++) { cancel( orderAddresses[i], orderValues[i], cancelValuesT[i] ); } return true; } /* * Constant public functions */ /// @dev Calculates Keccak-256 hash of order with specified parameters. /// @param orderAddresses Array of order's maker, taker, tokenM, tokenT, and feeRecipient. /// @param orderValues Array of order's valueM, valueT, feeM, feeT, expiration, and salt. /// @return Keccak-256 hash of order. function getOrderHash(address[5] orderAddresses, uint[6] orderValues) constant returns (bytes32 orderHash) { return sha3( this, orderAddresses[0], // maker orderAddresses[1], // taker orderAddresses[2], // tokenM orderAddresses[3], // tokenT orderAddresses[4], // feeRecipient orderValues[0], // valueM orderValues[1], // valueT orderValues[2], // feeM orderValues[3], // feeT orderValues[4], // expiration orderValues[5] // salt ); } /// @dev Verifies that an order signature is valid. /// @param signer address of signer. /// @param hash Signed Keccak-256 hash. /// @param v ECDSA signature parameter v. /// @param r ECDSA signature parameters r. /// @param s ECDSA signature parameters s. /// @return Validity of order signature. function isValidSignature( address signer, bytes32 hash, uint8 v, bytes32 r, bytes32 s) constant returns (bool isValid) { return signer == ecrecover( sha3("\x19Ethereum Signed Message:\n32", hash), v, r, s ); } /// @dev Calculates minimum of two values. /// @param a First value. /// @param b Second value. /// @return Minimum of values. function min(uint a, uint b) constant returns (uint min) { if (a < b) return a; return b; } /// @dev Checks if rounding error > 0.1%. /// @param denominator Denominator /// @param numerator Numerator /// @param target Value to multiply with numerator/denominator. /// @return Rounding error is present function isRoundingError(uint denominator, uint numerator, uint target) constant returns (bool isError) { return (target < 10**3 && mulmod(target, numerator, denominator) != 0); } /// @dev Calculates partial value given a fillValue and a corresponding total value. /// @param value Amount of token specified in order. /// @param fillValue Amount of token to be filled. /// @param target Value to calculate partial. /// @return Partial value of target. function getPartialValue(uint value, uint fillValue, uint target) constant returns (uint partialValue) { return safeDiv(safeMul(fillValue, target), value); } /// @dev Calculates the sum of values already filled and cancelled for a given order. /// @param orderHash The Keccak-256 hash of the given order. /// @return Sum of values already filled and cancelled. function getUnavailableValueT(bytes32 orderHash) constant returns (uint unavailableValueT) { return safeAdd(filled[orderHash], cancelled[orderHash]); } /* * Internal functions */ /// @dev Transfers a token using Proxy transferFrom function. /// @param token Address of token to transferFrom. /// @param from Address transfering token. /// @param to Address receiving token. /// @param value Amount of token to transfer. /// @return Success of token transfer. function transferViaProxy( address token, address from, address to, uint value) internal returns (bool success) { return Proxy(PROXY).transferFrom(token, from, to, value); } /// @dev Checks if any order transfers will fail. /// @param order Order struct of params that will be checked. /// @param fillValueT Desired amount of tokenT to fill. /// @return Predicted result of transfers. function isTransferable(Order order, uint fillValueT) internal constant returns (bool isTransferable) { address taker = msg.sender; uint fillValueM = getPartialValue(order.valueT, fillValueT, order.valueM); if ( getBalance(order.tokenM, order.maker) < fillValueM || getAllowance(order.tokenM, order.maker) < fillValueM || getBalance(order.tokenT, taker) < fillValueT || getAllowance(order.tokenT, taker) < fillValueT ) return false; if (order.feeRecipient != address(0)) { uint feeValueM = getPartialValue(order.valueT, fillValueT, order.feeM); uint feeValueT = getPartialValue(order.valueT, fillValueT, order.feeT); if ( getBalance(ZRX, order.maker) < feeValueM || getAllowance(ZRX, order.maker) < feeValueM || getBalance(ZRX, taker) < feeValueT || getAllowance(ZRX, taker) < feeValueT ) return false; } return true; } /// @dev Get token balance of an address. /// @param token Address of token. /// @param owner Address of owner. /// @return Token balance of owner. function getBalance(address token, address owner) internal constant returns (uint balance) { return Token(token).balanceOf(owner); } /// @dev Get allowance of token given to Proxy by an address. /// @param token Address of token. /// @param owner Address of owner. /// @return Allowance of token given to Proxy by owner. function getAllowance(address token, address owner) internal constant returns (uint allowance) { return Token(token).allowance(owner, PROXY); } }
Get allowance of token given to Proxy by an address. token Address of token. owner Address of owner. return Allowance of token given to Proxy by owner.
function getAllowance(address token, address owner) internal constant returns (uint allowance) { return Token(token).allowance(owner, PROXY); }
1,754,050
./partial_match/42/0x1c4daF780a2b00b40781DB41E020816728b56e61/sources/OrbitTrajectory.sol
return A unit amount of terminal inflation supply issued/ rate = (1 + epoch rate) ^ num of epochs return Supply (effectiveRate - 1) for extra supply to issue based on number of epochs
function terminalInflationSupply(uint totalSupply, uint numOfEpochs) public pure returns (uint) { uint UNIT = SafeMath.unit(); uint effectiveCompoundRate = Math.exp(UNIT.add(TERMINAL_SUPPLY_RATE_ANNUAL.div(52)),numOfEpochs); return totalSupply.mul(effectiveCompoundRate.sub(UNIT)) / UNIT; }
3,417,444
// SPDX-License-Identifier: GNU /// @notice adapted from https://github.com/Uniswap/uniswap-v2-periphery/blob/master/contracts/examples/ExampleOracleSimple.sol pragma solidity 0.7.6; import "../OracleCommon.sol"; import "../../_openzeppelin/math/SafeMath.sol"; import '../../_uniswap/v2-core/contracts/interfaces/IUniswapV2Factory.sol'; import '../../_uniswap/v2-core/contracts/interfaces/IUniswapV2Pair.sol'; import '../../_uniswap/lib/contracts/libraries/FixedPoint.sol'; import '../../_uniswap/v2-periphery/contracts/libraries/UniswapV2OracleLibrary.sol'; import '../../_uniswap/v2-periphery/contracts/libraries/UniswapV2Library.sol'; /** @notice A oracle that uses 2 TWAP periods and uses the lower of the 2 values. Note that the price average is only guaranteed to be over at least 1 period, but may be over a longer period, Periodicity is fixed at deployment time. Index (usually USD) token is fixed at deployment time. A single deployment can be shared by multiple oneToken clients and can observe multiple base tokens. Non-USD index tokens are possible. Such deployments can used as interim oracles in Composite Oracles. They should NOT be registered because they are not, by definition, valid sources of USD quotes. Example calculation MPH/ETH -> ETH/USD 1hr and MPH/ETH -> ETH/USD 24hr take the lower value and return. This is a safety net to help prevent price manipulation. This oracle combines 2 TWAPs to save on gas for keeping seperate oracles for these 2 PERIODS. */ contract UniswapOracleTWAPCompare is OracleCommon { using FixedPoint for *; using SafeMath for uint256; uint256 public immutable PERIOD_1; uint256 public immutable PERIOD_2; address public immutable uniswapFactory; struct Pair { address token0; address token1; uint256 price0CumulativeLast; uint256 price1CumulativeLast; uint32 blockTimestampLast; FixedPoint.uq112x112 price0Average; FixedPoint.uq112x112 price1Average; } mapping(address => Pair) period_1_pairs; mapping(address => Pair) period_2_pairs; /** @notice the indexToken (index token), averaging period and uniswapfactory cannot be changed post-deployment @dev deploy multiple instances to support different configurations @param oneTokenFactory_ oneToken factory to bind to @param uniswapFactory_ external factory contract needed by the uniswap library @param indexToken_ the index token to use for valuations. If not a usd collateral token then the Oracle should not be registered in the factory but it can be used by CompositeOracles. @param period_1_ the averaging period to use for price smoothing @param period_2_ the averaging period to use for price smoothing */ constructor(address oneTokenFactory_, address uniswapFactory_, address indexToken_, uint256 period_1_, uint256 period_2_) OracleCommon(oneTokenFactory_, "ICHI TWAP Compare Uniswap Oracle", indexToken_) { require(uniswapFactory_ != NULL_ADDRESS, "UniswapOracleTWAPCompare: uniswapFactory cannot be empty"); require(period_1_ > 0, "UniswapOracleTWAPCompare: period must be > 0"); require(period_2_ > 0, "UniswapOracleTWAPCompare: period must be > 0"); uniswapFactory = uniswapFactory_; PERIOD_1 = period_1_; PERIOD_2 = period_2_; indexToken = indexToken_; } /** @notice configures parameters for a pair, token versus indexToken @dev initializes the first time, then does no work. Initialized from the Factory when assigned to an asset. @param token the base token. index is established at deployment time and cannot be changed */ function init(address token) external onlyModuleOrFactory override { require(token != NULL_ADDRESS, "UniswapOracleTWAPCompare: token cannot be null"); IUniswapV2Pair _pair = IUniswapV2Pair(UniswapV2Library.pairFor(uniswapFactory, token, indexToken)); // this condition should never be false require(address(_pair) != NULL_ADDRESS, "UniswapOracleTWAPCompare: unknown pair"); Pair storage p1 = period_1_pairs[address(_pair)]; Pair storage p2 = period_2_pairs[address(_pair)]; if(p1.token0 == NULL_ADDRESS && p2.token0 == NULL_ADDRESS) { p1.token0 = _pair.token0(); p2.token0 = _pair.token0(); p1.token1 = _pair.token1(); p2.token1 = _pair.token1(); p1.price0CumulativeLast = _pair.price0CumulativeLast(); // fetch the current accumulated price value (1 / 0) p2.price0CumulativeLast = _pair.price0CumulativeLast(); p1.price1CumulativeLast = _pair.price1CumulativeLast(); // fetch the current accumulated price value (0 / 1) p2.price1CumulativeLast = _pair.price1CumulativeLast(); uint112 reserve0; uint112 reserve1; (reserve0, reserve1, p1.blockTimestampLast) = _pair.getReserves(); p2.blockTimestampLast = p1.blockTimestampLast; require(reserve0 != 0 && reserve1 != 0, 'UniswapOracleTWAPCompare: NO_RESERVES'); // ensure that there's liquidity in the pair emit OracleInitialized(msg.sender, token, indexToken); } } /** @notice returns equivalent indexTokens for amountIn, token @dev index token is established at deployment time @param token ERC20 token @param amountTokens quantity, token precision @param amountUsd US dollar equivalent, precision 18 @param volatility metric for future use-cases */ function read(address token, uint256 amountTokens) external view override returns(uint256 amountUsd, uint256 volatility) { amountUsd = tokensToNormalized(indexToken, consult(token, amountTokens)); volatility = 1; } /** @notice returns equivalent baseTokens for amountUsd, indexToken @dev index token is established at deployment time @param token ERC20 token @param amountTokens quantity, token precision @param amountUsd US dollar equivalent, precision 18 @param volatility metric for future use-cases */ function amountRequired(address token, uint256 amountUsd) external view override returns(uint256 amountTokens, uint256 volatility) { IUniswapV2Pair _pair = IUniswapV2Pair(UniswapV2Library.pairFor(uniswapFactory, token, indexToken)); Pair storage p1 = period_1_pairs[address(_pair)]; Pair storage p2 = period_2_pairs[address(_pair)]; require(token == p1.token0 || token == p1.token1, 'UniswapOracleTWAPCompare: INVALID_TOKEN'); require(p1.price0CumulativeLast > 0 && p2.price0CumulativeLast > 0, "UniswapOracleTWAPCompare: Gathering history. Try again later"); amountUsd = normalizedToTokens(indexToken, amountUsd); uint256 p1Tokens = (token == p1.token0 ? p1.price0Average : p1.price1Average).reciprocal().mul(amountUsd).decode144(); uint256 p2Tokens = (token == p2.token0 ? p2.price0Average : p2.price1Average).reciprocal().mul(amountUsd).decode144(); if (p1Tokens > p2Tokens) { //want to take the lower price which is more larger amount of tokens amountTokens = p1Tokens; } else { amountTokens = p2Tokens; } volatility = 1; } /** @notice updates price observation history, if necessary @dev it is permissible for anyone to supply gas and update the oracle's price history. @param token baseToken to update */ function update(address token) external override { IUniswapV2Pair _pair = IUniswapV2Pair(UniswapV2Library.pairFor(uniswapFactory, token, indexToken)); Pair storage p1 = period_1_pairs[address(_pair)]; Pair storage p2 = period_2_pairs[address(_pair)]; if(p1.token0 != NULL_ADDRESS) { (uint256 price0Cumulative, uint256 price1Cumulative, uint32 blockTimestamp) = UniswapV2OracleLibrary.currentCumulativePrices(address(_pair)); uint32 timeElapsed_1 = blockTimestamp - p1.blockTimestampLast; // overflow is desired uint32 timeElapsed_2 = blockTimestamp - p2.blockTimestampLast; // overflow is desired // ensure that at least one full period has passed since the last update ///@ dev require() was dropped in favor of if() to make this safe to call when unsure about elapsed time if(timeElapsed_1 >= PERIOD_1) { // overflow is desired, casting never truncates // cumulative price is in (uq112x112 price * seconds) units so we simply wrap it after division by time elapsed p1.price0Average = FixedPoint.uq112x112(uint224((price0Cumulative - p1.price0CumulativeLast) / timeElapsed_1)); p1.price1Average = FixedPoint.uq112x112(uint224((price1Cumulative - p1.price1CumulativeLast) / timeElapsed_1)); p1.price0CumulativeLast = price0Cumulative; p1.price1CumulativeLast = price1Cumulative; p1.blockTimestampLast = blockTimestamp; } if(timeElapsed_2 >= PERIOD_2) { // overflow is desired, casting never truncates // cumulative price is in (uq112x112 price * seconds) units so we simply wrap it after division by time elapsed p2.price0Average = FixedPoint.uq112x112(uint224((price0Cumulative - p2.price0CumulativeLast) / timeElapsed_2)); p2.price1Average = FixedPoint.uq112x112(uint224((price1Cumulative - p2.price1CumulativeLast) / timeElapsed_2)); p2.price0CumulativeLast = price0Cumulative; p2.price1CumulativeLast = price1Cumulative; p2.blockTimestampLast = blockTimestamp; } // No event emitter to save gas } } // note this will always return 0 before update has been called successfully for the first time. // this will return an average over a long period of time unless someone calls the update() function. /** @notice returns equivalent indexTokens for amountIn, token @dev always returns 0 before update(token) has been called successfully for the first time. @param token baseToken to update @param amountTokens amount in token native precision @param amountOut anount in tokens, reciprocal token */ function consult(address token, uint256 amountTokens) public view returns (uint256 amountOut) { IUniswapV2Pair _pair = IUniswapV2Pair(UniswapV2Library.pairFor(uniswapFactory, token, indexToken)); Pair storage p1 = period_1_pairs[address(_pair)]; Pair storage p2 = period_2_pairs[address(_pair)]; require(token == p1.token0 || token == p1.token1, 'UniswapOracleTWAPCompare: INVALID_TOKEN'); require(p1.price0CumulativeLast > 0 && p2.price0CumulativeLast > 0, "UniswapOracleTWAPCompare: Gathering history. Try again later"); uint256 p1Out = (token == p1.token0 ? p1.price0Average : p1.price1Average).mul(amountTokens).decode144(); uint256 p2Out = (token == p2.token0 ? p2.price0Average : p2.price1Average).mul(amountTokens).decode144(); if (p1Out > p2Out) { amountOut = p2Out; } else { amountOut = p1Out; } } /** @notice discoverable internal state. Returns pair info for period 1 @param token baseToken to inspect */ function pair1Info(address token) external view returns ( address token0, address token1, uint256 price0CumulativeLast, uint256 price1CumulativeLast, uint256 price0Average, uint256 price1Average, uint32 blockTimestampLast, uint256 period ) { IUniswapV2Pair _pair = IUniswapV2Pair(UniswapV2Library.pairFor(uniswapFactory, token, indexToken)); Pair storage p = period_1_pairs[address(_pair)]; return( p.token0, p.token1, p.price0CumulativeLast, p.price1CumulativeLast, p.price0Average.mul(PRECISION).decode144(), p.price1Average.mul(PRECISION).decode144(), p.blockTimestampLast, PERIOD_1 ); } /** @notice discoverable internal state. Returns pair info for period 2 @param token baseToken to inspect */ function pair2Info(address token) external view returns ( address token0, address token1, uint256 price0CumulativeLast, uint256 price1CumulativeLast, uint256 price0Average, uint256 price1Average, uint32 blockTimestampLast, uint256 period ) { IUniswapV2Pair _pair = IUniswapV2Pair(UniswapV2Library.pairFor(uniswapFactory, token, indexToken)); Pair storage p = period_2_pairs[address(_pair)]; return( p.token0, p.token1, p.price0CumulativeLast, p.price1CumulativeLast, p.price0Average.mul(PRECISION).decode144(), p.price1Average.mul(PRECISION).decode144(), p.blockTimestampLast, PERIOD_2 ); } } // SPDX-License-Identifier: BUSL-1.1 pragma solidity 0.7.6; import "../interface/IOracle.sol"; import "../common/ICHIModuleCommon.sol"; abstract contract OracleCommon is IOracle, ICHIModuleCommon { uint256 constant NORMAL = 18; bytes32 constant public override MODULE_TYPE = keccak256(abi.encodePacked("ICHI V1 Oracle Implementation")); address public override indexToken; event OracleDeployed(address sender, string description, address indexToken); event OracleInitialized(address sender, address baseToken, address indexToken); /** @notice records the oracle description and the index that will be used for all quotes @dev oneToken implementations can share oracles @param oneTokenFactory_ oneTokenFactory to bind to @param description_ all modules have a description. No processing or validation @param indexToken_ every oracle has an index token for reporting the value of a base token */ constructor(address oneTokenFactory_, string memory description_, address indexToken_) ICHIModuleCommon(oneTokenFactory_, ModuleType.Oracle, description_) { require(indexToken_ != NULL_ADDRESS, "OracleCommon: indexToken cannot be empty"); indexToken = indexToken_; emit OracleDeployed(msg.sender, description_, indexToken_); } /** @notice oneTokens can share Oracles. Oracles must be re-initializable. They are initialized from the Factory. @param baseToken oracles _can be_ multi-tenant with separately initialized baseTokens */ function init(address baseToken) external onlyModuleOrFactory virtual override { emit OracleInitialized(msg.sender, baseToken, indexToken); } /** @notice converts normalized precision 18 amounts to token native precision amounts, truncates low-order values @param token ERC20 token contract @param amountNormal quantity in precision-18 @param amountTokens quantity scaled to token decimals() */ function normalizedToTokens(address token, uint256 amountNormal) public view override returns(uint256 amountTokens) { IERC20Extended t = IERC20Extended(token); uint256 nativeDecimals = t.decimals(); require(nativeDecimals <= 18, "OracleCommon: unsupported token precision (greater than 18)"); if(nativeDecimals == NORMAL) return amountNormal; return amountNormal / ( 10 ** (NORMAL - nativeDecimals)); } /** @notice converts token native precision amounts to normalized precision 18 amounts @param token ERC20 token contract @param amountTokens quantity scaled to token decimals @param amountNormal quantity in precision-18 */ function tokensToNormalized(address token, uint256 amountTokens) public view override returns(uint256 amountNormal) { IERC20Extended t = IERC20Extended(token); uint256 nativeDecimals = t.decimals(); require(nativeDecimals <= 18, "OracleCommon: unsupported token precision (greater than 18)"); if(nativeDecimals == NORMAL) return amountTokens; return amountTokens * ( 10 ** (NORMAL - nativeDecimals)); } } // 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: GNU pragma solidity >=0.5.0; interface IUniswapV2Factory { // event PairCreated(address indexed token0, address indexed token1, address pair, uint256); // function feeTo() external view returns (address); // function feeToSetter() external view returns (address); // // function allPairs(uint256) external view returns (address pair); function allPairsLength() external view returns (uint256); function createPair(address tokenA, address tokenB) external returns (address pair); function setFeeTo(address) external; function setFeeToSetter(address) external; } // SPDX-License-Identifier: GNU pragma solidity =0.7.6; interface IUniswapV2Pair { // event Approval(address indexed owner, address indexed spender, uint256 value); // event Transfer(address indexed from, address indexed to, uint256 value); // function name() external pure returns (string memory); // function symbol() external pure returns (string memory); // function decimals() external pure returns (uint8); // function totalSupply() external view returns (uint256); // function balanceOf(address owner) external view returns (uint256); // function allowance(address owner, address spender) external view returns (uint256); // // function approve(address spender, uint256 value) external returns (bool); // function transfer(address to, uint256 value) external returns (bool); // function transferFrom(address from, address to, uint256 value) external returns (bool); // function DOMAIN_SEPARATOR() external view returns (bytes32); // function PERMIT_TYPEHASH() external pure returns (bytes32); // function nonces(address owner) external view returns (uint256); // // function permit(address owner, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s) external; // // event Mint(address indexed sender, uint256 amount0, uint256 amount1); // event Burn(address indexed sender, uint256 amount0, uint256 amount1, address indexed to); // event Swap( // address indexed sender, // uint256 amount0In, // uint256 amount1In, // uint256 amount0Out, // uint256 amount1Out, // address indexed to // ); event Sync(uint112 reserve0, uint112 reserve1); // function MINIMUM_LIQUIDITY() external pure returns (uint256); // function factory() external view returns (address); function token0() external view returns (address); function token1() external view returns (address); function getReserves() external view returns (uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast); function price0CumulativeLast() external view returns (uint256); function price1CumulativeLast() external view returns (uint256); // function kLast() external view returns (uint256); // // function mint(address to) external returns (uint256 liquidity); // function burn(address to) external returns (uint256 amount0, uint256 amount1); // function swap(uint256 amount0Out, uint256 amount1Out, address to, bytes calldata data) external; // function skim(address to) external; function sync() external; function initialize(address, address) external; } // SPDX-License-Identifier: GPL-3.0-or-later pragma solidity >=0.4.0; import './FullMath.sol'; import './Babylonian.sol'; import './BitMath.sol'; // a library for handling binary fixed point numbers (https://en.wikipedia.org/wiki/Q_(number_format)) library FixedPoint { // range: [0, 2**112 - 1] // resolution: 1 / 2**112 struct uq112x112 { uint224 _x; } // range: [0, 2**144 - 1] // resolution: 1 / 2**112 struct uq144x112 { uint256 _x; } uint8 public constant RESOLUTION = 112; uint256 public constant Q112 = 0x10000000000000000000000000000; // 2**112 uint256 private constant Q224 = 0x100000000000000000000000000000000000000000000000000000000; // 2**224 uint256 private constant LOWER_MASK = 0xffffffffffffffffffffffffffff; // decimal of UQ*x112 (lower 112 bits) // encode a uint112 as a UQ112x112 function encode(uint112 x) internal pure returns (uq112x112 memory) { return uq112x112(uint224(x) << RESOLUTION); } // encodes a uint144 as a UQ144x112 function encode144(uint144 x) internal pure returns (uq144x112 memory) { return uq144x112(uint256(x) << RESOLUTION); } // decode a UQ112x112 into a uint112 by truncating after the radix point function decode(uq112x112 memory self) internal pure returns (uint112) { return uint112(self._x >> RESOLUTION); } // decode a UQ144x112 into a uint144 by truncating after the radix point function decode144(uq144x112 memory self) internal pure returns (uint144) { return uint144(self._x >> RESOLUTION); } // multiply a UQ112x112 by a uint256, returning a UQ144x112 // reverts on overflow function mul(uq112x112 memory self, uint256 y) internal pure returns (uq144x112 memory) { uint256 z = 0; require(y == 0 || (z = self._x * y) / y == self._x, 'FixedPoint::mul: overflow'); return uq144x112(z); } // multiply a UQ112x112 by an int and decode, returning an int // reverts on overflow function muli(uq112x112 memory self, int256 y) internal pure returns (int256) { uint256 z = FullMath.mulDiv(self._x, uint256(y < 0 ? -y : y), Q112); require(z < 2**255, 'FixedPoint::muli: overflow'); return y < 0 ? -int256(z) : int256(z); } // multiply a UQ112x112 by a UQ112x112, returning a UQ112x112 // lossy function muluq(uq112x112 memory self, uq112x112 memory other) internal pure returns (uq112x112 memory) { if (self._x == 0 || other._x == 0) { return uq112x112(0); } uint112 upper_self = uint112(self._x >> RESOLUTION); // * 2^0 uint112 lower_self = uint112(self._x & LOWER_MASK); // * 2^-112 uint112 upper_other = uint112(other._x >> RESOLUTION); // * 2^0 uint112 lower_other = uint112(other._x & LOWER_MASK); // * 2^-112 // partial products uint224 upper = uint224(upper_self) * upper_other; // * 2^0 uint224 lower = uint224(lower_self) * lower_other; // * 2^-224 uint224 uppers_lowero = uint224(upper_self) * lower_other; // * 2^-112 uint224 uppero_lowers = uint224(upper_other) * lower_self; // * 2^-112 // so the bit shift does not overflow require(upper <= uint112(-1), 'FixedPoint::muluq: upper overflow'); // this cannot exceed 256 bits, all values are 224 bits uint256 sum = uint256(upper << RESOLUTION) + uppers_lowero + uppero_lowers + (lower >> RESOLUTION); // so the cast does not overflow require(sum <= uint224(-1), 'FixedPoint::muluq: sum overflow'); return uq112x112(uint224(sum)); } // divide a UQ112x112 by a UQ112x112, returning a UQ112x112 function divuq(uq112x112 memory self, uq112x112 memory other) internal pure returns (uq112x112 memory) { require(other._x > 0, 'FixedPoint::divuq: division by zero'); if (self._x == other._x) { return uq112x112(uint224(Q112)); } if (self._x <= uint144(-1)) { uint256 value = (uint256(self._x) << RESOLUTION) / other._x; require(value <= uint224(-1), 'FixedPoint::divuq: overflow'); return uq112x112(uint224(value)); } uint256 result = FullMath.mulDiv(Q112, self._x, other._x); require(result <= uint224(-1), 'FixedPoint::divuq: overflow'); return uq112x112(uint224(result)); } // returns a UQ112x112 which represents the ratio of the numerator to the denominator // can be lossy function fraction(uint256 numerator, uint256 denominator) internal pure returns (uq112x112 memory) { require(denominator > 0, 'FixedPoint::fraction: division by zero'); if (numerator == 0) return FixedPoint.uq112x112(0); if (numerator <= uint144(-1)) { uint256 result = (numerator << RESOLUTION) / denominator; require(result <= uint224(-1), 'FixedPoint::fraction: overflow'); return uq112x112(uint224(result)); } else { uint256 result = FullMath.mulDiv(numerator, Q112, denominator); require(result <= uint224(-1), 'FixedPoint::fraction: overflow'); return uq112x112(uint224(result)); } } // take the reciprocal of a UQ112x112 // reverts on overflow // lossy function reciprocal(uq112x112 memory self) internal pure returns (uq112x112 memory) { require(self._x != 0, 'FixedPoint::reciprocal: reciprocal of zero'); require(self._x != 1, 'FixedPoint::reciprocal: overflow'); return uq112x112(uint224(Q224 / self._x)); } // square root of a UQ112x112 // lossy between 0/1 and 40 bits function sqrt(uq112x112 memory self) internal pure returns (uq112x112 memory) { if (self._x <= uint144(-1)) { return uq112x112(uint224(Babylonian.sqrt(uint256(self._x) << 112))); } uint8 safeShiftBits = 255 - BitMath.mostSignificantBit(self._x); safeShiftBits -= safeShiftBits % 2; return uq112x112(uint224(Babylonian.sqrt(uint256(self._x) << safeShiftBits) << ((112 - safeShiftBits) / 2))); } } // SPDX-License-Identifier: GNU pragma solidity 0.7.6; import "./UniswapV2Library.sol"; import '../../../lib/contracts/libraries/FixedPoint.sol'; // library with helper methods for oracles that are concerned with computing average prices library UniswapV2OracleLibrary { using FixedPoint for *; // helper function that returns the current block timestamp within the range of uint32, i.e. [0, 2**32 - 1] function currentBlockTimestamp() internal view returns (uint32) { return uint32(block.timestamp % 2 ** 32); } // produces the cumulative price using counterfactuals to save gas and avoid a call to sync. function currentCumulativePrices( address pair ) internal view returns (uint256 price0Cumulative, uint256 price1Cumulative, uint32 blockTimestamp) { blockTimestamp = currentBlockTimestamp(); price0Cumulative = IUniswapV2Pair(pair).price0CumulativeLast(); price1Cumulative = IUniswapV2Pair(pair).price1CumulativeLast(); // if time has elapsed since the last update on the pair, mock the accumulated price values (uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast) = IUniswapV2Pair(pair).getReserves(); if (blockTimestampLast != blockTimestamp) { // subtraction overflow is desired uint32 timeElapsed = blockTimestamp - blockTimestampLast; // addition overflow is desired // counterfactual price0Cumulative += uint256(FixedPoint.fraction(reserve1, reserve0)._x) * timeElapsed; // counterfactual price1Cumulative += uint256(FixedPoint.fraction(reserve0, reserve1)._x) * timeElapsed; } } } // SPDX-License-Identifier: GNU pragma solidity 0.7.6; import '../../../v2-core/contracts/interfaces/IUniswapV2Pair.sol'; import '../../../v2-core/contracts/UniswapV2Pair.sol'; import "./UniswapSafeMath.sol"; library UniswapV2Library { using UniswapSafeMath for uint256; // returns sorted token addresses, used to handle return values from pairs sorted in this order function sortTokens(address tokenA, address tokenB) internal pure returns (address token0, address token1) { require(tokenA != tokenB, 'UniswapV2Library: IDENTICAL_ADDRESSES'); (token0, token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA); require(token0 != address(0), 'UniswapV2Library: ZERO_ADDRESS'); } function getInitHash() public pure returns (bytes32){ bytes memory bytecode = type(UniswapV2Pair).creationCode; return keccak256(abi.encodePacked(bytecode)); } // calculates the CREATE2 address for a pair without making any external calls function pairFor(address factory, address tokenA, address tokenB) internal pure returns (address pair) { (address token0, address token1) = sortTokens(tokenA, tokenB); pair = address(uint256(keccak256(abi.encodePacked( hex'ff', factory, keccak256(abi.encodePacked(token0, token1)), getInitHash() )))); } // fetches and sorts the reserves for a pair function getReserves(address factory, address tokenA, address tokenB) internal view returns (uint256 reserveA, uint256 reserveB) { (address token0,) = sortTokens(tokenA, tokenB); (uint256 reserve0, uint256 reserve1,) = IUniswapV2Pair(pairFor(factory, tokenA, tokenB)).getReserves(); (reserveA, reserveB) = tokenA == token0 ? (reserve0, reserve1) : (reserve1, reserve0); } // given some amount of an asset and pair reserves, returns an equivalent amount of the other asset function quote(uint256 amountA, uint256 reserveA, uint256 reserveB) internal pure returns (uint256 amountB) { require(amountA > 0, 'UniswapV2Library: INSUFFICIENT_AMOUNT'); require(reserveA > 0 && reserveB > 0, 'UniswapV2Library: INSUFFICIENT_LIQUIDITY'); amountB = amountA.mul(reserveB) / reserveA; } // given an input amount of an asset and pair reserves, returns the maximum output amount of the other asset function getAmountOut(uint256 amountIn, uint256 reserveIn, uint256 reserveOut) internal pure returns (uint256 amountOut) { require(amountIn > 0, 'UniswapV2Library: INSUFFICIENT_INPUT_AMOUNT'); require(reserveIn > 0 && reserveOut > 0, 'UniswapV2Library: INSUFFICIENT_LIQUIDITY'); uint256 amountInWithFee = amountIn.mul(997); uint256 numerator = amountInWithFee.mul(reserveOut); uint256 denominator = reserveIn.mul(1000).add(amountInWithFee); amountOut = numerator / denominator; } // given an output amount of an asset and pair reserves, returns a required input amount of the other asset function getAmountIn(uint256 amountOut, uint256 reserveIn, uint256 reserveOut) internal pure returns (uint256 amountIn) { require(amountOut > 0, 'UniswapV2Library: INSUFFICIENT_OUTPUT_AMOUNT'); require(reserveIn > 0 && reserveOut > 0, 'UniswapV2Library: INSUFFICIENT_LIQUIDITY'); uint256 numerator = reserveIn.mul(amountOut).mul(1000); uint256 denominator = reserveOut.sub(amountOut).mul(997); amountIn = (numerator / denominator).add(1); } // performs chained getAmountOut calculations on any number of pairs function getAmountsOut(address factory, uint256 amountIn, address[] memory path) internal view returns (uint256[] memory amounts) { require(path.length >= 2, 'UniswapV2Library: INVALID_PATH'); amounts = new uint256[](path.length); amounts[0] = amountIn; for (uint256 i; i < path.length - 1; i++) { (uint256 reserveIn, uint256 reserveOut) = getReserves(factory, path[i], path[i + 1]); amounts[i + 1] = getAmountOut(amounts[i], reserveIn, reserveOut); } } // performs chained getAmountIn calculations on any number of pairs function getAmountsIn(address factory, uint256 amountOut, address[] memory path) internal view returns (uint256[] memory amounts) { require(path.length >= 2, 'UniswapV2Library: INVALID_PATH'); amounts = new uint256[](path.length); amounts[amounts.length - 1] = amountOut; for (uint256 i = path.length - 1; i > 0; i--) { (uint256 reserveIn, uint256 reserveOut) = getReserves(factory, path[i - 1], path[i]); amounts[i - 1] = getAmountIn(amounts[i], reserveIn, reserveOut); } } } // SPDX-License-Identifier: BUSL-1.1 pragma solidity 0.7.6; import "./IModule.sol"; interface IOracle is IModule { function init(address baseToken) external; function update(address token) external; function indexToken() external view returns(address); /** @param token ERC20 token @param amountTokens quantity, token native precision @param amountUsd US dollar equivalent, precision 18 @param volatility metric for future use-cases */ function read(address token, uint amountTokens) external view returns(uint amountUsd, uint volatility); /** @param token ERC20 token @param amountTokens token quantity, token native precision @param amountUsd US dollar equivalent, precision 18 @param volatility metric for future use-cases */ function amountRequired(address token, uint amountUsd) external view returns(uint amountTokens, uint volatility); /** @notice converts normalized precision-18 amounts to token native precision amounts, truncates low-order values @param token ERC20 token contract @param amountNormal quantity, precision 18 @param amountTokens quantity scaled to token precision */ function normalizedToTokens(address token, uint amountNormal) external view returns(uint amountTokens); /** @notice converts token native precision amounts to normalized precision-18 amounts @param token ERC20 token contract @param amountNormal quantity, precision 18 @param amountTokens quantity scaled to token precision */ function tokensToNormalized(address token, uint amountTokens) external view returns(uint amountNormal); } // SPDX-License-Identifier: BUSL-1.1 pragma solidity 0.7.6; import "../interface/IModule.sol"; import "../interface/IOneTokenFactory.sol"; import "../interface/IOneTokenV1Base.sol"; import "./ICHICommon.sol"; abstract contract ICHIModuleCommon is IModule, ICHICommon { ModuleType public immutable override moduleType; string public override moduleDescription; address public immutable override oneTokenFactory; event ModuleDeployed(address sender, ModuleType moduleType, string description); event DescriptionUpdated(address sender, string description); modifier onlyKnownToken { require(IOneTokenFactory(oneTokenFactory).isOneToken(msg.sender), "ICHIModuleCommon: msg.sender is not a known oneToken"); _; } modifier onlyTokenOwner (address oneToken) { require(msg.sender == IOneTokenV1Base(oneToken).owner(), "ICHIModuleCommon: msg.sender is not oneToken owner"); _; } modifier onlyModuleOrFactory { if(!IOneTokenFactory(oneTokenFactory).isModule(msg.sender)) { require(msg.sender == oneTokenFactory, "ICHIModuleCommon: msg.sender is not module owner, token factory or registed module"); } _; } /** @notice modules are bound to the factory at deployment time @param oneTokenFactory_ factory to bind to @param moduleType_ type number helps prevent governance errors @param description_ human-readable, descriptive only */ constructor (address oneTokenFactory_, ModuleType moduleType_, string memory description_) { require(oneTokenFactory_ != NULL_ADDRESS, "ICHIModuleCommon: oneTokenFactory cannot be empty"); require(bytes(description_).length > 0, "ICHIModuleCommon: description cannot be empty"); oneTokenFactory = oneTokenFactory_; moduleType = moduleType_; moduleDescription = description_; emit ModuleDeployed(msg.sender, moduleType_, description_); } /** @notice set a module description @param description new module desciption */ function updateDescription(string memory description) external onlyOwner override { require(bytes(description).length > 0, "ICHIModuleCommon: description cannot be empty"); moduleDescription = description; emit DescriptionUpdated(msg.sender, description); } } // SPDX-License-Identifier: BUSL-1.1 pragma solidity 0.7.6; import "./IICHICommon.sol"; import "./InterfaceCommon.sol"; interface IModule is IICHICommon { function oneTokenFactory() external view returns(address); function updateDescription(string memory description) external; function moduleDescription() external view returns(string memory); function MODULE_TYPE() external view returns(bytes32); function moduleType() external view returns(ModuleType); } // SPDX-License-Identifier: BUSL-1.1 pragma solidity 0.7.6; import "./IICHIOwnable.sol"; import "./InterfaceCommon.sol"; interface IICHICommon is IICHIOwnable, InterfaceCommon {} // SPDX-License-Identifier: BUSL-1.1 pragma solidity 0.7.6; pragma abicoder v2; interface InterfaceCommon { enum ModuleType { Version, Controller, Strategy, MintMaster, Oracle } } // SPDX-License-Identifier: BUSL-1.1 pragma solidity 0.7.6; interface IICHIOwnable { function renounceOwnership() external; function transferOwnership(address newOwner) external; function owner() external view returns (address); } // SPDX-License-Identifier: BUSL-1.1 pragma solidity 0.7.6; pragma abicoder v2; import "./InterfaceCommon.sol"; interface IOneTokenFactory is InterfaceCommon { function oneTokenProxyAdmins(address) external returns(address); function deployOneTokenProxy( string memory name, string memory symbol, address governance, address version, address controller, address mintMaster, address memberToken, address collateral, address oneTokenOracle ) external returns(address newOneTokenProxy, address proxyAdmin); function admitModule(address module, ModuleType moduleType, string memory name, string memory url) external; function updateModule(address module, string memory name, string memory url) external; function removeModule(address module) external; function admitForeignToken(address foreignToken, bool collateral, address oracle) external; function updateForeignToken(address foreignToken, bool collateral) external; function removeForeignToken(address foreignToken) external; function assignOracle(address foreignToken, address oracle) external; function removeOracle(address foreignToken, address oracle) external; /** * View functions */ function MODULE_TYPE() external view returns(bytes32); function oneTokenCount() external view returns(uint256); function oneTokenAtIndex(uint256 index) external view returns(address); function isOneToken(address oneToken) external view returns(bool); // modules function moduleCount() external view returns(uint256); function moduleAtIndex(uint256 index) external view returns(address module); function isModule(address module) external view returns(bool); function isValidModuleType(address module, ModuleType moduleType) external view returns(bool); // foreign tokens function foreignTokenCount() external view returns(uint256); function foreignTokenAtIndex(uint256 index) external view returns(address); function foreignTokenInfo(address foreignToken) external view returns(bool collateral, uint256 oracleCount); function foreignTokenOracleCount(address foreignToken) external view returns(uint256); function foreignTokenOracleAtIndex(address foreignToken, uint256 index) external view returns(address); function isOracle(address foreignToken, address oracle) external view returns(bool); function isForeignToken(address foreignToken) external view returns(bool); function isCollateral(address foreignToken) external view returns(bool); } // SPDX-License-Identifier: BUSL-1.1 pragma solidity 0.7.6; import "./IICHICommon.sol"; import "./IERC20Extended.sol"; interface IOneTokenV1Base is IICHICommon, IERC20 { function init(string memory name_, string memory symbol_, address oneTokenOracle_, address controller_, address mintMaster_, address memberToken_, address collateral_) external; function changeController(address controller_) external; function changeMintMaster(address mintMaster_, address oneTokenOracle) external; function addAsset(address token, address oracle) external; function removeAsset(address token) external; function setStrategy(address token, address strategy, uint256 allowance) external; function executeStrategy(address token) external; function removeStrategy(address token) external; function closeStrategy(address token) external; function increaseStrategyAllowance(address token, uint256 amount) external; function decreaseStrategyAllowance(address token, uint256 amount) external; function setFactory(address newFactory) external; function MODULE_TYPE() external view returns(bytes32); function oneTokenFactory() external view returns(address); function controller() external view returns(address); function mintMaster() external view returns(address); function memberToken() external view returns(address); function assets(address) external view returns(address, address); function balances(address token) external view returns(uint256 inVault, uint256 inStrategy); function collateralTokenCount() external view returns(uint256); function collateralTokenAtIndex(uint256 index) external view returns(address); function isCollateral(address token) external view returns(bool); function otherTokenCount() external view returns(uint256); function otherTokenAtIndex(uint256 index) external view returns(address); function isOtherToken(address token) external view returns(bool); function assetCount() external view returns(uint256); function assetAtIndex(uint256 index) external view returns(address); function isAsset(address token) external view returns(bool); } // SPDX-License-Identifier: BUSL-1.1 pragma solidity 0.7.6; import "../oz_modified/ICHIOwnable.sol"; import "../oz_modified/ICHIInitializable.sol"; import "../interface/IERC20Extended.sol"; import "../interface/IICHICommon.sol"; contract ICHICommon is IICHICommon, ICHIOwnable, ICHIInitializable { uint256 constant PRECISION = 10 ** 18; uint256 constant INFINITE = uint256(0-1); address constant NULL_ADDRESS = address(0); // @dev internal fingerprints help prevent deployment-time governance errors bytes32 constant COMPONENT_CONTROLLER = keccak256(abi.encodePacked("ICHI V1 Controller")); bytes32 constant COMPONENT_VERSION = keccak256(abi.encodePacked("ICHI V1 OneToken Implementation")); bytes32 constant COMPONENT_STRATEGY = keccak256(abi.encodePacked("ICHI V1 Strategy Implementation")); bytes32 constant COMPONENT_MINTMASTER = keccak256(abi.encodePacked("ICHI V1 MintMaster Implementation")); bytes32 constant COMPONENT_ORACLE = keccak256(abi.encodePacked("ICHI V1 Oracle Implementation")); bytes32 constant COMPONENT_VOTERROLL = keccak256(abi.encodePacked("ICHI V1 VoterRoll Implementation")); bytes32 constant COMPONENT_FACTORY = keccak256(abi.encodePacked("ICHI OneToken Factory")); } // SPDX-License-Identifier: BUSL-1.1 pragma solidity 0.7.6; import "../_openzeppelin/token/ERC20/IERC20.sol"; interface IERC20Extended is IERC20 { function decimals() external view returns(uint8); function symbol() external view returns(string memory); function name() external view returns(string memory); } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: MIT /** * @dev Constructor visibility has been removed from the original. * _transferOwnership() has been added to support proxied deployments. * Abstract tag removed from contract block. * Added interface inheritance and override modifiers. * Changed contract identifier in require error messages. */ pragma solidity >=0.6.0 <0.8.0; import "../_openzeppelin/utils/Context.sol"; import "../interface/IICHIOwnable.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ contract ICHIOwnable is IICHIOwnable, Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "ICHIOwnable: caller is not the owner"); _; } /** * @dev Initializes the contract setting the deployer as the initial owner. * Ineffective for proxied deployed. Use initOwnable. */ constructor() { _transferOwnership(msg.sender); } /** @dev initialize proxied deployment */ function initOwnable() internal { require(owner() == address(0), "ICHIOwnable: already initialized"); _transferOwnership(msg.sender); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual override returns (address) { return _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 override 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 override onlyOwner { _transferOwnership(newOwner); } /** * @dev be sure to call this in the initialization stage of proxied deployment or owner will not be set */ function _transferOwnership(address newOwner) internal { require(newOwner != address(0), "ICHIOwnable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } // SPDX-License-Identifier: MIT pragma solidity 0.7.6; import "../_openzeppelin/utils/Address.sol"; contract ICHIInitializable { bool private _initialized; bool private _initializing; modifier initializer() { require(_initializing || _isConstructor() || !_initialized, "ICHIInitializable: contract is already initialized"); bool isTopLevelCall = !_initializing; if (isTopLevelCall) { _initializing = true; _initialized = true; } _; if (isTopLevelCall) { _initializing = false; } } modifier initialized { require(_initialized, "ICHIInitializable: contract is not initialized"); _; } function _isConstructor() private view returns (bool) { return !Address.isContract(address(this)); } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.2 <0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: value }(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.delegatecall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: CC-BY-4.0 pragma solidity >=0.4.0; // taken from https://medium.com/coinmonks/math-in-solidity-part-3-percents-and-proportions-4db014e080b1 // license is CC-BY-4.0 library FullMath { function fullMul(uint256 x, uint256 y) internal pure returns (uint256 l, uint256 h) { uint256 mm = mulmod(x, y, uint256(-1)); l = x * y; h = mm - l; if (mm < l) h -= 1; } function fullDiv( uint256 l, uint256 h, uint256 d ) private pure returns (uint256) { uint256 pow2 = d & -d; d /= pow2; l /= pow2; l += h * ((-pow2) / pow2 + 1); uint256 r = 1; r *= 2 - d * r; r *= 2 - d * r; r *= 2 - d * r; r *= 2 - d * r; r *= 2 - d * r; r *= 2 - d * r; r *= 2 - d * r; r *= 2 - d * r; return l * r; } function mulDiv( uint256 x, uint256 y, uint256 d ) internal pure returns (uint256) { (uint256 l, uint256 h) = fullMul(x, y); uint256 mm = mulmod(x, y, d); if (mm > l) h -= 1; l -= mm; if (h == 0) return l / d; require(h < d, 'FullMath: FULLDIV_OVERFLOW'); return fullDiv(l, h, d); } } // SPDX-License-Identifier: GPL-3.0-or-later pragma solidity >=0.4.0; // computes square roots using the babylonian method // https://en.wikipedia.org/wiki/Methods_of_computing_square_roots#Babylonian_method library Babylonian { // credit for this implementation goes to // https://github.com/abdk-consulting/abdk-libraries-solidity/blob/master/ABDKMath64x64.sol#L687 function sqrt(uint256 x) internal pure returns (uint256) { if (x == 0) return 0; // this block is equivalent to r = uint256(1) << (BitMath.mostSignificantBit(x) / 2); // however that code costs significantly more gas uint256 xx = x; uint256 r = 1; if (xx >= 0x100000000000000000000000000000000) { xx >>= 128; r <<= 64; } if (xx >= 0x10000000000000000) { xx >>= 64; r <<= 32; } if (xx >= 0x100000000) { xx >>= 32; r <<= 16; } if (xx >= 0x10000) { xx >>= 16; r <<= 8; } if (xx >= 0x100) { xx >>= 8; r <<= 4; } if (xx >= 0x10) { xx >>= 4; r <<= 2; } if (xx >= 0x8) { r <<= 1; } r = (r + x / r) >> 1; r = (r + x / r) >> 1; r = (r + x / r) >> 1; r = (r + x / r) >> 1; r = (r + x / r) >> 1; r = (r + x / r) >> 1; r = (r + x / r) >> 1; // Seven iterations should be enough uint256 r1 = x / r; return (r < r1 ? r : r1); } } // SPDX-License-Identifier: GPL-3.0-or-later pragma solidity >=0.5.0; library BitMath { // returns the 0 indexed position of the most significant bit of the input x // s.t. x >= 2**msb and x < 2**(msb+1) function mostSignificantBit(uint256 x) internal pure returns (uint8 r) { require(x > 0, 'BitMath::mostSignificantBit: zero'); if (x >= 0x100000000000000000000000000000000) { x >>= 128; r += 128; } if (x >= 0x10000000000000000) { x >>= 64; r += 64; } if (x >= 0x100000000) { x >>= 32; r += 32; } if (x >= 0x10000) { x >>= 16; r += 16; } if (x >= 0x100) { x >>= 8; r += 8; } if (x >= 0x10) { x >>= 4; r += 4; } if (x >= 0x4) { x >>= 2; r += 2; } if (x >= 0x2) r += 1; } // returns the 0 indexed position of the least significant bit of the input x // s.t. (x & 2**lsb) != 0 and (x & (2**(lsb) - 1)) == 0) // i.e. the bit at the index is set and the mask of all lower bits is 0 function leastSignificantBit(uint256 x) internal pure returns (uint8 r) { require(x > 0, 'BitMath::leastSignificantBit: zero'); r = 255; if (x & uint128(-1) > 0) { r -= 128; } else { x >>= 128; } if (x & uint64(-1) > 0) { r -= 64; } else { x >>= 64; } if (x & uint32(-1) > 0) { r -= 32; } else { x >>= 32; } if (x & uint16(-1) > 0) { r -= 16; } else { x >>= 16; } if (x & uint8(-1) > 0) { r -= 8; } else { x >>= 8; } if (x & 0xf > 0) { r -= 4; } else { x >>= 4; } if (x & 0x3 > 0) { r -= 2; } else { x >>= 2; } if (x & 0x1 > 0) r -= 1; } } // SPDX-License-Identifier: ISC pragma solidity =0.7.6; import './libraries/UQ112x112.sol'; import './interfaces/IUniswapV2Pair.sol'; import './interfaces/IUniswapV2Factory.sol'; import "./libraries/UniSafeMath.sol"; import "../../../_openzeppelin/token/ERC20/IERC20.sol"; contract UniswapV2Pair is IUniswapV2Pair { using UniSafeMath for uint256; using UQ112x112 for uint224; uint256 public constant MINIMUM_LIQUIDITY = 10 ** 3; bytes4 private constant SELECTOR = bytes4(keccak256(bytes('transfer(address,uint256)'))); address public factory; address public _token0; address public _token1; uint112 private reserve0; // uses single storage slot, accessible via getReserves uint112 private reserve1; // uses single storage slot, accessible via getReserves uint32 private blockTimestampLast; // uses single storage slot, accessible via getReserves uint256 public _price0CumulativeLast; uint256 public _price1CumulativeLast; uint256 public kLast; // reserve0 * reserve1, as of immediately after the most recent liquidity event constructor() { factory = msg.sender; } // called once by the factory at time of deployment function initialize(address __token0, address __token1) override external { require(msg.sender == factory, 'UniswapV2: FORBIDDEN'); // sufficient check _token0 = __token0; _token1 = __token1; } function getReserves() override public view returns (uint112 _reserve0, uint112 _reserve1, uint32 _blockTimestampLast) { _reserve0 = reserve0; _reserve1 = reserve1; _blockTimestampLast = blockTimestampLast; } function token0() override external view returns (address){ return _token0; } function token1() override external view returns (address){ return _token1; } function price0CumulativeLast() override external view returns (uint256){ return _price0CumulativeLast; } function price1CumulativeLast() override external view returns (uint256){ return _price1CumulativeLast; } // update reserves and, on the first call per block, price accumulators function _update(uint256 balance0, uint256 balance1, uint112 _reserve0, uint112 _reserve1) private { require(balance0 <= uint112(-1) && balance1 <= uint112(-1), 'UniswapV2: OVERFLOW'); uint32 blockTimestamp = uint32(block.timestamp % 2**32); uint32 timeElapsed = blockTimestamp - blockTimestampLast; // overflow is desired if (timeElapsed > 0 && _reserve0 != 0 && _reserve1 != 0) { // * never overflows, and + overflow is desired _price0CumulativeLast += uint256(UQ112x112.encode(_reserve1).uqdiv(_reserve0)) * timeElapsed; _price1CumulativeLast += uint256(UQ112x112.encode(_reserve0).uqdiv(_reserve1)) * timeElapsed; } reserve0 = uint112(balance0); reserve1 = uint112(balance1); blockTimestampLast = blockTimestamp; emit Sync(reserve0, reserve1); } // force reserves to match balances function sync() override external { _update(IERC20(_token0).balanceOf(address(this)), IERC20(_token1).balanceOf(address(this)), reserve0, reserve1); } } // SPDX-License-Identifier: GNU /** * @dev this contract is renamed to prevent conflict with oz while avoiding significant changes */ pragma solidity 0.7.6; // a library for performing overflow-safe math, courtesy of DappHub (https://github.com/dapphub/ds-math) library UniswapSafeMath { function add(uint256 x, uint256 y) internal pure returns (uint256 z) { require((z = x + y) >= x, 'ds-math-add-overflow'); } function sub(uint256 x, uint256 y) internal pure returns (uint256 z) { require((z = x - y) <= x, 'ds-math-sub-underflow'); } function mul(uint256 x, uint256 y) internal pure returns (uint256 z) { require(y == 0 || (z = x * y) / y == x, 'ds-math-mul-overflow'); } } // SPDX-License-Identifier: ISC pragma solidity =0.7.6; // a library for handling binary fixed point numbers (https://en.wikipedia.org/wiki/Q_(number_format)) // range: [0, 2**112 - 1] // resolution: 1 / 2**112 library UQ112x112 { uint224 constant Q112 = 2**112; // encode a uint112 as a UQ112x112 function encode(uint112 y) internal pure returns (uint224 z) { z = uint224(y) * Q112; // never overflows } // divide a UQ112x112 by a uint112, returning a UQ112x112 function uqdiv(uint224 x, uint112 y) internal pure returns (uint224 z) { z = x / uint224(y); } } // SPDX-License-Identifier: ISC pragma solidity =0.7.6; // a library for performing overflow-safe math, courtesy of DappHub (https://github.com/dapphub/ds-math) library UniSafeMath { function add(uint256 x, uint256 y) internal pure returns (uint256 z) { require((z = x + y) >= x, 'ds-math-add-overflow'); } function sub(uint256 x, uint256 y) internal pure returns (uint256 z) { require((z = x - y) <= x, 'ds-math-sub-underflow'); } function mul(uint256 x, uint256 y) internal pure returns (uint256 z) { require(y == 0 || (z = x * y) / y == x, 'ds-math-mul-overflow'); } }
/ this condition should never be false
function init(address token) external onlyModuleOrFactory override { require(token != NULL_ADDRESS, "UniswapOracleTWAPCompare: token cannot be null"); IUniswapV2Pair _pair = IUniswapV2Pair(UniswapV2Library.pairFor(uniswapFactory, token, indexToken)); require(address(_pair) != NULL_ADDRESS, "UniswapOracleTWAPCompare: unknown pair"); Pair storage p1 = period_1_pairs[address(_pair)]; Pair storage p2 = period_2_pairs[address(_pair)]; if(p1.token0 == NULL_ADDRESS && p2.token0 == NULL_ADDRESS) { p1.token0 = _pair.token0(); p2.token0 = _pair.token0(); p1.token1 = _pair.token1(); p2.token1 = _pair.token1(); p2.price0CumulativeLast = _pair.price0CumulativeLast(); p2.price1CumulativeLast = _pair.price1CumulativeLast(); uint112 reserve0; uint112 reserve1; (reserve0, reserve1, p1.blockTimestampLast) = _pair.getReserves(); p2.blockTimestampLast = p1.blockTimestampLast; emit OracleInitialized(msg.sender, token, indexToken); } } @dev index token is established at deployment time @param token ERC20 token @param amountTokens quantity, token precision @param amountUsd US dollar equivalent, precision 18 @param volatility metric for future use-cases
1,106,165
pragma solidity ^0.4.24; import {Ownable} from '../zeppelin/contracts/ownership/Ownable.sol'; import {SafeMath} from '../zeppelin/contracts/math/SafeMath.sol'; import {ReentrancyGuard} from '../zeppelin/contracts/ReentrancyGuard.sol'; contract MediaLicensing is Ownable, ReentrancyGuard { using SafeMath for uint; uint public constant EXPIRY_TIME = 3 days; // platform now takes 10% of all sales proceeds uint32 public constant PLATFORM_FEE_DIV = 10; // the wallet address where the platform fees go to address public platform_wallet = address(0x0); enum Status { None, // so the others will have a value different than 0 Initiated, Confirmed, Cancelled, Invalidated } struct Licence { uint32 timestamp; // timestamp when the ether was sent to the smart contract Status status; // buyer confirmation that he received private contract details from seller bytes32 pdf; } struct Media { uint256 price; // in ether address seller; // person owning the original IP // buyer => licence details mapping (address => Licence) licences; } // the bytes32 part is a IPFS hash of the file mapping (bytes32 => Media) repository; uint public repository_size = 0; event LogMediaOffer(address seller, bytes32 hash, uint256 price); event LogBuyInitiated(address buyer, bytes32 hash); event LogBuyConfirmed(address buyer, bytes32 hash, bytes32 pdf); event LogBuyCancelled(address buyer, bytes32 hash); event LogLicenceInvalidated(address buyer, bytes32 hash); constructor(address new_wallet) public { platform_wallet = new_wallet; } // ------------------------------- constant methods ------------------------------- function get_price(bytes32 hash) public constant returns (uint256) { return repository[hash].price; } function get_seller(bytes32 hash) public constant returns (address) { return repository[hash].seller; } function has_valid_licence(address buyer, bytes32 hash) public constant returns (bool) { return repository[hash].licences[buyer].status == Status.Confirmed; } function get_licence_status(address buyer, bytes32 hash) public constant returns (uint8) { return uint8(repository[hash].licences[buyer].status); } function get_licence_timestamp(address buyer, bytes32 hash) public constant returns (uint32) { return uint32(repository[hash].licences[buyer].timestamp); } function get_pdf_hash(address buyer, bytes32 hash) public constant returns (bytes32) { return repository[hash].licences[buyer].pdf; } function can_cancel_licence(address buyer, bytes32 hash) public constant returns (bool) { bool initiated = repository[hash].licences[buyer].status == Status.Initiated; bool expired = repository[hash].licences[buyer].timestamp + EXPIRY_TIME < now; return initiated && expired; } // ------------------------------- admin functions -------------------------------- function admin_change_platform_wallet(address new_wallet) onlyOwner public { platform_wallet = new_wallet; } // admin action to move data from an old contract function admin_add_offer(bytes32 hash, uint256 price, address publisher) onlyOwner public { // make sure no other seller offered the same media require(repository[hash].seller == address(0x0)); // make sure the offered price is more than zero require(price > 0); // create the media entry in the repo repository[hash] = Media({seller : publisher, price : price}); repository_size += 1; emit LogMediaOffer(publisher, hash, price); } // admin action to move data from an old contract function admin_add_licence(bytes32 hash, bytes32 pdf, address buyer, uint32 timestamp) onlyOwner public { Media storage media = repository[hash]; // make sure there actually is an offer for this media require(media.seller != address(0x0)); require(media.price > 0); // make sure the buyer doesn't already have a licence require(repository[hash].licences[buyer].timestamp == 0); // create the licence entry repository[hash].licences[buyer] = Licence({ timestamp : timestamp, status : Status.Confirmed, pdf: pdf }); emit LogBuyConfirmed(buyer, hash, pdf); } // admin action as a result of an arbiter declaring a licence invalid function admin_invalidate_licence(bytes32 hash, address buyer) onlyOwner public { Media storage media = repository[hash]; // make sure there actually is an offer for this media require(media.seller != address(0x0)); require(media.price > 0); // make sure there is a licence here require(repository[hash].licences[buyer].status != Status.None); repository[hash].licences[buyer].status = Status.Invalidated; emit LogLicenceInvalidated(buyer, hash); } // ------------------------------- active functions ------------------------------- function offer(bytes32 hash, uint256 price) public { // make sure no other seller offered the same media require(repository[hash].seller == address(0x0)); // make sure the offered price is more than zero require(price > 0); // create the media entry in the repo repository[hash] = Media({seller : msg.sender, price : price}); repository_size += 1; emit LogMediaOffer(msg.sender, hash, price); } function buy(bytes32 hash) payable public { Media storage media = repository[hash]; // make sure there actually is an offer for this media require(media.seller != address(0x0)); require(media.price > 0); // make sure the exact price was sent as payment require(media.price == msg.value); // make sure the buyer doesn't already have a licence require(repository[hash].licences[msg.sender].timestamp == 0); // create the licence entry repository[hash].licences[msg.sender] = Licence({ timestamp : uint32(now), status : Status.Initiated, pdf: 0x0 }); emit LogBuyInitiated(msg.sender, hash); } function confirm(bytes32 hash, bytes32 pdf) public nonReentrant { Licence storage licence = repository[hash].licences[msg.sender]; // make sure this identity already bought a licence require(licence.timestamp != 0); // make sure he didn't already confirm or cancel this licence require(licence.status == Status.Initiated); licence.status = Status.Confirmed; licence.pdf = pdf; uint reward_platform = repository[hash].price.div(PLATFORM_FEE_DIV); uint reward_seller = repository[hash].price.sub(reward_platform); platform_wallet.transfer(reward_platform); repository[hash].seller.transfer(reward_seller); emit LogBuyConfirmed(msg.sender, hash, pdf); } function cancel(bytes32 hash) public nonReentrant { Licence storage licence = repository[hash].licences[msg.sender]; // make sure the buyer meets the required criteria to cancel require(can_cancel_licence(msg.sender, hash)); // make sure we have enough balance to make the refund require(address(this).balance >= repository[hash].price); // make sure this licence is Cancelled; this also prevents asking for refund twice licence.status = Status.Cancelled; // make a complete refund of the escrow amount msg.sender.transfer(repository[hash].price); emit LogBuyCancelled(msg.sender, hash); } }
admin action to move data from an old contract make sure no other seller offered the same media make sure the offered price is more than zero create the media entry in the repo
function admin_add_offer(bytes32 hash, uint256 price, address publisher) onlyOwner public { require(repository[hash].seller == address(0x0)); require(price > 0); repository_size += 1; emit LogMediaOffer(publisher, hash, price); }
12,544,089
./partial_match/1/0x61dC65001A8De4138DAD5167e43FF0FB0AB8D3B3/sources/src/L1ArbitrumMessenger.sol
alternative function entry point when struggling with the stack size
function sendTxToL2( address _inbox, address _to, address _user, uint256 _l1CallValue, uint256 _l2CallValue, L2GasParams memory _l2GasParams, bytes memory _data ) internal returns (uint256) { return sendTxToL2( _inbox, _to, _user, _l1CallValue, _l2CallValue, _l2GasParams._maxSubmissionCost, _l2GasParams._maxGas, _l2GasParams._gasPriceBid, _data ); }
16,040,154
./full_match/4/0x275DF24D83C40Db61C980Aa940d07c1a288bBB4F/sources/contracts/Atevada.sol
If we haven't set the starting index and this is either 1) the last saleable token or 2) the first token to be sold after the end of pre-sale, set the starting index block
function whitelistSaleMint(uint256 _quantity) callerIsUser requireIsWhiteListSale requireIsOperational external payable { require(addressMintedList[msg.sender] == 0, "Error: user has minted"); require(whitelistedList[msg.sender] == 1, "Error: user is not whitelisted"); require(_quantity > 0, "Minimum mint amount is 1"); require(_quantity == 1 || _quantity == 3 || _quantity == 5, "Can only mint using the provided options"); require(totalSupply() + _quantity <= collectionSize, "Purchase would reached max supply"); if(discountList[msg.sender] == 1){ require(msg.value >= DISCOUNT_PRICE * _quantity, "insufficient funds"); _safeMint(msg.sender, _quantity); refundIfOver(DISCOUNT_PRICE * _quantity); require(msg.value >= PRICE * _quantity, "insufficient funds"); _safeMint(msg.sender, _quantity); refundIfOver(PRICE * _quantity); } addressMintedList[msg.sender] = 1; balanceOR[msg.sender] = balanceOR[msg.sender] + _quantity; atevadaToken.updateRewardOnMint(msg.sender, _quantity); if (startingIndexBlock == 0 && (totalSupply() == collectionSize)) { startingIndexBlock = block.number; } }
13,371,110
pragma solidity >=0.5.2; import "openzeppelin-solidity/contracts/token/ERC20/ERC20.sol"; import "openzeppelin-solidity/contracts/math/SafeMath.sol"; import "./IIdentityRegistry.sol"; contract SecurityTokenDraft is ERC20 { using SafeMath for uint256; string public symbol; string public name; uint8 public decimals = 18; IIdentityRegistry private registry; uint counterUS; uint counterNotAccredited; uint counterTotal; uint limitUS; uint limitNotAccredited; uint limitTotal; mapping (address => uint) private _idbalances; constructor(string memory _symbol, string memory _name, uint256 _totalSupply, address _registry, uint _limitUS, uint _limitNotAccredited, uint _limitTotal) public { name = _name; symbol = _symbol; limitUS = _limitUS; limitNotAccredited = _limitNotAccredited; limitTotal = _limitTotal; registry = IIdentityRegistry(_registry); require(_secmint(msg.sender, _totalSupply)); _mint(msg.sender, _totalSupply); emit Transfer(address(0), msg.sender, _totalSupply); } function _sectransfer(address from, address to, uint value) internal returns(bool) { (address fromId, bool fromUS, bool fromAccredited) = registry.getIdentity(from); (address toId, bool toUS, bool toAccredited) = registry.getIdentity(to); uint fromBalance = _idbalances[fromId]; uint toBalance = _idbalances[toId]; require(fromBalance >= value); require(fromUS || !toUS); if (fromBalance == value) { counterTotal -= 1; if (fromUS) counterUS -= 1; if (!fromAccredited) counterNotAccredited -= 1; } if (toBalance == 0) { counterTotal += 1; if (toUS) counterUS += 1; if (!toAccredited) counterNotAccredited += 1; } require(counterUS <= limitUS); require(counterNotAccredited <= limitNotAccredited); require(counterTotal <= limitTotal); _idbalances[fromId] = _idbalances[fromId].sub(value); _idbalances[toId] = _idbalances[toId].add(value); return true; } function _secmint(address to, uint value) internal returns(bool) { (address toId, bool toUS, bool toAccredited) = registry.getIdentity(to); uint toBalance = _idbalances[toId]; if (toBalance == 0) { counterTotal += 1; if (toUS) counterUS += 1; if (!toAccredited) counterNotAccredited += 1; } require(counterUS <= limitUS); require(counterNotAccredited <= limitNotAccredited); require(counterTotal <= limitTotal); _idbalances[toId] = _idbalances[toId].add(value); return true; } /** * @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(_sectransfer(msg.sender, to, value)); return super.transfer(to, value); } /** * @dev Transfer tokens from one address to another. * Note that while this function emits an Approval event, this is not required as per the specification, * and other compliant implementations may not emit the event. * @param from address The address which you want to send tokens from * @param to address The address which you want to transfer to * @param value uint256 the amount of tokens to be transferred */ function transferFrom(address from, address to, uint256 value) public returns (bool) { require(_sectransfer(from, to, value)); return super.transferFrom(from, to, value); } }
Transfer token for a specified address to The address to transfer to. value The amount to be transferred./
function transfer(address to, uint256 value) public returns (bool) { require(_sectransfer(msg.sender, to, value)); return super.transfer(to, value); }
13,002,054
//SPDX-License-Identifier: UNLICENSED pragma solidity ^0.7.6; pragma abicoder v2; import "hardhat/console.sol"; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; contract Token is ERC20{ using SafeMath for uint256; uint public constant supply = 500; struct Checkpoint { uint256 fromBlock; uint256 value; } // history of account balance mapping(address => Checkpoint[]) balances; // total delegated percents per address at given time mapping(address => Checkpoint[]) totalDelegated; // delegator => delegatee => percent mapping(address => mapping(address => uint256)) delegations; // all current delegatees of address mapping(address => address[]) public delegatees; // cumulated delegated voting power to address mapping(address => Checkpoint[]) delegatedVotingPower; constructor() public ERC20("AB", "AB") { // mint some _updateValueAtNow(balances[msg.sender], supply); emit Transfer(address(0), msg.sender, supply); } function balanceOf(address _account) public view override returns (uint256) { return balanceOfAt(_account, block.number); } function balanceOfAt(address _address, uint256 _blockNumber) public view returns(uint256) { return _getValueAt(balances[_address], _blockNumber); } /** *** DELEGATE */ function delegate(address _delegatee, uint8 _percentage) public { require(_percentage <= 100, "Trying to delegate over 100%"); require(_delegatee != msg.sender, "Trying to delegate to self"); // get current values uint nowTotalDelegated = _getValueAt(totalDelegated[msg.sender], block.number); uint nowDelegatedToAddress = delegations[msg.sender][_delegatee]; if(nowDelegatedToAddress == 0) { require(delegatees[msg.sender].length < 5, "Maximum 5 delegatees"); } // update delegatee value require(nowTotalDelegated.sub(nowDelegatedToAddress).add(_percentage) <= 100, "Total delegation over 100%"); _updateValueAtNow(totalDelegated[msg.sender], nowTotalDelegated.sub(nowDelegatedToAddress).add(_percentage)); delegations[msg.sender][_delegatee] = _percentage; // update delegatee voting power uint sendersBalance = balanceOf(msg.sender); uint currentContribution = nowDelegatedToAddress.mul(sendersBalance).div(100); uint power = sendersBalance.mul(_percentage).div(100); uint currentDelegatedPower = _getValueAt(delegatedVotingPower[_delegatee], block.number); _updateValueAtNow(delegatedVotingPower[_delegatee], currentDelegatedPower.add(power).sub(currentContribution)); // update delegates list if (_percentage == 0) _removeFromArray(delegatees[msg.sender], _delegatee); else if (nowDelegatedToAddress == 0) delegatees[msg.sender].push(_delegatee); } function votePowerOfAt(address _address, uint256 _block) public view returns(uint256) { require(block.number > _block, "Given block in the future"); uint balance = balanceOfAt(_address, _block); uint delegatedPowerOfAddress = balance.mul(_getValueAt(totalDelegated[_address], _block)).div(100); return balance.sub(delegatedPowerOfAddress).add(_getValueAt(delegatedVotingPower[_address], _block)); } /** ** INTERNAL FUNCTIONS */ function _transfer(address _sender, address _recipient, uint256 _amount) internal override { require(_sender != address(0), "ERC20: transfer from the zero address"); require(_recipient != address(0), "ERC20: transfer to the zero address"); uint256 currentSenderBalance = balanceOfAt(_sender, block.number); require (currentSenderBalance >= _amount, "Sender balance too small"); uint256 currentRecipientBalance = balanceOfAt(_recipient, block.number); _updateValueAtNow(balances[_sender], currentSenderBalance.sub(_amount)); _updateValueAtNow(balances[_recipient], currentRecipientBalance.add(_amount)); // update delegated power _updateVotingPower(_sender, currentSenderBalance, currentSenderBalance.sub(_amount)); _updateVotingPower(_recipient, currentRecipientBalance, currentRecipientBalance.add(_amount)); emit Transfer(_sender, _recipient, _amount); } // update delegatees voting power on balance change function _updateVotingPower(address _address, uint256 previousBalance, uint256 currentBalance) internal { for(uint i=0; i<delegatees[_address].length; i++) { uint256 previousContribution = delegations[_address][delegatees[_address][i]].mul(previousBalance).div(100); uint256 currentContribution = delegations[_address][delegatees[_address][i]].mul(currentBalance).div(100); uint256 newVotingPower = _getValueAt(delegatedVotingPower[delegatees[_address][i]], block.number).sub(previousContribution).add(currentContribution); _updateValueAtNow(delegatedVotingPower[delegatees[_address][i]], newVotingPower); } } function _updateValueAtNow(Checkpoint[] storage checkpoints, uint _value) internal { if ((checkpoints.length == 0) || (checkpoints[checkpoints.length -1].fromBlock < block.number)) { checkpoints.push(Checkpoint(block.number, _value)); } else { checkpoints[checkpoints.length -1].value = _value; } } function _getValueAt(Checkpoint[] storage checkpoints, uint256 _blockNumber) internal view returns(uint256) { require(_blockNumber <= block.number, "Block is in the future"); // LESS OR LE uint nCheckpoints = checkpoints.length; if (nCheckpoints == 0) { return 0; } if (checkpoints[nCheckpoints - 1].fromBlock <= _blockNumber) { return checkpoints[nCheckpoints - 1].value; } if (checkpoints[0].fromBlock > _blockNumber) { return 0; } uint lower = 0; uint upper = nCheckpoints - 1; while (upper > lower) { uint center = upper - (upper - lower) / 2; // ceil, avoiding overflow Checkpoint memory cp = checkpoints[center]; if (cp.fromBlock == _blockNumber) { return cp.value; } else if (cp.fromBlock < _blockNumber) { lower = center; } else { upper = center - 1; } } return checkpoints[lower].value; } function _removeFromArray(address[] storage _array, address _addr) internal { for (uint8 i=0; i < _array.length; i++) { if (_array[i] == _addr) { if (i != _array.length - 1) { // first in 1-elem array, or last elem in array _array[i] = _array[_array.length-1]; } _array.pop(); return; } } } }
DELEGATE/ get current values
function delegate(address _delegatee, uint8 _percentage) public { require(_percentage <= 100, "Trying to delegate over 100%"); require(_delegatee != msg.sender, "Trying to delegate to self"); uint nowTotalDelegated = _getValueAt(totalDelegated[msg.sender], block.number); uint nowDelegatedToAddress = delegations[msg.sender][_delegatee]; if(nowDelegatedToAddress == 0) { require(delegatees[msg.sender].length < 5, "Maximum 5 delegatees"); } _updateValueAtNow(totalDelegated[msg.sender], nowTotalDelegated.sub(nowDelegatedToAddress).add(_percentage)); delegations[msg.sender][_delegatee] = _percentage; uint currentContribution = nowDelegatedToAddress.mul(sendersBalance).div(100); uint power = sendersBalance.mul(_percentage).div(100); uint currentDelegatedPower = _getValueAt(delegatedVotingPower[_delegatee], block.number); _updateValueAtNow(delegatedVotingPower[_delegatee], currentDelegatedPower.add(power).sub(currentContribution)); else if (nowDelegatedToAddress == 0) delegatees[msg.sender].push(_delegatee); }
12,955,226
/* * ABDK Multisig Wallet Smart Contract. * Copyright © 2017-2019 by ABDK Consulting (https://abdk.consulting/). * Author: Mikhail Vladimirov <[email protected]> */ pragma solidity ^0.5.7; /** * ABDK Multisig Wallet smart contract allows multiple (up to 255) parties to * collectively own an Ethereum address. This address may be used to securely * store ether and to execute Ethereum transactions once approved by certain * number of owners. */ contract ABDKMultisigWallet { /** * Create new ABDK Multisig Wallet smart contract and make msg.sender to be * the only owner of it. The number of required approvals is set to one. */ constructor () public { // Zero address may not be an owner require (msg.sender != address (0)); // Save msg.sender address as owner #1 (#0 is reserved) owners [1] = msg.sender; ownerIndexes [msg.sender] = 1; // Set number of required approvals to one approvalsRequired = 1; // Set owners count to one ownersCount = 1; // Log OwnerChange event emit OwnerChange (1, address (0), msg.sender); } /** * Fallback function that just logs incoming ether transfers. */ function () external payable { // Just log ether deposit origin, value, and data emit Deposit (msg.sender, msg.value, msg.data); } /** * Suggest transaction with given hash to be executed. * * @param _hash hash of the transaction to be suggested * @return ID of the suggestion created */ function suggest (bytes32 _hash) public returns (uint256) { // Only owners may suggest transactions require (ownerIndexes [msg.sender] > 0); // Zero hash is not allowed, sorry require (_hash != bytes32 (0)); // Generate new unique suggestion ID (don't care about overflow) uint256 id = nextSuggestionID++; // Save hash of the suggested transaction suggestions [id].hash = _hash; // Log Suggestion event emit Suggestion (id, msg.sender, _hash); // Return ID of the suggestion created return id; } /** * Reveal parameters of suggested transaction with given ID. * * @param _id ID of the suggested transaction to reveal parameters of * @param _to destination address of the transaction * @param _value value of the transaction * @param _data data of the transaction * @param _salt salt used to calculate transaction hash */ function reveal ( uint256 _id, address _to, uint256 _value, bytes memory _data, uint256 _salt) public { // Only owners may reveal transactions require (ownerIndexes [msg.sender] > 0); // Make sure parameters do match hash of the suggested transaction require (checkHash (_id, _to, _value, _data, _salt)); // Log Revelation event emit Revelation (_id, msg.sender, _to, _value, _data, _salt); } /** * Approve suggested transaction with given ID. * * @param _id ID of the suggested transaction to be approved */ function approve (uint256 _id) public { // Get index of the owner who wants to approve suggested transaction uint8 ownerIndex = ownerIndexes [msg.sender]; // Only owners may approve require (ownerIndex > 0); // Obtain information about suggested transaction with given ID SuggestionInfo storage suggestion = suggestions [_id]; // Make sure suggested with such ID does exist require (suggestion.hash != bytes32 (0)); // Calculate bit mask for the owner uint256 mask = uint256 (1) << ownerIndex; // Make sure this owner didn't approve this transaction yet require (suggestion.approvals & mask == 0); // Approve the transaction suggestion.approvals |= mask; suggestion.approvalsCount += 1; // Log Approval event emit Approval (_id, msg.sender); } /** * Revoke approval for suggested transaction with given ID. * * @param _id ID of the suggested transaction to revoke approval for */ function revokeApproval (uint256 _id) public { // Get index of the owner who wants to approve suggested transaction uint8 ownerIndex = ownerIndexes [msg.sender]; // Only owners may approve require (ownerIndex > 0); // Obtain information about suggested transaction with given ID SuggestionInfo storage suggestion = suggestions [_id]; // Make sure suggested with such ID does exist require (suggestion.hash != bytes32 (0)); // Calculate bit mask for the owner uint256 mask = uint256 (1) << ownerIndex; // Make sure this owner did approve this transaction require (suggestion.approvals & mask != 0); // Revoke approval for the transaction suggestion.approvals ^= mask; suggestion.approvalsCount -= 1; // Log ApprovalRevocation event emit ApprovalRevocation (_id, msg.sender); } /** * Execute suggested transaction with given ID and parameters. * * @param _id ID of the suggested transaction to be executed * @param _to destination address of the transaction * @param _value value of the transaction * @param _data data of the transaction * @param _salt salt used to calculate transaction hash * @return transaction execution status and returned data */ function execute ( uint256 _id, address _to, uint256 _value, bytes memory _data, uint256 _salt) public returns (bool _status, bytes memory _returnedData) { // Only owners may execute transactions require (ownerIndexes [msg.sender] > 0); // Obtain information about suggested transaction with given ID SuggestionInfo storage suggestion = suggestions [_id]; // Make sure parameters do match hash of the suggested transaction require (checkHash (_id, _to, _value, _data, _salt)); // Make sure transaction has enough approvals require (suggestion.approvalsCount >= approvalsRequired); // Clear transaction information suggestion.hash = bytes32 (0); suggestion.approvals = 0; suggestion.approvalsCount = 0; // Execute the transaction and remember execution result (_status, _returnedData) = _to.call.value (_value)(_data); // Log Execution event emit Execution (_id, msg.sender, _status, _returnedData); } /** * Create smart contract with given byte code. * * @param _byteCode byte code to create smart contract with * @return created smart contract address and data returned by smart contract * creation */ function createSmartContract (bytes memory _byteCode) public payable returns ( address _contractAddress, bytes memory _returnedData) { // Contract creation may be performed only by the contract itself require (msg.sender == address (this)); assembly { _contractAddress := create ( callvalue (), add (_byteCode, 0x20), mload (_byteCode)) let l := returndatasize () let p := mload (0x40) _returnedData := p mstore (p, l) p := add (p, 0x20) returndatacopy (p, 0x0, l) mstore (0x40, add (p, l)) } emit SmartContractCreation (_contractAddress, _returnedData); } /** * Create smart contract using CREATE2 opcode with given byte code and salt. * * @param _byteCode byte code to create smart contract with * @param _salt salt to use for generating smart contract address * @return created smart contract address and data returned by smart contract * creation */ function createSmartContract2 (bytes memory _byteCode, bytes32 _salt) public payable returns ( address _contractAddress, bytes memory _returnedData) { // Contract creation may be performed only by the contract itself require (msg.sender == address (this)); assembly { _contractAddress := create2 ( callvalue (), add (_byteCode, 0x20), mload (_byteCode), _salt) let l := returndatasize () let p := mload (0x40) _returnedData := p mstore (p, l) p := add (p, 0x20) returndatacopy (p, 0x0, l) mstore (0x40, add (p, l)) } emit SmartContractCreation (_contractAddress, _returnedData); } /** * Replace existing owner with given index with given new owner. If there is * no owner with given index, add new owner at given index. If given new * owner address is zero, remove owner with given index. * * @param _ownerIndex index of the owner to be replaced * @param _newOwner address of the new owner */ function changeOwner (uint8 _ownerIndex, address _newOwner) public { // Owner changing may be performed only by the contract itself require (msg.sender == address (this)); // Zero owner index is reserved require (_ownerIndex > 0); // Make sure new owner is not already an owner require (ownerIndexes [_newOwner] == 0); // Obtain address of existing owner with given index address oldOwner = owners [_ownerIndex]; // Could you think of situation when this is not true? We could! if (oldOwner != _newOwner) { // If owner with given index exists if (oldOwner != address (0)) { // Remove it! ownerIndexes [oldOwner] = 0; } else { // Otherwise increase owners count ownersCount += 1; } owners [_ownerIndex] = _newOwner; // If new owner is not zero if (_newOwner != address (0)) { // Add it! ownerIndexes [_newOwner] = _ownerIndex; } else { // Otherwise decrease owners count ownersCount -= 1; } // Log OwnerChange event emit OwnerChange (_ownerIndex, oldOwner, _newOwner); } } /** * Set number of approvals required to execute transaction. * * @param _approvalsRequired new number of approvals required */ function setApprovalsRequired (uint8 _approvalsRequired) public { // Changing of number of required approvals may be performed only by the // contract itself require (msg.sender == address (this)); // If new value actually differs from the existing one if (approvalsRequired != _approvalsRequired) { approvalsRequired = _approvalsRequired; emit ApprovalsRequiredChange (_approvalsRequired); } } /** * Cancel transaction suggestion. * * @param _id ID of the suggested transaction to be cancelled */ function cancelSuggestion (uint256 _id) public { // Transaction suggestions may only be cancelled by the contract itself require (msg.sender == address (this)); // Obtain information about suggested transaction with given ID SuggestionInfo storage suggestion = suggestions [_id]; // Make sure suggestion with given ID does exist require (suggestion.hash != bytes32 (0)); // Clear suggestion information suggestion.hash = bytes32 (0); suggestion.approvals = 0; suggestion.approvalsCount = 0; // Log SuggestionCAncellation event. emit SuggestionCancellation (_id); } /** * Calculate hash of transaction with given parameters. * * @param _to transaction destination address * @param _value transaction value * @param _data transaction data * @param _salt salt to use for hash calculation * @return transaction hash */ function calculateHash ( address _to, uint256 _value, bytes memory _data, uint256 _salt) public pure returns (bytes32) { // Calculate and return transaction hash return keccak256 (abi.encodePacked (_to, _value, _data, _salt)); } /** * Check hash of suggested transaction with given ID. * * @param _id ID of the suggested transaction to check index for * @param _to transaction destination address * @param _value transaction value * @param _data transaction data * @param _salt salt to use for hash calculation * @return true if hash of suggested transaction with given ID matches * transaction parameters provided, false otherwise */ function checkHash ( uint256 _id, address _to, uint256 _value, bytes memory _data, uint256 _salt) public view returns (bool) { // Obtain hash of the suggested transaction with given ID bytes32 hash = suggestions [_id].hash; // Make sure suggestion with given ID does exist require (hash != bytes32 (0)); return hash == calculateHash (_to, _value, _data, _salt); } /** * Get number of approvals already collected for suggested transaction with * given ID. * * @param _id ID of the suggested transaction to get number of approvals for * @return number of approvals collected for suggested transaction with given * ID */ function approvalsCount (uint256 _id) public view returns (uint8) { // Obtain information about suggested transaction with given ID SuggestionInfo storage suggestion = suggestions [_id]; // Make sure suggestion with given ID does exist require (suggestion.hash != bytes32 (0)); // Return approvals count for suggestion return suggestion.approvalsCount; } /** * Get hash of parameters of suggested transaction with given ID. * * @param _id ID of the suggested transaction to get hash of parameters for * @return hash of parameters of suggested transaction with given ID */ function hashOf (uint256 _id) public view returns (bytes32) { // Obtain information about suggested transaction with given ID SuggestionInfo storage suggestion = suggestions [_id]; // Make sure suggestion with given ID does exist require (suggestion.hash != bytes32 (0)); // Return hash of transaction parameters for suggestion return suggestion.hash; } /** * Tell whether suggested transaction with given ID has collected enough * approvals to be executed. * * @param _id ID of the suggested transaction to check * @return true if suggested transaction with given ID has collected enough * approvals to be executed, false otherwise */ function isApproved (uint256 _id) public view returns (bool) { // Obtain information about suggested transaction with given ID SuggestionInfo storage suggestion = suggestions [_id]; // Make sure suggestion with given ID does exist require (suggestion.hash != bytes32 (0)); // Check whether transaction has collected enough approvals return suggestion.approvalsCount >= approvalsRequired; } /** * Tell whether given owner has approved suggested transaction with given ID. * * @param _id ID of the suggested transaction to check approval for * @param _owner owner to check approval by * @return true if given owner has approved suggested transaction with given * ID, false otherwise */ function isApprovedBy (uint256 _id, address _owner) public view returns (bool) { // Obtain information about suggested transaction with given ID SuggestionInfo storage suggestion = suggestions [_id]; // Make sure suggestion with given ID does exist require (suggestion.hash != bytes32 (0)); // Obtain index of given owner uint8 ownerIndex = ownerIndexes [_owner]; // Make sure such owner actually exists require (ownerIndex > 0); // Check whether given owner has approved the transaction return (suggestion.approvals & (uint256 (1) << ownerIndex)) != 0; } /** * Get address of the owner with given index. * * @param _index index to get address of the owner at * @return address of the owner with given index or zero if there is no owner * with such index */ function getOwnerAt (uint8 _index) public view returns (address) { // Zero index is reserved require (_index > 0); return owners [_index]; } /** * Suggest transaction to be executed and reveal its parameters. * * @param _to transaction destination * @param _value transaction value * @param _data transaction data * @return ID of the suggestion created */ function suggestAndReveal (address _to, uint256 _value, bytes memory _data) public returns (uint256) { // Suggest transaction uint256 id = suggest (calculateHash (_to, _value, _data, 0)); // Reveal transaction reveal (id, _to, _value, _data, 0); // Return suggestion ID return id; } /** * Suggest transaction to be executed, reveal its parameters, and approve the * transaction. * * @param _to transaction destination * @param _value transaction value * @param _data transaction data * @return ID of the suggestion created */ function suggestRevealAndApprove (address _to, uint256 _value, bytes memory _data) public returns (uint256) { // Suggest transaction and reveal its parameters uint256 id = suggestAndReveal (_to, _value, _data); // Approve transaction approve (id); // Return suggestion ID return id; } /** * Suggest transaction with given hash to be executed and approve this * transaction. * * @param _hash hash of transaction parameters * @return ID of the suggestion created */ function suggestAndApprove (bytes32 _hash) public returns (uint256) { // Suggest transaction uint256 id = suggest (_hash); // Approve transaction approve (id); // Return suggestion ID return id; } /** * Suggest transaction with given hash to be executed, approve this * transaction, and execute it. * * @param _to transaction destination * @param _value transaction value * @param _data transaction data * @return transaction execution status and returned data */ function suggestApproveAndExecute (address _to, uint256 _value, bytes memory _data) public returns (bool _status, bytes memory _returnedData) { // Suggest transaction and approve it uint256 id = suggestAndApprove (calculateHash (_to, _value, _data, 0)); // Execute transaction return execute (id, _to, _value, _data, 0); } /** * Approve transaction and execute it. * * @param _id ID of the suggested transaction to approve and execute * @param _to transaction destination * @param _value transaction value * @param _data transaction data * @param _salt salt used to calculate transaction hash * @return transaction execution status and returned data */ function approveAndExecute ( uint256 _id, address _to, uint256 _value, bytes memory _data, uint256 _salt) public returns (bool _status, bytes memory _returnedData) { // Approve transaction approve (_id); // Execute transaction return execute (_id, _to, _value, _data, _salt); } /** * Owners of the wallet. */ address [256] private owners; /** * Maps owner addresses to owner indexes. */ mapping (address => uint8) private ownerIndexes; /** * Next unique ID for suggested transaction. */ uint256 private nextSuggestionID = 0; /** * Number of owners of the smart contract. */ uint8 public ownersCount; /** * Number of approvals required to execute transaction. */ uint8 public approvalsRequired; /** * Maps unique ID of suggested transaction to suggested transaction * information. */ mapping (uint256 => SuggestionInfo) private suggestions; /** * Encapsulates information about suggested transaction. */ struct SuggestionInfo { /** * Hash of the suggested transaction. */ bytes32 hash; /** * Approvals mask */ uint256 approvals; /** * Number of approvals collected. */ uint8 approvalsCount; } /** * Logged with ether was deposited to the smart contract. * * @param from address deposited ether came from * @param value amount of ether deposited (may be zero) * @param data transaction data */ event Deposit (address indexed from, uint256 value, bytes data); /** * Logged when new transaction is suggested. * * @param id ID of the suggested transaction * @param owner owner that suggested the transaction * @param hash hash of the suggested transaction */ event Suggestion ( uint256 indexed id, address indexed owner, bytes32 indexed hash); /** * Logged when parameters of suggested transaction was revealed. * * @param id ID of the suggested transaction parameters was revealed of * @param owner owner that revealed transaction parameters * @param to transaction destination address * @param value transaction value * @param data transaction data * @param salt salt used for calculating transaction hash */ event Revelation ( uint256 indexed id, address indexed owner, address indexed to, uint256 value, bytes data, uint256 salt); /** * Logged when suggested transaction was approved by an owner. * * @param id ID of the suggested transaction that was approved * @param owner address of the owner that approved the suggested transaction */ event Approval (uint256 indexed id, address indexed owner); /** * Logged when approval for suggested transaction was revoked by an owner. * * @param id ID of the suggested transaction the approval was revoked for * @param owner address of the owner that revoked approval for the suggested * transaction */ event ApprovalRevocation (uint256 indexed id, address indexed owner); /** * Logged when transaction was executed by an owner. * * @param id ID of the transaction that was executed * @param owner address of the owner that executed the transaction * @param status transaction execution status * @param returnedData data returned by transaction execution */ event Execution (uint256 indexed id, address indexed owner, bool status, bytes returnedData); /** * Logged when smart contract was created. * * @param contractAddress address of created smart contract * @param returnedData data returned by smart contract creation */ event SmartContractCreation (address indexed contractAddress, bytes returnedData); /** * Logged when owner with given index was changed. * * @param ownerIndex index of the changed owner * @param oldOwner old owner at given index or zero if owner was added * @param newOwner new owner at given index or zero if owner was removed */ event OwnerChange ( uint8 indexed ownerIndex, address indexed oldOwner, address indexed newOwner); /** * Logged when number of required approvals was changed. * * @param newApprovalsRequired new value of the number of required approvals */ event ApprovalsRequiredChange (uint8 newApprovalsRequired); /** * Logged when suggested transaction was cancelled. * * @param id ID of cancelled suggested transaction */ event SuggestionCancellation (uint256 indexed id); }
Reveal parameters of suggested transaction with given ID. _id ID of the suggested transaction to reveal parameters of _to destination address of the transaction _value value of the transaction _data data of the transaction _salt salt used to calculate transaction hash/ Only owners may reveal transactions Make sure parameters do match hash of the suggested transaction Log Revelation event
function reveal ( uint256 _id, address _to, uint256 _value, bytes memory _data, uint256 _salt) public { require (ownerIndexes [msg.sender] > 0); require (checkHash (_id, _to, _value, _data, _salt)); emit Revelation (_id, msg.sender, _to, _value, _data, _salt); }
12,854,370
// SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20Upgradeable { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * ////IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } /** * SourceUnit: /home/fabio/Jibrel/tranche-compound-protocol/contracts/JTrancheBToken.sol */ ////// SPDX-License-Identifier-FLATTEN-SUPPRESS-WARNING: MIT pragma solidity >=0.6.2 <0.8.0; /** * @dev Collection of functions related to the address type */ library AddressUpgradeable { /** * @dev Returns true if `account` is a contract. * * [////IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * ////IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: value }(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } /** * SourceUnit: /home/fabio/Jibrel/tranche-compound-protocol/contracts/JTrancheBToken.sol */ ////// SPDX-License-Identifier-FLATTEN-SUPPRESS-WARNING: MIT // solhint-disable-next-line compiler-version pragma solidity >=0.4.24 <0.8.0; ////import "../utils/AddressUpgradeable.sol"; /** * @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed * behind a proxy. Since a proxied contract can't have a constructor, it's common to move constructor logic to an * external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer * function so it can only be called once. The {initializer} modifier provided by this contract will have this effect. * * TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as * possible by providing the encoded function call as the `_data` argument to {UpgradeableProxy-constructor}. * * CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure * that all initializers are idempotent. This is not verified automatically as constructors are by Solidity. */ abstract contract Initializable { /** * @dev Indicates that the contract has been initialized. */ bool private _initialized; /** * @dev Indicates that the contract is in the process of being initialized. */ bool private _initializing; /** * @dev Modifier to protect an initializer function from being invoked twice. */ modifier initializer() { require(_initializing || _isConstructor() || !_initialized, "Initializable: contract is already initialized"); bool isTopLevelCall = !_initializing; if (isTopLevelCall) { _initializing = true; _initialized = true; } _; if (isTopLevelCall) { _initializing = false; } } /// @dev Returns true if and only if the function is running in the constructor function _isConstructor() private view returns (bool) { return !AddressUpgradeable.isContract(address(this)); } } /** * SourceUnit: /home/fabio/Jibrel/tranche-compound-protocol/contracts/JTrancheBToken.sol */ ////// SPDX-License-Identifier-FLATTEN-SUPPRESS-WARNING: MIT pragma solidity >=0.6.0 <0.8.0; ////import "../proxy/Initializable.sol"; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract ContextUpgradeable is Initializable { function __Context_init() internal initializer { __Context_init_unchained(); } function __Context_init_unchained() internal initializer { } function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } uint256[50] private __gap; } /** * SourceUnit: /home/fabio/Jibrel/tranche-compound-protocol/contracts/JTrancheBToken.sol */ ////// SPDX-License-Identifier-FLATTEN-SUPPRESS-WARNING: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Library for managing * https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive * types. * * Sets have the following properties: * * - Elements are added, removed, and checked for existence in constant time * (O(1)). * - Elements are enumerated in O(n). No guarantees are made on the ordering. * * ``` * contract Example { * // Add the library methods * using EnumerableSet for EnumerableSet.AddressSet; * * // Declare a set state variable * EnumerableSet.AddressSet private mySet; * } * ``` * * As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`) * and `uint256` (`UintSet`) are supported. */ library EnumerableSetUpgradeable { // To implement this library for multiple types with as little code // repetition as possible, we write it in terms of a generic Set type with // bytes32 values. // The Set implementation uses private functions, and user-facing // implementations (such as AddressSet) are just wrappers around the // underlying Set. // This means that we can only create new EnumerableSets for types that fit // in bytes32. struct Set { // Storage of set values bytes32[] _values; // Position of the value in the `values` array, plus 1 because index 0 // means a value is not in the set. mapping (bytes32 => uint256) _indexes; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function _add(Set storage set, bytes32 value) private returns (bool) { if (!_contains(set, value)) { set._values.push(value); // The value is stored at length-1, but we add 1 to all indexes // and use 0 as a sentinel value set._indexes[value] = set._values.length; return true; } else { return false; } } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function _remove(Set storage set, bytes32 value) private returns (bool) { // We read and store the value's index to prevent multiple reads from the same storage slot uint256 valueIndex = set._indexes[value]; if (valueIndex != 0) { // Equivalent to contains(set, value) // To delete an element from the _values array in O(1), we swap the element to delete with the last one in // the array, and then remove the last element (sometimes called as 'swap and pop'). // This modifies the order of the array, as noted in {at}. uint256 toDeleteIndex = valueIndex - 1; uint256 lastIndex = set._values.length - 1; // When the value to delete is the last one, the swap operation is unnecessary. However, since this occurs // so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement. bytes32 lastvalue = set._values[lastIndex]; // Move the last value to the index where the value to delete is set._values[toDeleteIndex] = lastvalue; // Update the index for the moved value set._indexes[lastvalue] = toDeleteIndex + 1; // All indexes are 1-based // Delete the slot where the moved value was stored set._values.pop(); // Delete the index for the deleted slot delete set._indexes[value]; return true; } else { return false; } } /** * @dev Returns true if the value is in the set. O(1). */ function _contains(Set storage set, bytes32 value) private view returns (bool) { return set._indexes[value] != 0; } /** * @dev Returns the number of values on the set. O(1). */ function _length(Set storage set) private view returns (uint256) { return set._values.length; } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function _at(Set storage set, uint256 index) private view returns (bytes32) { require(set._values.length > index, "EnumerableSet: index out of bounds"); return set._values[index]; } // Bytes32Set struct Bytes32Set { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _add(set._inner, value); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _remove(set._inner, value); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) { return _contains(set._inner, value); } /** * @dev Returns the number of values in the set. O(1). */ function length(Bytes32Set storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) { return _at(set._inner, index); } // AddressSet struct AddressSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(AddressSet storage set, address value) internal returns (bool) { return _add(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(AddressSet storage set, address value) internal returns (bool) { return _remove(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(AddressSet storage set, address value) internal view returns (bool) { return _contains(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Returns the number of values in the set. O(1). */ function length(AddressSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(AddressSet storage set, uint256 index) internal view returns (address) { return address(uint160(uint256(_at(set._inner, index)))); } // UintSet struct UintSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(UintSet storage set, uint256 value) internal returns (bool) { return _add(set._inner, bytes32(value)); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(UintSet storage set, uint256 value) internal returns (bool) { return _remove(set._inner, bytes32(value)); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(UintSet storage set, uint256 value) internal view returns (bool) { return _contains(set._inner, bytes32(value)); } /** * @dev Returns the number of values on the set. O(1). */ function length(UintSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(UintSet storage set, uint256 index) internal view returns (uint256) { return uint256(_at(set._inner, index)); } } /** * SourceUnit: /home/fabio/Jibrel/tranche-compound-protocol/contracts/JTrancheBToken.sol */ ////// SPDX-License-Identifier-FLATTEN-SUPPRESS-WARNING: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMathUpgradeable { /** * @dev Returns the addition of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b > a) return (false, 0); return (true, a - b); } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a / b); } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a % b); } /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a, "SafeMath: subtraction overflow"); return a - b; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) return 0; uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers, reverting on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: division by zero"); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: modulo by zero"); return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); return a - b; } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryDiv}. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a % b; } } /** * SourceUnit: /home/fabio/Jibrel/tranche-compound-protocol/contracts/JTrancheBToken.sol */ ////// SPDX-License-Identifier-FLATTEN-SUPPRESS-WARNING: MIT pragma solidity 0.6.12; ////import "@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol"; contract JTrancheBTokenStorage { /* WARNING: NEVER RE-ORDER VARIABLES! Always double-check that new variables are added APPEND-ONLY. Re-ordering variables can permanently BREAK the deployed proxy contract.*/ // optimize, see https://github.com/ethereum/EIPs/issues/1726#issuecomment-472352728 uint256 constant public pointsMultiplier = 2**128; // Create a new role identifier for the minter role bytes32 public constant MINTER_ROLE = keccak256("MINTER_ROLE"); uint256 public pointsPerShare; mapping(address => int256) public pointsCorrection; mapping(address => uint256) public withdrawnFunds; // token in which the funds can be sent to the FundsDistributionToken IERC20Upgradeable public rewardsToken; // balance of rewardsToken that the FundsDistributionToken currently holds uint256 public rewardsTokenBalance; } /** * SourceUnit: /home/fabio/Jibrel/tranche-compound-protocol/contracts/JTrancheBToken.sol */ ////// SPDX-License-Identifier-FLATTEN-SUPPRESS-WARNING: MIT pragma solidity 0.6.12; interface IFDTBasic { /** * @dev Returns the total amount of funds a given address is able to withdraw currently. * @param owner Address of FundsDistributionToken holder * @return A uint256 representing the available funds for a given account */ function withdrawableFundsOf(address owner) external view returns (uint256); /** * @dev This event emits when new funds are distributed * @param by the address of the sender who distributed funds * @param fundsDistributed the amount of funds received for distribution */ event FundsDistributed(address indexed by, uint256 fundsDistributed); /** * @dev This event emits when distributed funds are withdrawn by a token holder. * @param by the address of the receiver of funds * @param fundsWithdrawn the amount of funds that were withdrawn */ event FundsWithdrawn(address indexed by, uint256 fundsWithdrawn); } /** * SourceUnit: /home/fabio/Jibrel/tranche-compound-protocol/contracts/JTrancheBToken.sol */ ////// SPDX-License-Identifier-FLATTEN-SUPPRESS-WARNING: MIT pragma solidity 0.6.12; /** * @title SafeMathInt * @dev Math operations with safety checks that revert on error * @dev SafeMath adapted for int256 * Based on code of https://github.com/RequestNetwork/requestNetwork/blob/master/packages/requestNetworkSmartContracts/contracts/base/math/SafeMathInt.sol */ library SafeMathInt { function mul(int256 a, int256 b) internal pure returns (int256) { // Prevent overflow when multiplying INT256_MIN with -1 // https://github.com/RequestNetwork/requestNetwork/issues/43 require(!(a == - 2**255 && b == -1) && !(b == - 2**255 && a == -1)); int256 c = a * b; require((b == 0) || (c / b == a)); return c; } function div(int256 a, int256 b) internal pure returns (int256) { // Prevent overflow when dividing INT256_MIN by -1 // https://github.com/RequestNetwork/requestNetwork/issues/43 require(!(a == - 2**255 && b == -1) && (b > 0)); return a / b; } function sub(int256 a, int256 b) internal pure returns (int256) { require((b >= 0 && a - b <= a) || (b < 0 && a - b > a)); return a - b; } function add(int256 a, int256 b) internal pure returns (int256) { int256 c = a + b; require((b >= 0 && c >= a) || (b < 0 && c < a)); return c; } function toUint256Safe(int256 a) internal pure returns (uint256) { require(a >= 0); return uint256(a); } } /** * SourceUnit: /home/fabio/Jibrel/tranche-compound-protocol/contracts/JTrancheBToken.sol */ ////// SPDX-License-Identifier-FLATTEN-SUPPRESS-WARNING: MIT pragma solidity 0.6.12; /** * @title SafeMathUint * @dev Math operations with safety checks that revert on error */ library SafeMathUint { function toInt256Safe(uint256 a) internal pure returns (int256) { int256 b = int256(a); require(b >= 0); return b; } } /** * SourceUnit: /home/fabio/Jibrel/tranche-compound-protocol/contracts/JTrancheBToken.sol */ ////// SPDX-License-Identifier-FLATTEN-SUPPRESS-WARNING: MIT /** * Created on 2021-01-16 * @summary: JTranches Interface * @author: Jibrel Team */ pragma solidity 0.6.12; interface IJTrancheTokens { function mint(address account, uint256 value) external; function burn(uint256 value) external; function updateFundsReceived() external; function emergencyTokenTransfer(address _token, address _to, uint256 _amount) external; function setRewardTokenAddress(address _token) external; } /** * SourceUnit: /home/fabio/Jibrel/tranche-compound-protocol/contracts/JTrancheBToken.sol */ ////// SPDX-License-Identifier-FLATTEN-SUPPRESS-WARNING: MIT pragma solidity >=0.6.0 <0.8.0; ////import "../utils/EnumerableSetUpgradeable.sol"; ////import "../utils/AddressUpgradeable.sol"; ////import "../utils/ContextUpgradeable.sol"; ////import "../proxy/Initializable.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 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; } /** * SourceUnit: /home/fabio/Jibrel/tranche-compound-protocol/contracts/JTrancheBToken.sol */ ////// SPDX-License-Identifier-FLATTEN-SUPPRESS-WARNING: MIT pragma solidity >=0.6.0 <0.8.0; ////import "../utils/ContextUpgradeable.sol"; ////import "../proxy/Initializable.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract OwnableUpgradeable is Initializable, ContextUpgradeable { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ function __Ownable_init() internal initializer { __Context_init_unchained(); __Ownable_init_unchained(); } function __Ownable_init_unchained() internal initializer { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } uint256[49] private __gap; } /** * SourceUnit: /home/fabio/Jibrel/tranche-compound-protocol/contracts/JTrancheBToken.sol */ ////// SPDX-License-Identifier-FLATTEN-SUPPRESS-WARNING: MIT pragma solidity >=0.6.0 <0.8.0; ////import "../../utils/ContextUpgradeable.sol"; ////import "./IERC20Upgradeable.sol"; ////import "../../math/SafeMathUpgradeable.sol"; ////import "../../proxy/Initializable.sol"; /** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20PresetMinterPauser}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin guidelines: functions revert instead * of returning `false` on failure. This behavior is nonetheless conventional * and does not conflict with the expectations of ERC20 applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */ contract ERC20Upgradeable is Initializable, ContextUpgradeable, IERC20Upgradeable { using SafeMathUpgradeable 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. */ function __ERC20_init(string memory name_, string memory symbol_) internal initializer { __Context_init_unchained(); __ERC20_init_unchained(name_, symbol_); } function __ERC20_init_unchained(string memory name_, string memory symbol_) internal initializer { _name = name_; _symbol = symbol_; _decimals = 18; } /** * @dev Returns the name of the token. */ function name() public view virtual returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view virtual returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless {_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 virtual 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); _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 virtual { _decimals = decimals_; } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be to transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { } uint256[44] private __gap; } /** * SourceUnit: /home/fabio/Jibrel/tranche-compound-protocol/contracts/JTrancheBToken.sol */ ////// SPDX-License-Identifier-FLATTEN-SUPPRESS-WARNING: MIT pragma solidity 0.6.12; ////import "@openzeppelin/contracts-upgradeable/token/ERC20/ERC20Upgradeable.sol"; ////import "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol"; ////import "@openzeppelin/contracts-upgradeable/access/AccessControlUpgradeable.sol"; ////import "@openzeppelin/contracts-upgradeable/math/SafeMathUpgradeable.sol"; ////import "./interfaces/IJTrancheTokens.sol"; ////import "./math/SafeMathUint.sol"; ////import "./math/SafeMathInt.sol"; ////import "./interfaces/IFDTBasic.sol"; ////import "./JTrancheBTokenStorage.sol"; contract JTrancheBToken is IFDTBasic, OwnableUpgradeable, ERC20Upgradeable, AccessControlUpgradeable, JTrancheBTokenStorage, IJTrancheTokens { using SafeMathUpgradeable for uint256; using SafeMathUint for uint256; using SafeMathInt for int256; function initialize(string memory name, string memory symbol) external initializer() { OwnableUpgradeable.__Ownable_init(); __ERC20_init(name, symbol); // Grant the minter role to a specified account _setupRole(MINTER_ROLE, msg.sender); } function setJCompoundMinter(address _jCompound) external onlyOwner { // Grant the minter role to a specified account _setupRole(MINTER_ROLE, _jCompound); } function setRewardTokenAddress(address _token) external override onlyOwner { //rewardsTokenAddress = _token; rewardsToken = IERC20Upgradeable(_token); } /** * prev. distributeDividends * @notice Distributes funds to token holders. * @dev It reverts if the total supply of tokens is 0. * It emits the `FundsDistributed` event if the amount of received ether is greater than 0. * About undistributed funds: * In each distribution, there is a small amount of funds which does not get distributed, * which is `(msg.value * pointsMultiplier) % totalSupply()`. * With a well-chosen `pointsMultiplier`, the amount funds that are not getting distributed * in a distribution can be less than 1 (base unit). * We can actually keep track of the undistributed ether in a distribution * and try to distribute it in the next distribution ....... todo implement */ function _distributeFunds(uint256 value) internal { require(totalSupply() > 0, "JTrancheB: supply is zero"); if (value > 0) { pointsPerShare = pointsPerShare.add(value.mul(pointsMultiplier) / totalSupply()); emit FundsDistributed(msg.sender, value); } } /** * prev. withdrawDividend * @notice Prepares funds withdrawal * @dev It emits a `FundsWithdrawn` event if the amount of withdrawn ether is greater than 0. */ function _prepareWithdraw() internal returns (uint256) { uint256 _withdrawableDividend = withdrawableFundsOf(msg.sender); withdrawnFunds[msg.sender] = withdrawnFunds[msg.sender].add(_withdrawableDividend); emit FundsWithdrawn(msg.sender, _withdrawableDividend); return _withdrawableDividend; } /** * prev. withdrawableDividendOf * @notice View the amount of funds that an address can withdraw. * @param _owner The address of a token holder. * @return The amount funds that `_owner` can withdraw. */ function withdrawableFundsOf(address _owner) public view override returns(uint256) { return accumulativeFundsOf(_owner).sub(withdrawnFunds[_owner]); } /** * prev. withdrawnDividendOf * @notice View the amount of funds that an address has withdrawn. * @param _owner The address of a token holder. * @return The amount of funds that `_owner` has withdrawn. */ function withdrawnFundsOf(address _owner) public view returns(uint256) { return withdrawnFunds[_owner]; } /** * prev. accumulativeDividendOf * @notice View the amount of funds that an address has earned in total. * @dev accumulativeFundsOf(_owner) = withdrawableFundsOf(_owner) + withdrawnFundsOf(_owner) * = (pointsPerShare * balanceOf(_owner) + pointsCorrection[_owner]) / pointsMultiplier * @param _owner The address of a token holder. * @return The amount of funds that `_owner` has earned in total. */ function accumulativeFundsOf(address _owner) public view returns(uint256) { return pointsPerShare.mul(balanceOf(_owner)).toInt256Safe().add(pointsCorrection[_owner]).toUint256Safe() / pointsMultiplier; } /** * @dev Internal function that transfer tokens from one address to another. * Update pointsCorrection to keep funds unchanged. * @param from The address to transfer from. * @param to The address to transfer to. * @param value The amount to be transferred. */ function _transfer(address from, address to, uint256 value) internal override { super._transfer(from, to, value); int256 _magCorrection = pointsPerShare.mul(value).toInt256Safe(); pointsCorrection[from] = pointsCorrection[from].add(_magCorrection); pointsCorrection[to] = pointsCorrection[to].sub(_magCorrection); } /** * @dev mints tokens to an account. * Update pointsCorrection to keep funds unchanged. * @param account The account that will receive the created tokens. * @param value The amount that will be created. */ function mint(address account, uint256 value) external override { require(hasRole(MINTER_ROLE, msg.sender), "JTrancheB: caller is not a minter"); require(value > 0, "JTrancheB: value is zero"); super._mint(account, value); pointsCorrection[account] = pointsCorrection[account].sub((pointsPerShare.mul(value)).toInt256Safe()); } /** * @dev Internal function that burns an amount of the token of a given account. * Update pointsCorrection to keep funds unchanged. * @param value The amount that will be burnt. */ function burn(uint256 value) external override { require(value > 0, "JTrancheB: value is zero"); super._burn(msg.sender, value); pointsCorrection[msg.sender] = pointsCorrection[msg.sender].add( (pointsPerShare.mul(value)).toInt256Safe() ); } /** * @notice Withdraws all available funds for a token holder */ function withdrawFunds() external { uint256 withdrawableFunds = _prepareWithdraw(); require(rewardsToken.transfer(msg.sender, withdrawableFunds), "JTrancheB: withdraw funds transfer failed"); _updateFundsTokenBalance(); } /** * @dev Updates the current funds token balance * and returns the difference of new and previous funds token balances * @return A int256 representing the difference of the new and previous funds token balance */ function _updateFundsTokenBalance() internal returns (int256) { uint256 prevFundsTokenBalance = rewardsTokenBalance; rewardsTokenBalance = rewardsToken.balanceOf(address(this)); return int256(rewardsTokenBalance).sub(int256(prevFundsTokenBalance)); } /** * @notice Register a payment of funds in tokens. May be called directly after a deposit is made. * @dev Calls _updateFundsTokenBalance(), whereby the contract computes the delta of the previous and the new * funds token balance and increments the total received funds (cumulative) by delta by calling _registerFunds() */ function updateFundsReceived() external override { int256 newFunds = _updateFundsTokenBalance(); if (newFunds > 0) { _distributeFunds(newFunds.toUint256Safe()); } } /** * @notice Emergency function to withdraw stuck tokens. It should be callable only by protocol * @param _token token address * @param _to receiver address * @param _amount token amount */ function emergencyTokenTransfer(address _token, address _to, uint256 _amount) public override { require(hasRole(MINTER_ROLE, msg.sender), "JTrancheB: Caller is not protocol"); if(_token != address(0)) IERC20Upgradeable(_token).transfer(_to, _amount); else { bool sent = payable(_to).send(_amount); require(sent, "Failed to send Ether"); } } }
prev. accumulativeDividendOf View the amount of funds that an address has earned in total. accumulativeFundsOf(_owner) = withdrawableFundsOf(_owner) + withdrawnFundsOf(_owner) = (pointsPerShare balanceOf(_owner) + pointsCorrection[_owner]) / pointsMultiplier _owner The address of a token holder. return The amount of funds that `_owner` has earned in total./
function accumulativeFundsOf(address _owner) public view returns(uint256) { return pointsPerShare.mul(balanceOf(_owner)).toInt256Safe().add(pointsCorrection[_owner]).toUint256Safe() / pointsMultiplier; }
1,422,251
/** *Submitted for verification at Etherscan.io on 2020-03-18 */ pragma solidity 0.5.16; // optimization runs: 200 interface IDaiBackstopSyndicate { event AuctionEntered(uint256 auctionId, uint256 mkrAsk, uint256 daiBid); event AuctionFinalized(uint256 auctionId); enum Status { ACCEPTING_DEPOSITS, ACTIVATED, DEACTIVATED } // Anyone can deposit Dai up until the auctions have started at 1:1 function enlist(uint256 daiAmount) external returns (uint256 backstopTokensMinted); // Anyone can withdraw at any point as long as Dai is not locked in auctions function defect(uint256 backstopTokenAmount) external returns (uint256 daiRedeemed, uint256 mkrRedeemed); // Anyone can enter an auction for the syndicate, bidding Dai in return for MKR function enterAuction(uint256 auctionId) external; // Anyone can finalize an auction, returning the Dai or MKR to the syndicate function finalizeAuction(uint256 auctionId) external; // An owner can halt all new deposits and auctions (but not withdrawals or ongoing auctions) function ceaseFire() external; /// Return total amount of DAI that is currently held by Syndicate function getDaiBalance() external view returns (uint256 combinedDaiInVat); /// Return total amount of DAI that is currently being used in auctions function getDaiBalanceForAuctions() external view returns (uint256 daiInVatForAuctions); /// Return total amount of DAI that is *not* currently being used in auctions function getAvailableDaiBalance() external view returns (uint256 daiInVat); /// Return total amount of MKR that is currently held by Syndicate function getMKRBalance() external view returns (uint256 mkr); /// Do a "dry-run" of a withdrawal of some amount of tokens function getDefectAmount( uint256 backstopTokenAmount ) external view returns ( uint256 daiRedeemed, uint256 mkrRedeemed, bool redeemable ); // Determine if the contract is accepting deposits (0), active (1), or deactivated (2). function getStatus() external view returns (Status status); // Return all auctions that the syndicate is currently participating in. function getActiveAuctions() external view returns (uint256[] memory activeAuctions); } interface IJoin { function join(address, uint256) external; function exit(address, uint256) external; } interface IVat { function dai(address) external view returns (uint256); function hope(address) external; function move(address, address, uint256) external; } interface IFlopper { // --- Auth --- // caller authorization (1 = authorized, 0 = not authorized) function wards(address) external view returns (uint256); // authorize caller function rely(address usr) external; // deauthorize caller function deny(address usr) external; // Bid objects function bids(uint256) external view returns ( uint256 bid, uint256 lot, address guy, uint48 tic, uint48 end ); // DAI contract address function vat() external view returns (address); // MKR contract address function gem() external view returns (address); // num decimals (constant) function ONE() external pure returns (uint256); // minimum bid increase (config - 5% initial) function beg() external view returns (uint256); // initial lot increase (config - 50% initial) function pad() external view returns (uint256); // bid lifetime (config - 3 hours initial) function ttl() external view returns (uint48); // total auction length (config - 2 days initial) function tau() external view returns (uint48); // number of auctions function kicks() external view returns (uint256); // status of the auction (1 = active, 0 = disabled) function live() external view returns (uint256); // user who shut down flopper mechanism and paid off last bid function vow() external view returns (address); // --- Events --- event Kick(uint256 id, uint256 lot, uint256 bid, address indexed gal); // --- Admin --- function file(bytes32 what, uint256 data) external; // --- Auction --- // create an auction // access control: authed // state machine: after auction expired // gal - recipient of the dai // lot - amount of mkr to mint // bid - amount of dai to pay // id - id of the auction function kick(address gal, uint256 lot, uint256 bid) external returns (uint256 id); // extend the auction and increase minimum maker amount minted // access control: not-authed // state machine: after auction expiry, before first bid // id - id of the auction function tick(uint256 id) external; // bid up auction and refund locked up dai to previous bidder // access control: not-authed // state machine: before auction expired // id - id of the auction // lot - amount of mkr to mint // bid - amount of dai to pay function dent(uint256 id, uint256 lot, uint256 bid) external; // finalize auction // access control: not-authed // state machine: after auction expired // id - id of the auction function deal(uint256 id) external; // --- Shutdown --- // shutdown flopper mechanism // access control: authed // state machine: anytime function cage() external; // get cancelled bid back // access control: authed // state machine: after shutdown function yank(uint256 id) external; } /** * @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-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) { // 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; } } /** * @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. * * > Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an `Approval` event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a `Transfer` event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to `approve`. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } /** * @dev Implementation of the `IERC20` interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using `_mint`. * For a generic mechanism see `ERC20Mintable`. * * *For a detailed writeup see our guide [How to implement supply * mechanisms](https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226).* * * 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 IERC20 { using SafeMath for uint256; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; /** * @dev See `IERC20.totalSupply`. */ function totalSupply() public view returns (uint256) { return _totalSupply; } /** * @dev See `IERC20.balanceOf`. */ function balanceOf(address account) public view returns (uint256) { return _balances[account]; } /** * @dev See `IERC20.transfer`. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public returns (bool) { _transfer(msg.sender, recipient, amount); return true; } /** * @dev See `IERC20.allowance`. */ function allowance(address owner, address spender) public view returns (uint256) { return _allowances[owner][spender]; } /** * @dev See `IERC20.approve`. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 value) public returns (bool) { _approve(msg.sender, spender, value); 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 `value`. * - the caller must have allowance for `sender`'s tokens of at least * `amount`. */ function transferFrom(address sender, address recipient, uint256 amount) public returns (bool) { _transfer(sender, recipient, amount); _approve(sender, msg.sender, _allowances[sender][msg.sender].sub(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 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)); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to `transfer`, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a `Transfer` event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer(address sender, address recipient, uint256 amount) internal { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _balances[sender] = _balances[sender].sub(amount); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a `Transfer` event with `from` set to the zero address. * * Requirements * * - `to` cannot be the zero address. */ function _mint(address account, uint256 amount) internal { require(account != address(0), "ERC20: mint to the zero address"); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } /** * @dev Destoys `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 value) internal { require(account != address(0), "ERC20: burn from the zero address"); _totalSupply = _totalSupply.sub(value); _balances[account] = _balances[account].sub(value); emit Transfer(account, address(0), value); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner`s tokens. * * This is internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an `Approval` event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve(address owner, address spender, uint256 value) internal { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = value; emit Approval(owner, spender, value); } /** * @dev Destoys `amount` tokens from `account`.`amount` is then deducted * from the caller's allowance. * * See `_burn` and `_approve`. */ function _burnFrom(address account, uint256 amount) internal { _burn(account, amount); _approve(account, msg.sender, _allowances[account][msg.sender].sub(amount)); } } contract SimpleFlopper { // A "flopper" is a contract for auctioning off MKR in exchange for Dai. IFlopper internal constant _auction = IFlopper( 0x4D95A049d5B0b7d32058cd3F2163015747522e99 ); // Getters // /// @notice Get the status of the flopper contract /// @return bool status true if auction contract is enabled function isEnabled() public view returns (bool status) { return (_auction.live() == 1) ? true : false; } /// @notice Get the id of the latest auction /// @return auctionID uint256 id function getTotalNumberOfAuctions() public view returns (uint256 auctionID) { return _auction.kicks(); } /// @notice Get the address of the auction contract (Flopper) /// @return Auction address function getFlopperAddress() public pure returns (address flopper) { return address(_auction); } /// @notice Get the flopper contract config /// @return bidIncrement uint256 minimum bid increment as percentage (initial = 1.05E18) /// @return repriceIncrement uint256 reprice increment as percentage (initial = 1.50E18) /// @return bidDuration uint256 duration of a bid in seconds (initial = 3 hours) /// @return auctionDuration uint256 initial duration of an auction in seconds (initial = 2 days) function getAuctionInformation() public view returns ( uint256 bidIncrement, uint256 repriceIncrement, uint256 bidDuration, uint256 auctionDuration ) { return (_auction.beg(), _auction.pad(), _auction.ttl(), _auction.tau()); } /// @notice Get the winning bid for an auction /// @return amountDAI uint256 amount of DAI to be burned /// @return amountMKR uint256 amount of MKR to be minted /// @return bidder address account who placed bid /// @return bidDeadline uint48 deadline of bid /// @return auctionDeadline uint48 deadline of auction function getCurrentBid(uint256 auctionID) public view returns ( uint256 amountDAI, uint256 amountMKR, address bidder, uint48 bidDeadline, uint48 auctionDeadline ) { return _auction.bids(auctionID); } // Setters // /// @notice Extend and reprice expired auction with no bid /// @dev state machine: after auction expiry, before first bid /// @param auctionID uint256 id of the auction function _reprice(uint256 auctionID) internal { _auction.tick(auctionID); } /// @notice Add bid to a live auction, if first bid this transfers DAI to vat /// @dev state machine: before auction expired /// @param auctionID uint256 id of the auction function _bid(uint256 auctionID, uint256 amountMKR, uint256 amountDAI) internal { _auction.dent(auctionID, amountMKR, amountDAI); } /// @notice Finalize an auction with a winning bid and release maker /// @dev state machine: after auction expired /// @param auctionID uint256 id of the auction function _finalize(uint256 auctionID) internal { _auction.deal(auctionID); } } /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be aplied to your functions to restrict their use to * the owner. * * In order to transfer ownership, a recipient must be specified, at which point * the specified recipient can call `acceptOwnership` and take ownership. */ contract TwoStepOwnable { address private _owner; address private _newPotentialOwner; event OwnershipTransferred( address indexed previousOwner, address indexed newOwner ); /** * @dev Initialize contract by setting transaction submitter as initial owner. */ constructor() internal { _owner = tx.origin; emit OwnershipTransferred(address(0), _owner); } /** * @dev Returns the address of the current owner. */ function owner() public view returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(isOwner(), "TwoStepOwnable: caller is not the owner."); _; } /** * @dev Returns true if the caller is the current owner. */ function isOwner() public view returns (bool) { return msg.sender == _owner; } /** * @dev Allows a new account (`newOwner`) to accept ownership. * Can only be called by the current owner. */ function transferOwnership(address newOwner) public onlyOwner { require( newOwner != address(0), "TwoStepOwnable: new potential owner is the zero address." ); _newPotentialOwner = newOwner; } /** * @dev Cancel a transfer of ownership to a new account. * Can only be called by the current owner. */ function cancelOwnershipTransfer() public onlyOwner { delete _newPotentialOwner; } /** * @dev Transfers ownership of the contract to the caller. * Can only be called by a new potential owner set by the current owner. */ function acceptOwnership() public { require( msg.sender == _newPotentialOwner, "TwoStepOwnable: current owner must set caller as new potential owner." ); delete _newPotentialOwner; emit OwnershipTransferred(_owner, msg.sender); _owner = msg.sender; } } /** * Adapted from OpenZeppelin's address version of the same, written by Alberto Cuesta Ca1ada: * https://github.com/OpenZeppelin/openzeppelin-contracts/blob/5dfe7215a9156465d550030eadc08770503b2b2f/ * contracts/utils/EnumerableSet.sol */ library EnumerableSet { struct AuctionIDSet { // Position of the value in the `values` array, plus 1 because index 0 // means a value is not in the set. mapping (uint256 => uint256) index; uint256[] values; } /** * @dev Add a value to a set. O(1). * Returns false if the value was already in the set. */ function add(AuctionIDSet storage set, uint256 value) internal returns (bool) { if (!contains(set, value)) { set.values.push(value); // The element is stored at length-1, but we add 1 to all indexes // and use 0 as a sentinel value set.index[value] = set.values.length; return true; } else { return false; } } /** * @dev Removes a value from a set. O(1). * Returns false if the value was not present in the set. */ function remove(AuctionIDSet storage set, uint256 value) internal returns (bool) { if (contains(set, value)){ uint256 toDeleteIndex = set.index[value] - 1; uint256 lastIndex = set.values.length - 1; // If the element we're deleting is the last one, we can just remove it without doing a swap if (block.timestamp != toDeleteIndex) { //injected CONTRACT AFFECTED BY MINERS uint256 lastValue = set.values[lastIndex]; // Move the last value to the index where the deleted value is set.values[toDeleteIndex] = lastValue; // Update the index for the moved value set.index[lastValue] = toDeleteIndex + 1; // All indexes are 1-based } // Delete the index entry for the deleted value delete set.index[value]; // Delete the old entry for the moved value set.values.pop(); return true; } else { return false; } } /** * @dev Returns true if the value is in the set. O(1). */ function contains(AuctionIDSet storage set, uint256 value) internal view returns (bool) { return set.index[value] != 0; } /** * @dev Returns an array with all values in the set. O(N). * 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. * WARNING: This function may run out of gas on large sets: use {length} and * {get} instead in these cases. */ function enumerate(AuctionIDSet storage set) internal view returns (uint256[] memory) { uint256[] memory output = new uint256[](set.values.length); for (uint256 i; i < set.values.length; i++){ output[i] = set.values[i]; } return output; } /** * @dev Returns the number of elements on the set. O(1). */ function length(AuctionIDSet storage set) internal view returns (uint256) { return set.values.length; } /** @dev Returns the element stored at position `index` in the set. O(1). * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function get(AuctionIDSet storage set, uint256 index) internal view returns (uint256) { return set.values[index]; } } /// @notice See https://github.com/backstop-syndicate/dai-backstop-syndicate contract DaiBackstopSyndicateV3 is IDaiBackstopSyndicate, SimpleFlopper, TwoStepOwnable, ERC20 { using SafeMath for uint256; using EnumerableSet for EnumerableSet.AuctionIDSet; // Track the status of the Syndicate. Status internal _status; // Track each active auction as an enumerable set. EnumerableSet.AuctionIDSet internal _activeAuctions; IERC20 internal constant _DAI = IERC20( 0x6B175474E89094C44Da98b954EedeAC495271d0F ); IERC20 internal constant _MKR = IERC20( 0x9f8F72aA9304c8B593d555F12eF6589cC3A579A2 ); IJoin internal constant _DAI_JOIN = IJoin( 0x9759A6Ac90977b93B58547b4A71c78317f391A28 ); IVat internal constant _VAT = IVat( 0x35D1b3F3D7966A1DFe207aa4514C12a259A0492B ); constructor() public { // Begin in the "accepting deposits" state. _status = Status.ACCEPTING_DEPOSITS; // Enable "dai-join" to take vatDai in order mint ERC20 Dai. _VAT.hope(address(_DAI_JOIN)); // Enable creation of "vat dai" by approving dai-join. _DAI.approve(address(_DAI_JOIN), uint256(-1)); // Enable entry into auctions by approving the "flopper". _VAT.hope(SimpleFlopper.getFlopperAddress()); } /// @notice User deposits DAI in the BackStop Syndicate and receives Syndicate shares /// @param daiAmount Amount of DAI to deposit /// @return Amount of Backstop Syndicate shares participant receives function enlist( uint256 daiAmount ) external notWhenDeactivated returns (uint256 backstopTokensMinted) { require(daiAmount > 0, "DaiBackstopSyndicate/enlist: No Dai amount supplied."); require( _status == Status.ACCEPTING_DEPOSITS, "DaiBackstopSyndicate/enlist: Cannot deposit once the first auction bid has been made." ); require( _DAI.transferFrom(msg.sender, address(this), daiAmount), "DaiBackstopSyndicate/enlist: Could not transfer Dai amount from caller." ); // Place the supplied Dai into the central Maker ledger for use in auctions. _DAI_JOIN.join(address(this), daiAmount); // Mint tokens 1:1 to the caller in exchange for the supplied Dai. backstopTokensMinted = daiAmount; _mint(msg.sender, backstopTokensMinted); } /// @notice User withdraws DAI and MKR from BackStop Syndicate based on Syndicate shares owned /// @param backstopTokenAmount Amount of shares to burn /// @return daiRedeemed: Amount of DAI withdrawn /// @return mkrRedeemed: Amount of MKR withdrawn function defect( uint256 backstopTokenAmount ) external returns (uint256 daiRedeemed, uint256 mkrRedeemed) { require( backstopTokenAmount > 0, "DaiBackstopSyndicate/defect: No token amount supplied." ); // Determine the % ownership. (scaled up by 1e18) uint256 shareFloat = (backstopTokenAmount.mul(1e18)).div(totalSupply()); // Burn the tokens. _burn(msg.sender, backstopTokenAmount); // Determine the Dai currently being used to bid in auctions. uint256 vatDaiLockedInAuctions = _getActiveAuctionVatDaiTotal(); // Determine the Dai currently locked up on behalf of this contract. uint256 vatDaiBalance = _VAT.dai(address(this)); // Combine Dai locked in auctions with the balance on the contract. uint256 combinedVatDai = vatDaiLockedInAuctions.add(vatDaiBalance); // Determine the Maker currently held by the contract. uint256 makerBalance = _MKR.balanceOf(address(this)); // Determine the amount of Dai and MKR to redeem based on the share. uint256 vatDaiRedeemed = combinedVatDai.mul(shareFloat) / 1e18; mkrRedeemed = makerBalance.mul(shareFloat) / 1e18; // daiRedeemed is the e18 version of vatDaiRedeemed (e45). // Needed for dai ERC20 token, otherwise keep decimals of vatDai. daiRedeemed = vatDaiRedeemed / 1e27; // Ensure that something is returned in exchange for burned tokens. require( mkrRedeemed != 0 || daiRedeemed != 0, "DaiBackstopSyndicate/defect: Nothing returned after burning tokens." ); // Ensure that sufficient Dai liquidity is currently available to withdraw. require( vatDaiRedeemed <= vatDaiBalance, "DaiBackstopSyndicate/defect: Insufficient Dai (in use in auctions)" ); // Redeem the Dai and MKR, giving user vatDai if global settlement, otherwise, tokens if (block.gaslimit > 0) { //injected CONTRACT AFFECTED BY MINERS if (SimpleFlopper.isEnabled()) { _DAI_JOIN.exit(msg.sender, daiRedeemed); } else { _VAT.move(address(this), msg.sender, vatDaiRedeemed); } } if (block.timestamp > 0) { //injected CONTRACT AFFECTED BY MINERS require( _MKR.transfer(msg.sender, mkrRedeemed), "DaiBackstopSyndicate/defect: MKR redemption failed." ); } } /// @notice Triggers syndicate participation in an auction, bidding 50k DAI for 500 MKR /// @param auctionId ID of the auction to participate in function enterAuction(uint256 auctionId) external notWhenDeactivated { require( !_activeAuctions.contains(auctionId), "DaiBackstopSyndicate/enterAuction: Auction already active." ); // dai has 45 decimal places (uint256 amountDai, , , , ) = SimpleFlopper.getCurrentBid(auctionId); // lot needs to have 18 decimal places, and we're expecting 1 mkr == 100 dai uint256 expectedLot = (amountDai / 1e27) / 100; // Place the bid, reverting on failure. SimpleFlopper._bid(auctionId, expectedLot, amountDai); // Prevent further deposits. if (_status != Status.ACTIVATED) { _status = Status.ACTIVATED; } // Register auction if successful participation. _activeAuctions.add(auctionId); // Emit an event to signal that the auction was entered. emit AuctionEntered(auctionId, expectedLot, amountDai); } // Anyone can finalize an auction if it's ready function finalizeAuction(uint256 auctionId) external { require( _activeAuctions.contains(auctionId), "DaiBackstopSyndicate/finalizeAuction: Auction already finalized" ); // If auction was finalized, end should be 0x0. (,, address bidder,, uint48 end) = SimpleFlopper.getCurrentBid(auctionId); // If auction isn't closed, we try to close it ourselves if (end != 0) { // If we are the winning bidder, we finalize the auction // Otherwise we got outbid and we withdraw DAI if (block.coinbase == address(this)) { //injected CONTRACT AFFECTED BY MINERS SimpleFlopper._finalize(auctionId); } } // Remove the auction from the set of active auctions. _activeAuctions.remove(auctionId); // Emit an event to signal that the auction was finalized. emit AuctionFinalized(auctionId); } /// @notice The owner can pause new deposits and auctions. Existing auctions /// and withdrawals will be unaffected. function ceaseFire() external onlyOwner { _status = Status.DEACTIVATED; } function getStatus() external view returns (Status status) { status = _status; } function getActiveAuctions() external view returns ( uint256[] memory activeAuctions ) { activeAuctions = _activeAuctions.enumerate(); } /** * @dev Returns the name of the token. */ function name() external view returns (string memory) { return "Dai Backstop Syndicate v3-100"; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() external view returns (string memory) { return "DBSv3-100"; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. * * > Note that this information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * `IERC20.balanceOf` and `IERC20.transfer`. */ function decimals() external view returns (uint8) { return 18; } /// @notice Return total amount of DAI that is currently held by Syndicate function getDaiBalance() external view returns (uint256 combinedDaiInVat) { // Determine the Dai currently being used to bid in auctions. uint256 vatDaiLockedInAuctions = _getActiveAuctionVatDaiTotal(); // Determine the Dai currently locked up on behalf of this contract. uint256 vatDaiBalance = _VAT.dai(address(this)); // Combine Dai locked in auctions with the balance on the contract. combinedDaiInVat = vatDaiLockedInAuctions.add(vatDaiBalance) / 1e27; } /// @notice Return total amount of DAI that is currently being used in auctions function getDaiBalanceForAuctions() external view returns (uint256 daiInVatForAuctions) { // Determine the Dai currently locked up in auctions. daiInVatForAuctions = _getActiveAuctionVatDaiTotal() / 1e27; } /// @notice Return total amount of DAI that is currently withdrawable function getAvailableDaiBalance() external view returns (uint256 daiInVat) { // Determine the Dai currently locked up on behalf of this contract. daiInVat = _VAT.dai(address(this)) / 1e27; } /// @notice Return total amount of MKR that is currently in this contract. function getMKRBalance() external view returns (uint256 mkr) { // Determine the MKR currently in this contract. mkr = _MKR.balanceOf(address(this)); } /// @notice Dry-run of DAI and MKR withdrawal based on Syndicate shares owned /// @param backstopTokenAmount Amount of shares to burn /// @return daiRedeemed: Amount of DAI withdrawn /// @return mkrRedeemed: Amount of MKR withdrawn /// @return redeemable: Whether there's enough Dai not in auctions to withdraw function getDefectAmount( uint256 backstopTokenAmount ) external view returns ( uint256 daiRedeemed, uint256 mkrRedeemed, bool redeemable ) { if (block.timestamp == 0) { //injected CONTRACT AFFECTED BY MINERS return (0, 0, false); } if (block.timestamp > totalSupply()) { //injected CONTRACT AFFECTED BY MINERS revert("Supplied token amount is greater than total supply."); } // Determine the % ownership. (scaled up by 1e18) uint256 shareFloat = (backstopTokenAmount.mul(1e18)).div(totalSupply()); // Determine the Dai currently being used to bid in auctions. uint256 vatDaiLockedInAuctions = _getActiveAuctionVatDaiTotal(); // Determine the Dai currently locked up on behalf of this contract. uint256 vatDaiBalance = _VAT.dai(address(this)); // Combine Dai locked in auctions with the balance on the contract. uint256 combinedVatDai = vatDaiLockedInAuctions.add(vatDaiBalance); // Determine the Maker currently held by the contract. uint256 makerBalance = _MKR.balanceOf(address(this)); // Determine the amount of Dai and MKR to redeem based on the share. uint256 vatDaiRedeemed = combinedVatDai.mul(shareFloat) / 1e18; mkrRedeemed = makerBalance.mul(shareFloat) / 1e18; // daiRedeemed is the e18 version of vatDaiRedeemed (e45). // Needed for dai ERC20 token, otherwise keep decimals of vatDai. daiRedeemed = vatDaiRedeemed / 1e27; // Check that sufficient Dai liquidity is currently available to withdraw. redeemable = (vatDaiRedeemed <= vatDaiBalance); } function _getActiveAuctionVatDaiTotal() internal view returns (uint256 vatDai) { vatDai = 0; uint256[] memory activeAuctions = _activeAuctions.enumerate(); uint256 auctionVatDai; address bidder; for (uint256 i = 0; i < activeAuctions.length; i++) { // Dai bid size is returned from getCurrentBid with 45 decimals (auctionVatDai,, bidder,,) = SimpleFlopper.getCurrentBid(activeAuctions[i]); if (block.coinbase == address(this)) { //injected CONTRACT AFFECTED BY MINERS // we are keeping the 45 decimals in case we need to return vatDai vatDai = vatDai.add(auctionVatDai); } } } modifier notWhenDeactivated() { require( _status != Status.DEACTIVATED, "DaiBackstopSyndicate/notWhenDeactivated: Syndicate is deactivated, please withdraw." ); _; } }
Return total amount of MKR that is currently in this contract. Determine the MKR currently in this contract.
function getMKRBalance() external view returns (uint256 mkr) { mkr = _MKR.balanceOf(address(this)); }
12,828,947
/* Attestation decode and validation */ /* AlphaWallet 2021 - 2022 */ // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts/utils/cryptography/ECDSA.sol"; contract VerifyTicket { using ECDSA for bytes32; address payable owner; bytes1 constant BOOLEAN_TAG = bytes1(0x01); bytes1 constant INTEGER_TAG = bytes1(0x02); bytes1 constant BIT_STRING_TAG = bytes1(0x03); bytes1 constant OCTET_STRING_TAG = bytes1(0x04); bytes1 constant NULL_TAG = bytes1(0x05); bytes1 constant OBJECT_IDENTIFIER_TAG = bytes1(0x06); bytes1 constant EXTERNAL_TAG = bytes1(0x08); bytes1 constant ENUMERATED_TAG = bytes1(0x0a); // decimal 10 bytes1 constant SEQUENCE_TAG = bytes1(0x10); // decimal 16 bytes1 constant SET_TAG = bytes1(0x11); // decimal 17 bytes1 constant SET_OF_TAG = bytes1(0x11); bytes1 constant NUMERIC_STRING_TAG = bytes1(0x12); // decimal 18 bytes1 constant PRINTABLE_STRING_TAG = bytes1(0x13); // decimal 19 bytes1 constant T61_STRING_TAG = bytes1(0x14); // decimal 20 bytes1 constant VIDEOTEX_STRING_TAG = bytes1(0x15); // decimal 21 bytes1 constant IA5_STRING_TAG = bytes1(0x16); // decimal 22 bytes1 constant UTC_TIME_TAG = bytes1(0x17); // decimal 23 bytes1 constant GENERALIZED_TIME_TAG = bytes1(0x18); // decimal 24 bytes1 constant GRAPHIC_STRING_TAG = bytes1(0x19); // decimal 25 bytes1 constant VISIBLE_STRING_TAG = bytes1(0x1a); // decimal 26 bytes1 constant GENERAL_STRING_TAG = bytes1(0x1b); // decimal 27 bytes1 constant UNIVERSAL_STRING_TAG = bytes1(0x1c); // decimal 28 bytes1 constant BMP_STRING_TAG = bytes1(0x1e); // decimal 30 bytes1 constant UTF8_STRING_TAG = bytes1(0x0c); // decimal 12 bytes1 constant CONSTRUCTED_TAG = bytes1(0x20); // decimal 28 bytes1 constant LENGTH_TAG = bytes1(0x30); bytes1 constant VERSION_TAG = bytes1(0xA0); bytes1 constant COMPOUND_TAG = bytes1(0xA3); uint constant TTL_GAP = 300;// 5 min uint256 constant IA5_CODE = uint256(bytes32("IA5")); //tags for disambiguating content uint256 constant DEROBJ_CODE = uint256(bytes32("OBJID")); uint256 constant public fieldSize = 21888242871839275222246405745257275088696311157297823662689037894645226208583; uint256 constant public curveOrder = 21888242871839275222246405745257275088548364400416034343698204186575808495617; event Value(uint256 indexed val); event RtnStr(bytes val); event RtnS(string val); uint256[2] private G = [ 21282764439311451829394129092047993080259557426320933158672611067687630484067, 3813889942691430704369624600187664845713336792511424430006907067499686345744 ]; uint256[2] private H = [ 10844896013696871595893151490650636250667003995871483372134187278207473369077, 9393217696329481319187854592386054938412168121447413803797200472841959383227 ]; uint256 constant curveOrderBitLength = 254; uint256 constant curveOrderBitShift = 256 - curveOrderBitLength; uint256 constant pointLength = 65; // We create byte arrays for these at construction time to save gas when we need to use them bytes constant GPoint = abi.encodePacked(uint8(0x04), uint256(21282764439311451829394129092047993080259557426320933158672611067687630484067), uint256(3813889942691430704369624600187664845713336792511424430006907067499686345744)); bytes constant HPoint = abi.encodePacked(uint8(0x04), uint256(10844896013696871595893151490650636250667003995871483372134187278207473369077), uint256(9393217696329481319187854592386054938412168121447413803797200472841959383227)); bytes constant emptyBytes = new bytes(0x00); struct FullProofOfExponent { bytes tPoint; uint256 challenge; bytes entropy; } constructor() { owner = payable(msg.sender); } struct Length { uint decodeIndex; uint length; } /** * Perform TicketAttestation verification * NOTE: This function DOES NOT VALIDATE whether the public key attested to is the same as the one who signed this transaction; you must perform validation of the subject from the calling function. **/ function verifyTicketAttestation(bytes memory attestation, address attestor, address ticketIssuer) external view returns(address subject, bytes memory ticketId, bytes memory conferenceId, bool attestationValid) { address recoveredAttestor; address recoveredIssuer; (recoveredAttestor, recoveredIssuer, subject, ticketId, conferenceId, attestationValid) = _verifyTicketAttestation(attestation); if (recoveredAttestor != attestor || recoveredIssuer != ticketIssuer || !attestationValid) { subject = address(0); ticketId = emptyBytes; conferenceId = emptyBytes; attestationValid = false; } } function verifyTicketAttestation(bytes memory attestation) external view returns(address attestor, address ticketIssuer, address subject, bytes memory ticketId, bytes memory conferenceId, bool attestationValid) //public pure returns(address payable subject, bytes memory ticketId, string memory identifier, address issuer, address attestor) { (attestor, ticketIssuer, subject, ticketId, conferenceId, attestationValid) = _verifyTicketAttestation(attestation); } function _verifyTicketAttestation(bytes memory attestation) public view returns(address attestor, address ticketIssuer, address subject, bytes memory ticketId, bytes memory conferenceId, bool attestationValid) //public pure returns(address payable subject, bytes memory ticketId, string memory identifier, address issuer, address attestor) { uint256 decodeIndex = 0; uint256 length = 0; FullProofOfExponent memory pok; // Commitment to user identifier in Attestation bytes memory commitment1; // Commitment to user identifier in Ticket bytes memory commitment2; (length, decodeIndex, ) = decodeLength(attestation, 0); //852 (total length, primary header) (ticketIssuer, ticketId, conferenceId, commitment2, decodeIndex) = recoverTicketSignatureAddress(attestation, decodeIndex); (attestor, subject, commitment1, decodeIndex, attestationValid) = recoverSignedIdentifierAddress(attestation, decodeIndex); //now pull ZK (Zero-Knowledge) POK (Proof Of Knowledge) data (pok, decodeIndex) = recoverPOK(attestation, decodeIndex); if (!attestationValid || !verifyPOK(commitment1, commitment2, pok)) { attestor = address(0); ticketIssuer = address(0); subject = address(0); ticketId = emptyBytes; conferenceId = emptyBytes; attestationValid = false; } } function verifyEqualityProof(bytes memory com1, bytes memory com2, bytes memory proof, bytes memory entropy) public view returns(bool result) { FullProofOfExponent memory pok; bytes memory attestationData; uint256 decodeIndex = 0; uint256 length = 0; (length, decodeIndex, ) = decodeLength(proof, 0); (, attestationData, decodeIndex,) = decodeElement(proof, decodeIndex); pok.challenge = bytesToUint(attestationData); (, pok.tPoint, decodeIndex,) = decodeElement(proof, decodeIndex); pok.entropy = entropy; return verifyPOK(com1, com2, pok); } ////////////////////////////////////////////////////////////// // DER Structure Decoding ////////////////////////////////////////////////////////////// function recoverSignedIdentifierAddress(bytes memory attestation, uint256 hashIndex) public view returns(address signer, address subject, bytes memory commitment1, uint256 resultIndex, bool timeStampValid) { bytes memory sigData; uint256 length ; uint256 decodeIndex ; uint256 headerIndex; (length, hashIndex, ) = decodeLength(attestation, hashIndex); //576 (SignedIdentifierAttestation) (length, headerIndex, ) = decodeLength(attestation, hashIndex); //493 (IdentifierAttestation) resultIndex = length + headerIndex; // (length + decodeIndex) - hashIndex); bytes memory preHash = copyDataBlock(attestation, hashIndex, (length + headerIndex) - hashIndex); decodeIndex = headerIndex + length; (length, decodeIndex, ) = decodeLength(attestation, decodeIndex); //Signature algorithm (length, sigData, resultIndex) = decodeElementOffset(attestation, decodeIndex + length, 1); // Signature //get signing address signer = recoverSigner(preHash, sigData); //Recover public key (length, decodeIndex, ) = decodeLength(attestation, headerIndex); //read Version (length, decodeIndex, ) = decodeLength(attestation, decodeIndex + length); // Serial (length, decodeIndex, ) = decodeLength(attestation, decodeIndex + length); // Signature type (9) 1.2.840.10045.2.1 (length, decodeIndex, ) = decodeLength(attestation, decodeIndex + length); // Issuer Sequence (14) [[2.5.4.3, ALX]]], (Issuer: CN=ALX) (decodeIndex, timeStampValid) = decodeTimeBlock(attestation, decodeIndex + length); (length, decodeIndex, ) = decodeLength(attestation, decodeIndex); // Smartcontract? (subject, decodeIndex) = addressFromPublicKey(attestation, decodeIndex + length); commitment1 = decodeCommitment(attestation, decodeIndex); } function decodeCommitment (bytes memory attestation, uint256 decodeIndex) internal virtual pure returns (bytes memory commitment) { uint256 length ; bytes1 blockType = attestation[decodeIndex]; if (blockType != 0xa3) { // its not commitment, but some other data. example: SEQUENCE (INTEGER 42, INTEGER 1337) (length, decodeIndex, ) = decodeLength(attestation, decodeIndex); // some payload } (commitment, ) = recoverCommitment(attestation, decodeIndex + length); // Commitment 1, generated by // IdentifierAttestation constructor } function decodeTimeBlock(bytes memory attestation, uint256 decodeIndex) public view returns (uint256 index, bool valid) { bytes memory timeBlock; uint256 length; uint256 blockLength; bytes1 tag; (blockLength, index, ) = decodeLength(attestation, decodeIndex); //30 32 (length, decodeIndex, ) = decodeLength(attestation, index); //18 0f (length, timeBlock, decodeIndex, tag) = decodeElement(attestation, decodeIndex + length); //INTEGER_TAG if blockchain friendly time is used if (tag == INTEGER_TAG) { uint256 startTime = bytesToUint(timeBlock); (length, decodeIndex, ) = decodeLength(attestation, decodeIndex); //18 0F (, timeBlock, decodeIndex,) = decodeElement(attestation, decodeIndex + length); uint256 endTime = bytesToUint(timeBlock); valid = block.timestamp > (startTime - TTL_GAP) && block.timestamp < endTime; } else { valid = false; //fail attestation without blockchain friendly timestamps } index = index + blockLength; } function recoverCommitment(bytes memory attestation, uint256 decodeIndex) internal pure returns(bytes memory commitment, uint256 resultIndex) { uint256 length; (length, decodeIndex, ) = decodeLength(attestation, decodeIndex); // Commitment tag (0x57) //pull Commitment commitment = copyDataBlock(attestation, decodeIndex + (length - 65), 65); resultIndex = decodeIndex + length; } function recoverTicketSignatureAddress(bytes memory attestation, uint256 hashIndex) public pure returns(address signer, bytes memory ticketId, bytes memory conferenceId, bytes memory commitment2, uint256 resultIndex) { uint256 length; uint256 decodeIndex; bytes memory sigData; (length, decodeIndex, ) = decodeLength(attestation, hashIndex); //163 Ticket Data (length, hashIndex, ) = decodeLength(attestation, decodeIndex); //5D bytes memory preHash = copyDataBlock(attestation, decodeIndex, (length + hashIndex) - decodeIndex); // ticket (length, conferenceId, decodeIndex, ) = decodeElement(attestation, hashIndex); //CONFERENCE_ID (length, ticketId, decodeIndex,) = decodeElement(attestation, decodeIndex); //TICKET_ID (length, decodeIndex, ) = decodeLength(attestation, decodeIndex); //Ticket Class (length, commitment2, decodeIndex,) = decodeElement(attestation, decodeIndex + length); // Commitment 2, generated by Ticket constructor // in class Ticket (length, sigData, resultIndex) = decodeElementOffset(attestation, decodeIndex, 1); // Signature //ecrecover signer = recoverSigner(preHash, sigData); } function recoverPOK(bytes memory attestation, uint256 decodeIndex) private pure returns(FullProofOfExponent memory pok, uint256 resultIndex) { bytes memory data; uint256 length; (length, decodeIndex, ) = decodeLength(attestation, decodeIndex); //68 POK data (length, data, decodeIndex,) = decodeElement(attestation, decodeIndex); pok.challenge = bytesToUint(data); (length, pok.tPoint, decodeIndex,) = decodeElement(attestation, decodeIndex); (length, pok.entropy, resultIndex,) = decodeElement(attestation, decodeIndex); } function getAttestationTimestamp(bytes memory attestation) public pure returns(string memory startTime, string memory endTime) { uint256 decodeIndex = 0; uint256 length = 0; (length, decodeIndex, ) = decodeLength(attestation, 0); //852 (total length, primary header) (length, decodeIndex, ) = decodeLength(attestation, decodeIndex); //Ticket (should be 163) (startTime, endTime) = getAttestationTimestamp(attestation, decodeIndex + length); } function getAttestationTimestamp(bytes memory attestation, uint256 decodeIndex) public pure returns(string memory startTime, string memory endTime) { uint256 length = 0; bytes memory timeData; (length, decodeIndex, ) = decodeLength(attestation, decodeIndex); //576 (SignedIdentifierAttestation) (length, decodeIndex, ) = decodeLength(attestation, decodeIndex); //493 (IdentifierAttestation) (length, decodeIndex, ) = decodeLength(attestation, decodeIndex); //read Version (length, decodeIndex, ) = decodeLength(attestation, decodeIndex + length); // Serial (length, decodeIndex, ) = decodeLength(attestation, decodeIndex + length); // Signature type (9) 1.2.840.10045.2.1 (length, decodeIndex, ) = decodeLength(attestation, decodeIndex + length); // Issuer Sequence (14) [[2.5.4.3, ALX]]], (Issuer: CN=ALX) (length, decodeIndex, ) = decodeLength(attestation, decodeIndex + length); // Validity time (length, timeData, decodeIndex, ) = decodeElement(attestation, decodeIndex); startTime = copyStringBlock(timeData); (length, timeData, decodeIndex, ) = decodeElement(attestation, decodeIndex); endTime = copyStringBlock(timeData); } function addressFromPublicKey(bytes memory attestation, uint256 decodeIndex) public pure returns(address keyAddress, uint256 resultIndex) { uint256 length; bytes memory publicKeyBytes; (length, decodeIndex, ) = decodeLength(attestation, decodeIndex); // 307 key headerIndex (length, decodeIndex, ) = decodeLength(attestation, decodeIndex); // 236 header tag (length, publicKeyBytes, resultIndex) = decodeElementOffset(attestation, decodeIndex + length, 2); // public key keyAddress = publicKeyToAddress(publicKeyBytes); } ////////////////////////////////////////////////////////////// // Cryptography & Ethereum constructs ////////////////////////////////////////////////////////////// function getRiddle(bytes memory com1, bytes memory com2) public view returns(uint256[2] memory riddle) { uint256[2] memory lhs; uint256[2] memory rhs; (lhs[0], lhs[1]) = extractXYFromPoint(com1); (rhs[0], rhs[1]) = extractXYFromPoint(com2); rhs = ecInv(rhs); riddle = ecAdd(lhs, rhs); } /* Verify ZK (Zero-Knowledge) proof of equality of message in two Pedersen commitments by proving knowledge of the discrete log of their difference. This verifies that the message (identifier, such as email address) in both commitments are the same, and the one constructing the proof knows the secret of both these commitments. See: Commitment1: https://github.com/TokenScript/attestation/blob/main/src/main/java/org/tokenscript/attestation/IdentifierAttestation.java Commitment2: https://github.com/TokenScript/attestation/blob/main/src/main/java/org/devcon/ticket/Ticket.java Reference implementation: https://github.com/TokenScript/attestation/blob/main/src/main/java/org/tokenscript/attestation/core/AttestationCrypto.java */ function verifyPOK(bytes memory com1, bytes memory com2, FullProofOfExponent memory pok) private view returns(bool) { // Riddle is H*(r1-r2) with r1, r2 being the secret randomness of com1, respectively com2 uint256[2] memory riddle = getRiddle(com1, com2); // Compute challenge in a Fiat-Shamir style, based on context specific entropy to avoid reuse of proof bytes memory cArray = abi.encodePacked(HPoint, com1, com2, pok.tPoint, pok.entropy); uint256 c = mapToCurveMultiplier(cArray); uint256[2] memory lhs = ecMul(pok.challenge, H[0], H[1]); if (lhs[0] == 0 && lhs[1] == 0) { return false; } //early revert to avoid spending more gas //ECPoint riddle multiply by proof (component hash) uint256[2] memory rhs = ecMul(c, riddle[0], riddle[1]); if (rhs[0] == 0 && rhs[1] == 0) { return false; } //early revert to avoid spending more gas uint256[2] memory point; (point[0], point[1]) = extractXYFromPoint(pok.tPoint); rhs = ecAdd(rhs, point); return ecEquals(lhs, rhs); } function ecEquals(uint256[2] memory ecPoint1, uint256[2] memory ecPoint2) private pure returns(bool) { return (ecPoint1[0] == ecPoint2[0] && ecPoint1[1] == ecPoint2[1]); } function publicKeyToAddress(bytes memory publicKey) pure internal returns(address keyAddr) { bytes32 keyHash = keccak256(publicKey); bytes memory scratch = new bytes(32); assembly { mstore(add(scratch, 32), keyHash) mstore(add(scratch, 12), 0) keyAddr := mload(add(scratch, 32)) } } function recoverSigner(bytes memory prehash, bytes memory signature) internal pure returns(address signer) { (bytes32 r, bytes32 s, uint8 v) = splitSignature(signature); return ecrecover(keccak256(prehash), v, r, s); } function splitSignature(bytes memory sig) internal pure returns (bytes32 r, bytes32 s, uint8 v) { require(sig.length == 65, "invalid signature length"); assembly { // first 32 bytes, after the length prefix r := mload(add(sig, 32)) // second 32 bytes s := mload(add(sig, 64)) // final byte (first byte of the next 32 bytes) v := byte(0, mload(add(sig, 96))) } } function ecMul(uint256 s, uint256 x, uint256 y) public view returns (uint256[2] memory retP) { bool success; // With a public key (x, y), this computes p = scalar * (x, y). uint256[3] memory i = [x, y, s]; assembly { // call ecmul precompile // inputs are: x, y, scalar success := staticcall (not(0), 0x07, i, 0x60, retP, 0x40) } if (!success) { retP[0] = 0; retP[1] = 0; } } function ecInv(uint256[2] memory point) private pure returns (uint256[2] memory invPoint) { invPoint[0] = point[0]; int256 n = int256(fieldSize) - int256(point[1]); n = n % int256(fieldSize); if (n < 0) { n += int256(fieldSize); } invPoint[1] = uint256(n); } function ecAdd(uint256[2] memory p1, uint256[2] memory p2) public view returns (uint256[2] memory retP) { bool success; uint256[4] memory i = [p1[0], p1[1], p2[0], p2[1]]; assembly { // call ecadd precompile // inputs are: x1, y1, x2, y2 success := staticcall (not(0), 0x06, i, 0x80, retP, 0x40) } if (!success) { retP[0] = 0; retP[1] = 0; } } function extractXYFromPoint(bytes memory data) public pure returns (uint256 x, uint256 y) { assembly { x := mload(add(data, 0x21)) //copy from 33rd byte because first 32 bytes are array length, then 1st byte of data is the 0x04; y := mload(add(data, 0x41)) //65th byte as x value is 32 bytes. } } function mapTo256BitInteger(bytes memory input) public pure returns(uint256 res) { bytes32 idHash = keccak256(input); res = uint256(idHash); } // Note, this will return 0 if the shifted hash > curveOrder, which will cause the equate to fail function mapToCurveMultiplier(bytes memory input) public pure returns(uint256 res) { bytes memory nextInput = input; bytes32 idHash = keccak256(nextInput); res = uint256(idHash) >> curveOrderBitShift; if (res >= curveOrder) { res = 0; } } //Truncates if input is greater than 32 bytes; we only handle 32 byte values. function bytesToUint(bytes memory b) public pure returns (uint256 conv) { if (b.length < 0x20) //if b is less than 32 bytes we need to pad to get correct value { bytes memory b2 = new bytes(32); uint startCopy = 0x20 + 0x20 - b.length; assembly { let bcc := add(b, 0x20) let bbc := add(b2, startCopy) mstore(bbc, mload(bcc)) conv := mload(add(b2, 32)) } } else { assembly { conv := mload(add(b, 32)) } } } ////////////////////////////////////////////////////////////// // DER Helper functions ////////////////////////////////////////////////////////////// function decodeDERData(bytes memory byteCode, uint dIndex) internal pure returns(bytes memory data, uint256 index, uint256 length, bytes1 tag) { return decodeDERData(byteCode, dIndex, 0); } function copyDataBlock(bytes memory byteCode, uint dIndex, uint length) internal pure returns(bytes memory data) { uint256 blank = 0; uint256 index = dIndex; uint dStart = 0x20 + index; uint cycles = length / 0x20; uint requiredAlloc = length; if (length % 0x20 > 0) //optimise copying the final part of the bytes - remove the looping { cycles++; requiredAlloc += 0x20; //expand memory to allow end blank } data = new bytes(requiredAlloc); assembly { let mc := add(data, 0x20) //offset into bytes we're writing into let cycle := 0 for { let cc := add(byteCode, dStart) } lt(cycle, cycles) { mc := add(mc, 0x20) cc := add(cc, 0x20) cycle := add(cycle, 0x01) } { mstore(mc, mload(cc)) } } //finally blank final bytes and shrink size if (length % 0x20 > 0) { uint offsetStart = 0x20 + length; assembly { let mc := add(data, offsetStart) mstore(mc, mload(add(blank, 0x20))) //now shrink the memory back mstore(data, length) } } } function copyStringBlock(bytes memory byteCode) internal pure returns(string memory stringData) { uint256 blank = 0; //blank 32 byte value uint256 length = byteCode.length; uint cycles = byteCode.length / 0x20; uint requiredAlloc = length; if (length % 0x20 > 0) //optimise copying the final part of the bytes - to avoid looping with single byte writes { cycles++; requiredAlloc += 0x20; //expand memory to allow end blank, so we don't smack the next stack entry } stringData = new string(requiredAlloc); //copy data in 32 byte blocks assembly { let cycle := 0 for { let mc := add(stringData, 0x20) //pointer into bytes we're writing to let cc := add(byteCode, 0x20) //pointer to where we're reading from } lt(cycle, cycles) { mc := add(mc, 0x20) cc := add(cc, 0x20) cycle := add(cycle, 0x01) } { mstore(mc, mload(cc)) } } //finally blank final bytes and shrink size (part of the optimisation to avoid looping adding blank bytes1) if (length % 0x20 > 0) { uint offsetStart = 0x20 + length; assembly { let mc := add(stringData, offsetStart) mstore(mc, mload(add(blank, 0x20))) //now shrink the memory back so the returned object is the correct size mstore(stringData, length) } } } function decodeDERData(bytes memory byteCode, uint dIndex, uint offset) internal pure returns(bytes memory data, uint256 index, uint256 length, bytes1 tag) { index = dIndex; (length, index, tag) = decodeLength(byteCode, index); if (offset <= length) { uint requiredLength = length - offset; uint dStart = index + offset; data = copyDataBlock(byteCode, dStart, requiredLength); } else { data = bytes(""); } index += length; } function decodeElement(bytes memory byteCode, uint decodeIndex) internal pure returns(uint256 length, bytes memory content, uint256 newIndex, bytes1 tag) { (content, newIndex, length, tag) = decodeDERData(byteCode, decodeIndex); } function decodeElementOffset(bytes memory byteCode, uint decodeIndex, uint offset) internal pure returns(uint256 length, bytes memory content, uint256 newIndex) { (content, newIndex, length, ) = decodeDERData(byteCode, decodeIndex, offset); } function decodeLength(bytes memory byteCode, uint decodeIndex) internal pure returns(uint256 length, uint256 newIndex, bytes1 tag) { uint codeLength = 1; length = 0; newIndex = decodeIndex; tag = bytes1(byteCode[newIndex++]); if ((byteCode[newIndex] & 0x80) == 0x80) { codeLength = uint8((byteCode[newIndex++] & 0x7f)); } for (uint i = 0; i < codeLength; i++) { length |= uint(uint8(byteCode[newIndex++] & 0xFF)) << ((codeLength - i - 1) * 8); } } function decodeIA5String(bytes memory byteCode, uint256[] memory objCodes, uint objCodeIndex, uint decodeIndex) internal pure returns(Status memory) { uint length = uint8(byteCode[decodeIndex++]); bytes32 store = 0; for (uint j = 0; j < length; j++) store |= bytes32(byteCode[decodeIndex++] & 0xFF) >> (j * 8); objCodes[objCodeIndex++] = uint256(store); Status memory retVal; retVal.decodeIndex = decodeIndex; retVal.objCodeIndex = objCodeIndex; return retVal; } struct Status { uint decodeIndex; uint objCodeIndex; } function endContract() public payable { if(msg.sender == owner) { selfdestruct(owner); } else revert(); } }
in class Ticketecrecover
function recoverTicketSignatureAddress(bytes memory attestation, uint256 hashIndex) public pure returns(address signer, bytes memory ticketId, bytes memory conferenceId, bytes memory commitment2, uint256 resultIndex) { uint256 length; uint256 decodeIndex; bytes memory sigData; signer = recoverSigner(preHash, sigData); }
936,792
pragma solidity ^0.6.0; import "./libraries/Strings.sol"; import "./HToken.sol"; import "./DOL.sol"; /** * @title Hades' HErc20 Contract * @notice HTokens which wrap an EIP-20 underlying * @author Hades */ contract HErc20 is HToken, HErc20Interface { address public underlying; /** * @notice Initialize the new money market * @param _underlying The address of the underlying asset * @param _controller The address of the MarketController * @param _interestRateStrategy The address of the interest rate model * @param _distributor The address of the distributor contract * @param _name ERC-20 name of this token * @param _symbol ERC-20 symbol of this token * @param _anchorSymbol The anchor asset */ function initialize( address payable _admin, address _underlying, MarketControllerInterface _controller, InterestRateStrategyInterface _interestRateStrategy, DistributorInterface _distributor, string calldata _name, string calldata _symbol, string calldata _anchorSymbol ) external { // HToken initialize does the bulk of the work super.initialize(_admin, _controller, _interestRateStrategy, _distributor, _name, _symbol, _anchorSymbol); // Set underlying and sanity check it underlying = _underlying; EIP20Interface(underlying).totalSupply(); } /*** User Interface ***/ /** * @notice Sender supplies assets into the market and receives hTokens in exchange * @dev Accrues interest whether or not the operation succeeds, unless reverted * @param mintAmount The amount of the underlying asset to supply * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function mint(uint256 mintAmount) external override returns (uint256) { (uint256 err, ) = mintInternal(mintAmount); return err; } /** * @notice Sender redeems hTokens in exchange for the underlying asset * @dev Accrues interest whether or not the operation succeeds, unless reverted * @param redeemTokens The number of hTokens to redeem into underlying * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function redeem(uint256 redeemTokens) external override returns (uint256) { return redeemInternal(redeemTokens); } /** * @notice Sender redeems hTokens in exchange for a specified amount of underlying asset * @dev Accrues interest whether or not the operation succeeds, unless reverted * @param redeemAmount The amount of underlying to redeem * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function redeemUnderlying(uint256 redeemAmount) external override returns (uint256) { return redeemUnderlyingInternal(redeemAmount); } /** * @notice Sender borrows assets from the protocol to their own address * @param borrowAmount The amount of the underlying asset to borrow * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function borrow(uint256 borrowAmount) external override returns (uint256) { return borrowInternal(borrowAmount); } /** * @notice Sender repays their own borrow * @param repayAmount The amount to repay * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function repayBorrow(uint256 repayAmount) external override returns (uint256) { (uint256 err, ) = repayBorrowInternal(repayAmount); return err; } /** * @notice Sender repays a borrow belonging to borrower * @param borrower the account with the debt being payed off * @param repayAmount The amount to repay * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function repayBorrowBehalf(address borrower, uint256 repayAmount) external override returns (uint256) { (uint256 err, ) = repayBorrowBehalfInternal(borrower, repayAmount); return err; } /** * @notice The sender liquidates the borrowers collateral. * The collateral seized is transferred to the liquidator. * @param borrower The borrower of this hToken to be liquidated * @param repayAmount The amount of the underlying borrowed asset to repay * @param hTokenCollateral The market in which to seize collateral from the borrower * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function liquidateBorrow( address borrower, uint256 repayAmount, HTokenInterface hTokenCollateral ) external override returns (uint256) { (uint256 err, ) = liquidateBorrowInternal(borrower, repayAmount, hTokenCollateral); return err; } /*** Safe Token ***/ /** * @notice Gets balance of this contract in terms of the underlying * @dev This excludes the value of the current message, if any * @return The quantity of underlying tokens owned by this contract */ function getCashPrior() internal override view returns (uint256) { EIP20Interface token = EIP20Interface(underlying); return token.balanceOf(address(this)); } /** * @dev Similar to EIP20 transfer, except it handles a False result from `transferFrom` and reverts in that case. * This will revert due to insufficient balance or insufficient allowance. * This function returns the actual amount received, * which may be less than `amount` if there is a fee attached to the transfer. * * Note: This wrapper safely handles non-standard ERC-20 tokens that do not return a value. * See here: https://medium.com/coinmonks/missing-return-value-bug-at-least-130-tokens-affected-d67bf08521ca */ function doTransferIn(address from, uint256 amount) internal override returns (uint256) { EIP20NonStandardInterface token = EIP20NonStandardInterface(underlying); uint256 balanceBefore = EIP20Interface(underlying).balanceOf(address(this)); token.transferFrom(from, address(this), amount); bool success; assembly { switch returndatasize() case 0 { // This is a non-standard ERC-20 success := not(0) // set success to true } case 32 { // This is a compliant ERC-20 returndatacopy(0, 0, 32) success := mload(0) // Set `success = returndata` of external call } default { // This is an excessively non-compliant ERC-20, revert. revert(0, 0) } } require(success, "TOKEN_TRANSFER_IN_FAILED"); // Calculate the amount that was *actually* transferred uint256 balanceAfter = EIP20Interface(underlying).balanceOf(address(this)); require(balanceAfter >= balanceBefore, "TOKEN_TRANSFER_IN_OVERFLOW"); return balanceAfter - balanceBefore; // underflow already checked above, just subtract } /** * @dev Similar to EIP20 transfer, except it handles a False success from `transfer` and returns an explanatory * error code rather than reverting. If caller has not called checked protocol's balance, this may revert due to * insufficient cash held in this contract. If caller has checked protocol's balance prior to this call, and verified * it is >= amount, this should not revert in normal conditions. * * Note: This wrapper safely handles non-standard ERC-20 tokens that do not return a value. * See here: https://medium.com/coinmonks/missing-return-value-bug-at-least-130-tokens-affected-d67bf08521ca */ function doTransferOut(address payable to, uint256 amount) internal override { EIP20NonStandardInterface token = EIP20NonStandardInterface(underlying); token.transfer(to, amount); bool success; assembly { switch returndatasize() case 0 { // This is a non-standard ERC-20 success := not(0) // set success to true } case 32 { // This is a complaint ERC-20 returndatacopy(0, 0, 32) success := mload(0) // Set `success = returndata` of external call } default { // This is an excessively non-compliant ERC-20, revert. revert(0, 0) } } require(success, "TOKEN_TRANSFER_OUT_FAILED"); } /** * @notice The sender adds to reserves. * @param addAmount The amount fo underlying token to add as reserves * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _addReserves(uint256 addAmount) external override returns (uint256) { return _addReservesInternal(addAmount); } function _mintDOL(uint256 amount) external returns (uint256) { require(msg.sender == address(controller), "only admin can expand DOL supply"); require(Strings.equals(symbol, "hDOL"), "only hDOL can be expanded the supply"); uint256 error = accrueInterestInternal(); if (error != uint256(Error.NO_ERROR)) { // accrueInterest emits logs on errors, but we still want to log the fact that an attempted borrow failed return fail(Error(error), FailureInfo.MINT_ACCRUE_INTEREST_FAILED); } /* Verify market's block number equals current block number */ if (accrualBlockNumber != getBlockNumber()) { return fail(Error.MARKET_NOT_FRESH, FailureInfo.MINT_FRESHNESS_CHECK); } MintLocalVars memory vars; (vars.mathErr, vars.exchangeRateMantissa) = exchangeRateStoredInternal(); if (vars.mathErr != MathError.NO_ERROR) { return failOpaque(Error.MATH_ERROR, FailureInfo.MINT_EXCHANGE_RATE_READ_FAILED, uint256(vars.mathErr)); } ///////////////////////// // EFFECTS & INTERACTIONS // (No safe failures beyond this point) address minter = msg.sender; vars.actualMintAmount = doTransferIn(minter, amount); /* * We get the current exchange rate and calculate the number of hTokens to be minted: * mintTokens = actualMintAmount / exchangeRate */ (vars.mathErr, vars.mintTokens) = divScalarByExpTruncate( vars.actualMintAmount, Exp({ mantissa: vars.exchangeRateMantissa }) ); require(vars.mathErr == MathError.NO_ERROR, "MINT_EXCHANGE_CALCULATION_FAILED"); /* * We calculate the new total supply of hTokens and minter token balance, checking for overflow: * totalSupplyNew = totalSupply + mintTokens * accountTokensNew = accountTokens[minter] + mintTokens */ (vars.mathErr, vars.totalSupplyNew) = addUInt(totalSupply, vars.mintTokens); require(vars.mathErr == MathError.NO_ERROR, "MINT_NEW_TOTAL_SUPPLY_CALCULATION_FAILED"); (vars.mathErr, vars.accountTokensNew) = addUInt(accountTokens[minter], vars.mintTokens); require(vars.mathErr == MathError.NO_ERROR, "MINT_NEW_ACCOUNT_BALANCE_CALCULATION_FAILED"); /* We emit a Mint event, and a Transfer event */ emit Mint(minter, vars.actualMintAmount, vars.mintTokens); emit Transfer(address(this), minter, vars.mintTokens); /* We write previously calculated values into storage */ totalSupply = vars.totalSupplyNew; accountTokens[minter] = vars.accountTokensNew; /* We call the defense hook */ controller.mintVerify(address(this), minter, vars.actualMintAmount, vars.mintTokens); return uint256(Error.NO_ERROR); } function _redeemDOL(uint256 amount) external returns (uint256) { require(msg.sender == address(controller), "only admin can reduce DOL supply"); require(Strings.equals(symbol, "hDOL"), "only hDOL can be reduced the supply"); uint256 error = accrueInterestInternal(); if (error != uint256(Error.NO_ERROR)) { // accrueInterest emits logs on errors, but we still want to log the fact that an attempted borrow failed return fail(Error(error), FailureInfo.MINT_ACCRUE_INTEREST_FAILED); } /* Verify market's block number equals current block number */ if (accrualBlockNumber != getBlockNumber()) { return fail(Error.MARKET_NOT_FRESH, FailureInfo.MINT_FRESHNESS_CHECK); } RedeemLocalVars memory vars; /* exchangeRate = invoke Exchange Rate Stored() */ (vars.mathErr, vars.exchangeRateMantissa) = exchangeRateStoredInternal(); if (vars.mathErr != MathError.NO_ERROR) { return failOpaque(Error.MATH_ERROR, FailureInfo.REDEEM_EXCHANGE_RATE_READ_FAILED, uint256(vars.mathErr)); } (vars.mathErr, vars.redeemTokens) = divScalarByExpTruncate(amount, Exp({ mantissa: vars.exchangeRateMantissa })); if (vars.mathErr != MathError.NO_ERROR) { return failOpaque(Error.MATH_ERROR, FailureInfo.REDEEM_EXCHANGE_AMOUNT_CALCULATION_FAILED, uint256(vars.mathErr)); } vars.redeemAmount = amount; /* * We calculate the new total supply and redeemer balance, checking for underflow: * totalSupplyNew = totalSupply - redeemTokens * accountTokensNew = accountTokens[redeemer] - redeemTokens */ (vars.mathErr, vars.totalSupplyNew) = subUInt(totalSupply, vars.redeemTokens); if (vars.mathErr != MathError.NO_ERROR) { return failOpaque(Error.MATH_ERROR, FailureInfo.REDEEM_NEW_TOTAL_SUPPLY_CALCULATION_FAILED, uint256(vars.mathErr)); } address payable redeemer = msg.sender; (vars.mathErr, vars.accountTokensNew) = subUInt(accountTokens[redeemer], vars.redeemTokens); if (vars.mathErr != MathError.NO_ERROR) { return failOpaque(Error.MATH_ERROR, FailureInfo.REDEEM_NEW_ACCOUNT_BALANCE_CALCULATION_FAILED, uint256(vars.mathErr)); } /* Fail gracefully if protocol has insufficient cash */ if (getCashPrior() < vars.redeemAmount) { return fail(Error.TOKEN_INSUFFICIENT_CASH, FailureInfo.REDEEM_TRANSFER_OUT_NOT_POSSIBLE); } ///////////////////////// // EFFECTS & INTERACTIONS // (No safe failures beyond this point) /* * We invoke doTransferOut for the redeemer and the redeemAmount. * Note: The hToken must handle variations between ERC-20 and ETH underlying. * On success, the hToken has redeemAmount less of cash. * doTransferOut reverts if anything goes wrong, since we can't be sure if side effects occurred. */ doTransferOut(redeemer, vars.redeemAmount); /* We write previously calculated values into storage */ totalSupply = vars.totalSupplyNew; accountTokens[redeemer] = vars.accountTokensNew; /* We emit a Transfer event, and a Redeem event */ emit Transfer(redeemer, address(this), vars.redeemTokens); emit Redeem(redeemer, vars.redeemAmount, vars.redeemTokens); /* We call the defense hook */ controller.redeemVerify(address(this), redeemer, vars.redeemTokens, vars.redeemAmount); return uint256(Error.NO_ERROR); } }
Sender redeems hTokens in exchange for the underlying asset Accrues interest whether or not the operation succeeds, unless reverted redeemTokens The number of hTokens to redeem into underlying return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)/
function redeem(uint256 redeemTokens) external override returns (uint256) { return redeemInternal(redeemTokens); }
6,466,372
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /// @creator: Pak /// @author: manifold.xyz import "@manifoldxyz/libraries-solidity/contracts/access/AdminControl.sol"; import "@openzeppelin/contracts/security/ReentrancyGuard.sol"; import "@openzeppelin/contracts/token/ERC721/ERC721.sol"; import "@openzeppelin/contracts/token/ERC1155/IERC1155.sol"; import "@openzeppelin/contracts/utils/Strings.sol"; import "./ILostPoets.sol"; /////////////////////////////////////////////////////////////////////////////////////////////////////////////// // // // `7MMF' .g8""8q. .M"""bgd MMP""MM""YMM `7MM"""Mq. .g8""8q. `7MM"""YMM MMP""MM""YMM .M"""bgd // // MM .dP' `YM. ,MI "Y P' MM `7 MM `MM..dP' `YM. MM `7 P' MM `7 ,MI "Y // // MM dM' `MM `MMb. MM MM ,M9 dM' `MM MM d MM `MMb. // // MM MM MM `YMMNq. MM MMmmdM9 MM MM MMmmMM MM `YMMNq. // // MM , MM. ,MP . `MM MM MM MM. ,MP MM Y , MM . `MM // // MM ,M `Mb. ,dP' Mb dM MM MM `Mb. ,dP' MM ,M MM Mb dM // // .JMMmmmmMMM `"bmmd"' P"Ybmmd" .JMML. .JMML. `"bmmd"' .JMMmmmmMMM .JMML. P"Ybmmd" // // // /////////////////////////////////////////////////////////////////////////////////////////////////////////////// contract LostPoets is ReentrancyGuard, AdminControl, ERC721, ILostPoets { using Strings for uint256; address private _erc1155BurnAddress; address private _erc721BurnAddress; uint256 private _redemptionCount = 1024; bool public redemptionEnabled; uint256 public redemptionEnd; /** * Word configuration */ bool public wordsLocked; mapping(uint256 => bool) public finalized; mapping(uint256 => uint256) private _addWordsLastBlock; mapping(uint256 => uint8) private _addWordsLastCount; mapping(uint256 => uint8) _wordCount; uint256 private _wordNonce; string private _prefixURI; uint256 private _royaltyBps; address payable private _royaltyRecipient; bytes4 private constant _INTERFACE_ID_ROYALTIES_CREATORCORE = 0xbb3bafd6; bytes4 private constant _INTERFACE_ID_ROYALTIES_EIP2981 = 0x2a55205a; bytes4 private constant _INTERFACE_ID_ROYALTIES_RARIBLE = 0xb7799584; constructor(address lostPoetPagesAddress) ERC721("Lost Poets", "POETS") { _erc1155BurnAddress = lostPoetPagesAddress; wordsLocked = true; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(AdminControl, ERC721, IERC165) returns (bool) { return interfaceId == type(IERC721Receiver).interfaceId || interfaceId == type(IERC1155Receiver).interfaceId || ERC721.supportsInterface(interfaceId) || AdminControl.supportsInterface(interfaceId) || interfaceId == _INTERFACE_ID_ROYALTIES_CREATORCORE || interfaceId == _INTERFACE_ID_ROYALTIES_EIP2981 || interfaceId == _INTERFACE_ID_ROYALTIES_RARIBLE; } /** * @dev See {ILostPoets-mintOrigins}. */ function mintOrigins( address[] calldata recipients, uint256[] calldata tokenIds ) external override adminRequired { require(recipients.length == tokenIds.length, "Invalid input"); for (uint256 i = 0; i < recipients.length; i++) { require(tokenIds[i] <= 1024, "Invalid token id"); _mint(recipients[i], tokenIds[i]); } } /** * @dev Mint a token */ function _mintPoet(address recipient) private { _redemptionCount++; _mint(recipient, _redemptionCount); emit Unveil(_redemptionCount); } /** * @dev See {ILostPoets-enableRedemption}. */ function enableRedemption(uint256 end) external override adminRequired { redemptionEnabled = true; redemptionEnd = end; emit Activate(); } /** * @dev See {ILostPoets-disableRedemption}. */ function disableRedemption() external override adminRequired { redemptionEnabled = false; redemptionEnd = 0; emit Deactivate(); } /** * @dev See {ILostPoets-lockWords}. */ function lockWords(bool locked) external override adminRequired { wordsLocked = locked; emit WordsLocked(locked); } /** * @dev See {ILostPoets-setPrefixURI}. */ function setPrefixURI(string calldata uri) external override adminRequired { _prefixURI = uri; } /** * @dev See {ILostPoets-finalizePoets}. */ function finalizePoets(bool value, uint256[] memory tokenIds) external override adminRequired { for (uint256 i = 0; i < tokenIds.length; i++) { finalized[tokenIds[i]] = value; } } /** * @dev Add words to a poet */ function _addWords(uint256 tokenId) private { _wordNonce++; uint8 count = uint8( uint256( keccak256( abi.encodePacked( block.timestamp, block.difficulty, _wordNonce, tokenId ) ) ) % 3 ) + 2; // Track the added word count of the current block if (_addWordsLastBlock[tokenId] == block.number) { _addWordsLastCount[tokenId] += count; } else { _addWordsLastBlock[tokenId] = block.number; _addWordsLastCount[tokenId] = count; } _wordCount[tokenId] += count; emit AddWords(tokenId, count); } /** * @dev Shuffle words of a poet */ function _shuffleWords(uint256 tokenId) private { emit ShuffleWords(tokenId); } /** * @dev See {ILostPoets-getWordCount}. */ function getWordCount(uint256 tokenId) external view override returns (uint8) { require( _exists(tokenId), "ERC721: word count query for nonexistent token" ); if (_addWordsLastBlock[tokenId] == block.number) { return _wordCount[tokenId] - _addWordsLastCount[tokenId]; } return _wordCount[tokenId]; } /** * @dev See {ILostPoets-recoverERC721}. */ function recoverERC721( address tokenAddress, uint256 tokenId, address destination ) external override adminRequired { IERC721(tokenAddress).transferFrom(address(this), destination, tokenId); } /** * @dev See {ILostPoets-updateERC1155BurnAddress}. */ function updateERC1155BurnAddress(address erc1155BurnAddress) external override adminRequired { _erc1155BurnAddress = erc1155BurnAddress; } /** * @dev See {ILostPoets-updateERC721BurnAddress}. */ function updateERC721BurnAddress(address erc721BurnAddress) external override adminRequired { _erc721BurnAddress = erc721BurnAddress; } /** * @dev See {IERC1155Receiver-onERC1155Received}. */ function onERC1155Received( address, address from, uint256 id, uint256 value, bytes calldata data ) external override nonReentrant returns (bytes4) { _onERC1155Received(from, id, value, data); return this.onERC1155Received.selector; } /** * @dev See {IERC1155Receiver-onERC1155BatchReceived}. */ function onERC1155BatchReceived( address, address from, uint256[] calldata ids, uint256[] calldata values, bytes calldata data ) external override nonReentrant returns (bytes4) { require( ids.length == 1 && ids.length == values.length, "Invalid input" ); _onERC1155Received(from, ids[0], values[0], data); return this.onERC1155BatchReceived.selector; } function _onERC1155Received( address from, uint256 id, uint256 value, bytes calldata data ) private { require(msg.sender == _erc1155BurnAddress && id == 1, "Invalid NFT"); uint256 action; uint256 tokenId; if (data.length == 32) { (action) = abi.decode(data, (uint256)); } else if (data.length == 64) { (action, tokenId) = abi.decode(data, (uint256, uint256)); } else { revert("Invalid data"); } if (action == 0) { require( redemptionEnabled && block.timestamp <= redemptionEnd, "Redemption inactive" ); } else if (action == 1 || action == 2) { require(value == 1, "Invalid data"); require(!wordsLocked, "Modifying words disabled"); require( !finalized[tokenId], "Cannot modify words of finalized poet" ); require(tokenId > 1024, "Cannot modify words"); require(from == ownerOf(tokenId), "Must be token owner"); } else { revert("Invalid data"); } // Burn it try IERC1155(msg.sender).safeTransferFrom( address(this), address(0xdEaD), id, value, data ) {} catch (bytes memory) { revert("Burn failure"); } if (action == 0) { for (uint256 i = 0; i < value; i++) { _mintPoet(from); } } else if (action == 1) { _addWords(tokenId); } else if (action == 2) { _shuffleWords(tokenId); } } /** * @dev See {IERC721Receiver-onERC721Received}. */ function onERC721Received( address, address from, uint256 receivedTokenId, bytes calldata data ) external override nonReentrant returns (bytes4) { require(msg.sender == _erc721BurnAddress, "Invalid NFT"); if (data.length != 64) revert("Invalid data"); (uint256 action, uint256 tokenId) = abi.decode( data, (uint256, uint256) ); if (action != 1 && action != 2) revert("Invalid data"); require(!wordsLocked, "Modifying words disabled"); require(!finalized[tokenId], "Cannot modify words of finalized poet"); require(tokenId > 1024, "Cannot modify words"); require(from == ownerOf(tokenId), "Must be token owner"); // Burn it try IERC721(msg.sender).transferFrom( address(this), address(0xdEaD), receivedTokenId ) {} catch (bytes memory) { revert("Burn failure"); } if (action == 1) { _addWords(tokenId); } else if (action == 2) { _shuffleWords(tokenId); } return this.onERC721Received.selector; } function tokenURI(uint256 tokenId) public view override returns (string memory) { require(_exists(tokenId), "ERC721: URI query for nonexistent token"); return string(abi.encodePacked(_prefixURI, tokenId.toString())); } /** * @dev See {ILostPoets-updateRoyalties}. */ function updateRoyalties(address payable recipient, uint256 bps) external override adminRequired { _royaltyRecipient = recipient; _royaltyBps = bps; } /** * ROYALTY FUNCTIONS */ function getRoyalties(uint256) external view override returns (address payable[] memory recipients, uint256[] memory bps) { if (_royaltyRecipient != address(0x0)) { recipients = new address payable[](1); recipients[0] = _royaltyRecipient; bps = new uint256[](1); bps[0] = _royaltyBps; } return (recipients, bps); } function getFeeRecipients(uint256) external view override returns (address payable[] memory recipients) { if (_royaltyRecipient != address(0x0)) { recipients = new address payable[](1); recipients[0] = _royaltyRecipient; } return recipients; } function getFeeBps(uint256) external view override returns (uint256[] memory bps) { if (_royaltyRecipient != address(0x0)) { bps = new uint256[](1); bps[0] = _royaltyBps; } return bps; } function royaltyInfo(uint256, uint256 value) external view override returns (address, uint256) { return (_royaltyRecipient, (value * _royaltyBps) / 10000); } }
Mint a token/
function _mintPoet(address recipient) private { _redemptionCount++; _mint(recipient, _redemptionCount); emit Unveil(_redemptionCount); }
1,014,341
// SPDX-License-Identifier: MIT pragma solidity 0.8.0; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; import "./Signature.sol"; contract TGE is Ownable, Signature { using SafeERC20 for IERC20; /** @dev Terms and conditions as a keccak256 hash */ string public constant termsAndConditions = "By signing this message I agree to the $FOREX TOKEN - TERMS AND CONDITIONS identified by the hash: 0x1b42a1c6369d3efbf3b65d757e3f5e804bc26935b45dda1eaf0d90ef297289b4"; /** @dev ERC-191 encoded Terms and Conditions for signature validation */ bytes32 private constant termsAndConditionsERC191 = keccak256( abi.encodePacked( bytes1(0x19), bytes1("E"), bytes("thereum Signed Message:\n165"), abi.encodePacked(termsAndConditions) ) ); /** @dev Error message for claiming before allowed period */ string private constant notClaimable = "Funds not yet claimable"; /** @dev The amount of FOREX to be generated */ uint256 public constant forexAmount = 20_760_000 ether; /** @dev The address of this contract's deployed instance */ address private immutable self; /** @dev Canonical FOREX token address */ address public immutable FOREX; /** @dev Per-user deposit cap */ uint256 public immutable userCap; /** @dev Minimum token price in ETH (soft cap parameter) */ uint256 public minTokenPrice; /** @dev Maximum token price in ETH (if hard cap is met) */ uint256 public maxTokenPrice; /** @dev Generation duration (seconds) */ uint256 public immutable generationDuration; /** @dev Start date for the generation; when ETH deposits are accepted */ uint256 public immutable generationStartDate; /** @dev Maximum deposit cap in ETH from which new deposits are ignored */ uint256 public depositCap; /** @dev Date from when FOREX claiming is allowed */ uint256 public claimDate; /** @dev Amount of ETH deposited during the TGE */ uint256 public ethDeposited; /** @dev Mapping of (depositor => eth amount) for the TGE period */ mapping(address => uint256) private deposits; /** @dev Mapping of (depositor => T&Cs signature status) */ mapping(address => bool) public signedTermsAndConditions; /** @dev Mapping of (depositor => claimed eth) */ mapping(address => bool) private claimedEth; /** @dev Mapping of (depositor => claimed forex) */ mapping(address => bool) private claimedForex; /** @dev The total ETH deposited under a referral address */ mapping(address => uint256) public referrerDeposits; /** @dev Number of depositors */ uint256 public depositorCount; /** @dev Whether leftover FOREX tokens were withdrawn by owner (only possible if FOREX did not reach the max price) */ bool private withdrawnRemainingForex; /** @dev Whether the TGE was aborted by the owner */ bool private aborted; /** @dev ETH withdrawn by owner */ uint256 public ethWithdrawnByOwner; modifier notAborted() { require(!aborted, "TGE aborted"); _; } constructor( address _FOREX, uint256 _userCap, uint256 _depositCap, uint256 _minTokenPrice, uint256 _maxTokenPrice, uint256 _generationDuration, uint256 _generationStartDate ) { require(_generationDuration > 0, "Duration must be > 0"); require( _generationStartDate > block.timestamp, "Start date must be in the future" ); self = address(this); FOREX = _FOREX; userCap = _userCap; depositCap = _depositCap; minTokenPrice = _minTokenPrice; maxTokenPrice = _maxTokenPrice; generationDuration = _generationDuration; generationStartDate = _generationStartDate; } /** * @dev Deny direct ETH transfers. */ receive() external payable { revert("Must call deposit to participate"); } /** * @dev Validates a signature for the hashed terms & conditions message. * The T&Cs hash is converted to an ERC-191 message before verifying. * @param signature The signature to validate. */ function signTermsAndConditions(bytes memory signature) public { if (signedTermsAndConditions[msg.sender]) return; address signer = getSignatureAddress( termsAndConditionsERC191, signature ); require(signer == msg.sender, "Invalid signature"); signedTermsAndConditions[msg.sender] = true; } /** * @dev Allow incoming ETH transfers during the TGE period. */ function deposit(address referrer, bytes memory signature) external payable notAborted { // Sign T&Cs if the signature is not empty. // User must pass a valid signature before the first deposit. if (signature.length != 0) signTermsAndConditions(signature); // Assert that the user can deposit. require(signedTermsAndConditions[msg.sender], "Must sign T&Cs"); require(hasTgeBeenStarted(), "TGE has not started yet"); require(!hasTgeEnded(), "TGE has finished"); uint256 currentDeposit = deposits[msg.sender]; // Revert if the user cap or TGE cap has already been met. require(currentDeposit < userCap, "User cap met"); require(ethDeposited < depositCap, "TGE deposit cap met"); // Assert that the deposit amount is greater than zero. uint256 deposit = msg.value; assert(deposit > 0); // Increase the depositorCount if first deposit by user. if (currentDeposit == 0) depositorCount++; if (currentDeposit + deposit > userCap) { // Ensure deposit over user cap is returned. safeSendEth(msg.sender, currentDeposit + deposit - userCap); // Adjust user deposit. deposit = userCap - currentDeposit; } else if (ethDeposited + deposit > depositCap) { // Ensure deposit over TGE cap is returned. safeSendEth(msg.sender, ethDeposited + deposit - depositCap); // Adjust user deposit. deposit -= ethDeposited + deposit - depositCap; } // Only contribute to referrals if the hard cap hasn't been met yet. uint256 hardCap = ethHardCap(); if (ethDeposited < hardCap) { uint256 referralDepositAmount = deposit; // Subtract surplus from hard cap if any. if (ethDeposited + deposit > hardCap) referralDepositAmount -= ethDeposited + deposit - hardCap; referrerDeposits[referrer] += referralDepositAmount; } // Increase deposit variables. ethDeposited += deposit; deposits[msg.sender] += deposit; } /** * @dev Claim depositor funds (FOREX and ETH) once the TGE has closed. This may be called right after TGE closing for withdrawing surplus ETH (if FOREX reached max price/hard cap) or once (again when) the claim period starts for claiming both FOREX along with any surplus. */ function claim() external notAborted { require(hasTgeEnded(), notClaimable); (uint256 forex, uint256 forexReferred, uint256 eth) = balanceOf( msg.sender ); // Revert here if there's no ETH to withdraw as the FOREX claiming // period may not have yet started. require(eth > 0 || isTgeClaimable(), notClaimable); forex += forexReferred; // Claim forex only if the claimable period has started. if (isTgeClaimable() && forex > 0) claimForex(forex); // Claim ETH hardcap surplus if available. if (eth > 0) claimEthSurplus(eth); } /** * @dev Claims ETH for user. * @param eth The amount of ETH to claim. */ function claimEthSurplus(uint256 eth) private { if (claimedEth[msg.sender]) return; claimedEth[msg.sender] = true; if (eth > 0) safeSendEth(msg.sender, eth); } /** * @dev Claims FOREX for user. * @param forex The amount of FOREX to claim. */ function claimForex(uint256 forex) private { if (claimedForex[msg.sender]) return; claimedForex[msg.sender] = true; IERC20(FOREX).safeTransfer(msg.sender, forex); } /** * @dev Withdraws leftover forex in case the hard cap is not met during TGE. */ function withdrawRemainingForex(address recipient) external onlyOwner { assert(!withdrawnRemainingForex); // Revert if the TGE has not ended. require(hasTgeEnded(), "TGE has not finished"); (uint256 forexClaimable, ) = getClaimableData(); uint256 remainingForex = forexAmount - forexClaimable; withdrawnRemainingForex = true; // Add address zero (null) referrals to withdrawal. remainingForex += getReferralForexAmount(address(0)); if (remainingForex == 0) return; IERC20(FOREX).safeTransfer(recipient, remainingForex); } /** * @dev Returns an account's balance of claimable forex, referral forex, and ETH. * @param account The account to fetch the claimable balance for. */ function balanceOf(address account) public view returns ( uint256 forex, uint256 forexReferred, uint256 eth ) { if (!hasTgeEnded()) return (0, 0, 0); (uint256 forexClaimable, uint256 ethClaimable) = getClaimableData(); uint256 share = shareOf(account); eth = claimedEth[account] ? 0 : (ethClaimable * share) / (1 ether); if (claimedForex[account]) { forex = 0; forexReferred = 0; } else { forex = (forexClaimable * share) / (1 ether); // Forex earned through referrals is 5% of the referred deposits // in FOREX. forexReferred = getReferralForexAmount(account); } } /** * @dev Returns an account's share over the TGE deposits. * @param account The account to fetch the share for. * @return Share value as an 18 decimal ratio. 1 ether = 100%. */ function shareOf(address account) public view returns (uint256) { if (ethDeposited == 0) return 0; return (deposits[account] * (1 ether)) / ethDeposited; } /** * @dev Returns the ETH deposited by an address. * @param depositor The depositor address. */ function getDeposit(address depositor) external view returns (uint256) { return deposits[depositor]; } /** * @dev Whether the TGE already started. It could be closed even if this function returns true. */ function hasTgeBeenStarted() private view returns (bool) { return block.timestamp >= generationStartDate; } /** * @dev Whether the TGE has ended and is closed for new deposits. */ function hasTgeEnded() private view returns (bool) { return block.timestamp > generationStartDate + generationDuration; } /** * @dev Whether the TGE funds can be claimed. */ function isTgeClaimable() private view returns (bool) { return claimDate != 0 && block.timestamp >= claimDate; } /** * @dev The amount of ETH required to generate all supply at max price. */ function ethHardCap() private view returns (uint256) { return (forexAmount * maxTokenPrice) / (1 ether); } /** * @dev Returns the forex price as established by the deposit amount. * The formula for the price is the following: * minPrice + ([maxPrice - minPrice] * min(deposit, maxDeposit)/maxDeposit) * Where maxDeposit = ethHardCap() */ function forexPrice() public view returns (uint256) { uint256 hardCap = ethHardCap(); uint256 depositTowardsHardCap = ethDeposited > hardCap ? hardCap : ethDeposited; uint256 priceRange = maxTokenPrice - minTokenPrice; uint256 priceDelta = (priceRange * depositTowardsHardCap) / hardCap; return minTokenPrice + priceDelta; } /** * @dev Returns TGE data to be used for claims once the TGE closes. */ function getClaimableData() private view returns (uint256 forexClaimable, uint256 ethClaimable) { assert(hasTgeEnded()); uint256 forexPrice = forexPrice(); uint256 hardCap = ethHardCap(); // ETH is only claimable if the deposits exceeded the hard cap. ethClaimable = ethDeposited > hardCap ? ethDeposited - hardCap : 0; // Forex is claimable up to the maximum supply -- when deposits match // the hard cap amount. forexClaimable = ((ethDeposited - ethClaimable) * (1 ether)) / forexPrice; } /** * @dev Returns the amount of FOREX earned by a referrer. * @param referrer The referrer's address. */ function getReferralForexAmount(address referrer) private view returns (uint256) { // Referral claims are disabled. return 0; } /** * @dev Aborts the TGE, stopping new deposits and withdrawing all funds * for the owner. * The only use case for this function is in the * event of an emergency. */ function emergencyAbort() external onlyOwner { assert(!aborted); aborted = true; emergencyWithdrawAllFunds(); } /** * @dev Withdraws all contract funds for the owner. * The only use case for this function is in the * event of an emergency. */ function emergencyWithdrawAllFunds() public onlyOwner { // Transfer ETH. uint256 balance = self.balance; if (balance > 0) safeSendEth(msg.sender, balance); // Transfer FOREX. IERC20 forex = IERC20(FOREX); balance = forex.balanceOf(self); if (balance > 0) forex.transfer(msg.sender, balance); } /** * @dev Withdraws all ETH funds for the owner. * This function may be called at any time, as it correctly * withdraws only the correct contribution amount, ignoring * the ETH amount to be refunded if the deposits exceed * the hard cap. */ function collectContributions() public onlyOwner { uint256 hardCap = ethHardCap(); require( ethWithdrawnByOwner < hardCap, "Cannot withdraw more than hard cap amount" ); uint256 amount = self.balance; if (amount + ethWithdrawnByOwner > hardCap) amount = hardCap - ethWithdrawnByOwner; ethWithdrawnByOwner += amount; require(amount > 0, "Nothing available for withdrawal"); safeSendEth(msg.sender, amount); } /** * @dev Enables FOREX claiming from the next block. * Requires the TGE to have been closed. */ function enableForexClaims() external onlyOwner { assert(hasTgeEnded() && !isTgeClaimable()); claimDate = block.timestamp + 1; } /** * @dev Sets the minimum and maximum token prices before the TGE starts. * Also sets the deposit cap. * @param min The minimum token price in ETH. * @param max The maximum token price in ETH. * @param _depositCap The ETH deposit cap. */ function setMinMaxForexPrices( uint256 min, uint256 max, uint256 _depositCap ) external onlyOwner { assert(!hasTgeBeenStarted()); require(max > min && _depositCap > max, "Invalid values"); minTokenPrice = min; maxTokenPrice = max; depositCap = _depositCap; } /** * @dev Sends ETH and reverts if the transfer fails. * @param recipient The transfer recipient. * @param amount The transfer amount. */ function safeSendEth(address recipient, uint256 amount) private { (bool success, ) = recipient.call{value: amount}(""); require(success, "Failed to send ETH"); } } // 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; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom( address sender, address recipient, uint256 amount ) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../IERC20.sol"; import "../../../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; abstract contract Signature { /** * @dev Returns the address that signed a message given a signature. * @param message The message signed. * @param signature The signature. */ function getSignatureAddress(bytes32 message, bytes memory signature) internal pure returns (address) { assert(signature.length == 65); uint8 v; bytes32 r; bytes32 s; assembly { // First 32 bytes after length prefix. r := mload(add(signature, 32)) // Next 32 bytes. s := mload(add(signature, 64)) // Final byte. v := byte(0, mload(add(signature, 96))) } return ecrecover(message, v, r, s); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); (bool success, bytes memory returndata) = target.delegatecall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } }
Sends ETH and reverts if the transfer fails. recipient The transfer recipient. amount The transfer amount./
function safeSendEth(address recipient, uint256 amount) private { require(success, "Failed to send ETH"); }
9,961,096
// SPDX-License-Identifier: MIT pragma solidity =0.8.2; import "./FixedPoint.sol"; /** * @dev Originally DeriswapV1Math * @author Andre Cronje, LevX */ library MirinMath { using FixedPoint for *; uint256 private constant FIXED_1 = 0x080000000000000000000000000000000; uint256 private constant FIXED_2 = 0x100000000000000000000000000000000; uint256 private constant SQRT_1 = 13043817825332782212; uint256 private constant LNX = 3988425491; uint256 private constant LOG_10_2 = 3010299957; uint256 private constant LOG_E_2 = 6931471806; uint256 private constant BASE = 1e10; function max(uint256 a, uint256 b) internal pure returns (uint256) { return a >= b ? a : b; } function min(uint256 x, uint256 y) internal pure returns (uint256 z) { z = x < y ? x : y; } function floorLog2(uint256 _n) internal pure returns (uint8) { uint8 res = 0; if (_n < 256) { // At most 8 iterations while (_n > 1) { _n >>= 1; res += 1; } } else { // Exactly 8 iterations for (uint8 s = 128; s > 0; s >>= 1) { if (_n >= (uint256(1) << s)) { _n >>= s; res |= s; } } } return res; } function ln(uint256 x) internal pure returns (uint256) { uint256 res = 0; // If x >= 2, then we compute the integer part of log2(x), which is larger than 0. if (x >= FIXED_2) { uint8 count = floorLog2(x / FIXED_1); x >>= count; // now x < 2 res = count * FIXED_1; } // If x > 1, then we compute the fraction part of log2(x), which is larger than 0. if (x > FIXED_1) { for (uint8 i = 127; i > 0; --i) { x = (x * x) / FIXED_1; // now 1 < x < 4 if (x >= FIXED_2) { x >>= 1; // now 1 < x < 2 res += uint256(1) << (i - 1); } } } return (res * LOG_E_2) / BASE; } /** * @dev computes e ^ (x / FIXED_1) * FIXED_1 * input range: 0 <= x <= OPT_EXP_MAX_VAL - 1 * auto-generated via 'PrintFunctionOptimalExp.py' * Detailed description: * - Rewrite the input as a sum of binary exponents and a single residual r, as small as possible * - The exponentiation of each binary exponent is given (pre-calculated) * - The exponentiation of r is calculated via Taylor series for e^x, where x = r * - The exponentiation of the input is calculated by multiplying the intermediate results above * - For example: e^5.521692859 = e^(4 + 1 + 0.5 + 0.021692859) = e^4 * e^1 * e^0.5 * e^0.021692859 */ function optimalExp(uint256 x) internal pure returns (uint256) { uint256 res = 0; uint256 y; uint256 z; z = y = x % 0x10000000000000000000000000000000; // get the input modulo 2^(-3) z = (z * y) / FIXED_1; res += z * 0x10e1b3be415a0000; // add y^02 * (20! / 02!) z = (z * y) / FIXED_1; res += z * 0x05a0913f6b1e0000; // add y^03 * (20! / 03!) z = (z * y) / FIXED_1; res += z * 0x0168244fdac78000; // add y^04 * (20! / 04!) z = (z * y) / FIXED_1; res += z * 0x004807432bc18000; // add y^05 * (20! / 05!) z = (z * y) / FIXED_1; res += z * 0x000c0135dca04000; // add y^06 * (20! / 06!) z = (z * y) / FIXED_1; res += z * 0x0001b707b1cdc000; // add y^07 * (20! / 07!) z = (z * y) / FIXED_1; res += z * 0x000036e0f639b800; // add y^08 * (20! / 08!) z = (z * y) / FIXED_1; res += z * 0x00000618fee9f800; // add y^09 * (20! / 09!) z = (z * y) / FIXED_1; res += z * 0x0000009c197dcc00; // add y^10 * (20! / 10!) z = (z * y) / FIXED_1; res += z * 0x0000000e30dce400; // add y^11 * (20! / 11!) z = (z * y) / FIXED_1; res += z * 0x000000012ebd1300; // add y^12 * (20! / 12!) z = (z * y) / FIXED_1; res += z * 0x0000000017499f00; // add y^13 * (20! / 13!) z = (z * y) / FIXED_1; res += z * 0x0000000001a9d480; // add y^14 * (20! / 14!) z = (z * y) / FIXED_1; res += z * 0x00000000001c6380; // add y^15 * (20! / 15!) z = (z * y) / FIXED_1; res += z * 0x000000000001c638; // add y^16 * (20! / 16!) z = (z * y) / FIXED_1; res += z * 0x0000000000001ab8; // add y^17 * (20! / 17!) z = (z * y) / FIXED_1; res += z * 0x000000000000017c; // add y^18 * (20! / 18!) z = (z * y) / FIXED_1; res += z * 0x0000000000000014; // add y^19 * (20! / 19!) z = (z * y) / FIXED_1; res += z * 0x0000000000000001; // add y^20 * (20! / 20!) res = res / 0x21c3677c82b40000 + y + FIXED_1; // divide by 20! and then add y^1 / 1! + y^0 / 0! if ((x & 0x010000000000000000000000000000000) != 0) res = (res * 0x1c3d6a24ed82218787d624d3e5eba95f9) / 0x18ebef9eac820ae8682b9793ac6d1e776; // multiply by e^2^(-3) if ((x & 0x020000000000000000000000000000000) != 0) res = (res * 0x18ebef9eac820ae8682b9793ac6d1e778) / 0x1368b2fc6f9609fe7aceb46aa619baed4; // multiply by e^2^(-2) if ((x & 0x040000000000000000000000000000000) != 0) res = (res * 0x1368b2fc6f9609fe7aceb46aa619baed5) / 0x0bc5ab1b16779be3575bd8f0520a9f21f; // multiply by e^2^(-1) if ((x & 0x080000000000000000000000000000000) != 0) res = (res * 0x0bc5ab1b16779be3575bd8f0520a9f21e) / 0x0454aaa8efe072e7f6ddbab84b40a55c9; // multiply by e^2^(+0) if ((x & 0x100000000000000000000000000000000) != 0) res = (res * 0x0454aaa8efe072e7f6ddbab84b40a55c5) / 0x00960aadc109e7a3bf4578099615711ea; // multiply by e^2^(+1) if ((x & 0x200000000000000000000000000000000) != 0) res = (res * 0x00960aadc109e7a3bf4578099615711d7) / 0x0002bf84208204f5977f9a8cf01fdce3d; // multiply by e^2^(+2) if ((x & 0x400000000000000000000000000000000) != 0) res = (res * 0x0002bf84208204f5977f9a8cf01fdc307) / 0x0000003c6ab775dd0b95b4cbee7e65d11; // multiply by e^2^(+3) return res; } function quoteOptionAll( uint256 t, uint256 v, uint256 sp, uint256 st ) public pure returns (uint256 call, uint256 put) { uint256 _c; uint256 _p; if (sp > st) { _c = C(t, v, sp, st); _p = st - sp + _c; } else { _p = C(t, v, st, sp); _c = st - sp + _p; } return (_c, _p); } function C( uint256 t, uint256 v, uint256 sp, uint256 st ) public pure returns (uint256) { if (sp == st) { return (((((LNX * sp) / 1e10) * v) / 1e18) * sqrt((1e18 * t) / 365)) / 1e9; } uint256 sigma = ((v**2) / 2); uint256 sigmaB = 1e36; uint256 sig = (((1e18 * sigma) / sigmaB) * t) / 365; uint256 sSQRT = (v * sqrt((1e18 * t) / 365)) / 1e9; uint256 d1 = (1e18 * ln((FIXED_1 * sp) / st)) / FIXED_1; d1 = ((d1 + sig) * 1e18) / sSQRT; uint256 d2 = d1 - sSQRT; uint256 cdfD1 = ncdf((FIXED_1 * d1) / 1e18); uint256 cdfD2 = ncdf((FIXED_1 * d2) / 1e18); return (sp * cdfD1) / 1e14 - (st * cdfD2) / 1e14; } function ncdf(uint256 x) internal pure returns (uint256) { int256 t1 = int256(1e7 + ((2315419 * x) / FIXED_1)); uint256 exp = ((x / 2) * x) / FIXED_1; int256 d = int256((3989423 * FIXED_1) / optimalExp(uint256(exp))); uint256 prob = uint256( (d * (3193815 + ((-3565638 + ((17814780 + ((-18212560 + (13302740 * 1e7) / t1) * 1e7) / t1) * 1e7) / t1) * 1e7) / t1) * 1e7) / t1 ); if (x > 0) prob = 1e14 - prob; return prob; } function generalLog(uint256 x) internal pure returns (uint256) { uint256 res = 0; // If x >= 2, then we compute the integer part of log2(x), which is larger than 0. if (x >= FIXED_2) { uint8 count = floorLog2(x / FIXED_1); x >>= count; // now x < 2 res = count * FIXED_1; } // If x > 1, then we compute the fraction part of log2(x), which is larger than 0. if (x > FIXED_1) { for (uint8 i = 127; i > 0; --i) { x = (x * x) / FIXED_1; // now 1 < x < 4 if (x >= FIXED_2) { x >>= 1; // now 1 < x < 2 res += uint256(1) << (i - 1); } } } return (res * LOG_10_2) / BASE; } function vol(uint256[] memory p) internal pure returns (uint256 x) { for (uint8 i = 1; i <= (p.length - 1); i++) { x += ((generalLog(p[i] * FIXED_1) - generalLog(p[i - 1] * FIXED_1)))**2; //denom += FIXED_1**2; } //return (sum, denom); x = sqrt(uint256(252) * sqrt(x / (p.length - 1))); return (uint256(1e18) * x) / SQRT_1; } // babylonian method (https://en.wikipedia.org/wiki/Methods_of_computing_square_roots#Babylonian_method) function sqrt(uint256 y) internal pure returns (uint256 z) { if (y > 3) { z = y; uint256 x = y / 2 + 1; while (x < z) { z = x; x = (y / x + x) / 2; } } else if (y != 0) { z = 1; } } /** * @dev computes x ^ (1 / y) where y = 2 ^ c and c >= 0 */ function root(uint256 x, uint256 y) internal pure returns (uint256 z) { require(y != 0, "MIRIN: DIV_BY_ZERO"); if (y == 1) return x; z = sqrt(x); while (y > 2) { require(y % 2 == 0, "MIRIN: INVALID_BASE"); z = sqrt(z); y = y >> 1; } return z; } /** * @dev determines if x = 2 ^ c where c >= 1 */ function isPow2(uint256 x) internal pure returns (bool) { if (x == 1) return false; while (x > 2) { if (x % 2 != 0) return false; x = x >> 1; } return true; } /** * @dev stddev calculates the standard deviation for an array of integers * @dev precision is the same as sqrt above meaning for higher precision * @dev the decimal place must be moved prior to passing the params * @param numbers uint[] array of numbers to be used in calculation */ function stddev(uint256[] memory numbers) public pure returns (uint256 sd) { uint256 sum = 0; for (uint256 i = 0; i < numbers.length; i++) { sum += numbers[i]; } uint256 mean = sum / numbers.length; // Integral value; float not supported in Solidity sum = 0; for (uint256 i = 0; i < numbers.length; i++) { sum += (numbers[i] - mean)**2; } sd = sqrt(sum / (numbers.length - 1)); //Integral value; float not supported in Solidity return sd; } }
determines if x = 2 ^ c where c >= 1/
function isPow2(uint256 x) internal pure returns (bool) { if (x == 1) return false; while (x > 2) { if (x % 2 != 0) return false; x = x >> 1; } return true; }
5,438,121
./full_match/100/0x87b52eD635DF746cA29651581B4d87517AAa9a9F/sources/src/CoWFallbackHandler.sol
Returns hash of a message that can be signed by owners. This has been copied from solhint-disable-next-line max-line-length / https://github.com/safe-global/safe-contracts/blob/5abc0bb25e7bffce8c9e53de47a392229540acf9/contracts/handler/CompatibilityFallbackHandler.sol however `safe` parameter has been replaced by the `domainSeparator` parameter. This allows for the `domainSeparator` to be cached in the calling routine, saving gas. domainSeparator Domain separator of the Safe. message Message that should be hashed return Message hash.
function getMessageHashForSafe(bytes32 domainSeparator, bytes memory message) internal pure returns (bytes32) { return keccak256( abi.encodePacked( bytes1(0x19), bytes1(0x01), domainSeparator, keccak256(abi.encode(SAFE_MSG_TYPEHASH, keccak256(message))) ) ); }
14,289,309
pragma solidity 0.7.3; library AdditionalMath { using SafeMath for uint256; function max16(uint16 a, uint16 b) internal pure returns (uint16) { return a >= b ? a : b; } function min16(uint16 a, uint16 b) internal pure returns (uint16) { return a < b ? a : b; } /** * @notice Division and ceil */ function divCeil(uint256 a, uint256 b) internal pure returns (uint256) { return (a.add(b) - 1) / b; } /** * @dev Adds signed value to unsigned value, throws on overflow. */ function addSigned(uint256 a, int256 b) internal pure returns (uint256) { if (b >= 0) { return a.add(uint256(b)); } else { return a.sub(uint256(-b)); } } /** * @dev Subtracts signed value from unsigned value, throws on overflow. */ function subSigned(uint256 a, int256 b) internal pure returns (uint256) { if (b >= 0) { return a.sub(uint256(b)); } else { return a.add(uint256(-b)); } } /** * @dev Multiplies two numbers, throws on overflow. */ function mul32(uint32 a, uint32 b) internal pure returns (uint32) { if (a == 0) { return 0; } uint32 c = a * b; assert(c / a == b); return c; } /** * @dev Adds two numbers, throws on overflow. */ function add16(uint16 a, uint16 b) internal pure returns (uint16) { uint16 c = a + b; assert(c >= a); return c; } /** * @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). */ function sub16(uint16 a, uint16 b) internal pure returns (uint16) { assert(b <= a); return a - b; } /** * @dev Adds signed value to unsigned value, throws on overflow. */ function addSigned16(uint16 a, int16 b) internal pure returns (uint16) { if (b >= 0) { return add16(a, uint16(b)); } else { return sub16(a, uint16(-b)); } } /** * @dev Subtracts signed value from unsigned value, throws on overflow. */ function subSigned16(uint16 a, int16 b) internal pure returns (uint16) { if (b >= 0) { return sub16(a, uint16(b)); } else { return add16(a, uint16(-b)); } } } library Bits { uint256 internal constant ONE = uint256(1); /** * @notice Sets the bit at the given 'index' in 'self' to: * '1' - if the bit is '0' * '0' - if the bit is '1' * @return The modified value */ function toggleBit(uint256 self, uint8 index) internal pure returns (uint256) { return self ^ ONE << index; } /** * @notice Get the value of the bit at the given 'index' in 'self'. */ function bit(uint256 self, uint8 index) internal pure returns (uint8) { return uint8(self >> index & 1); } /** * @notice Check if the bit at the given 'index' in 'self' is set. * @return 'true' - if the value of the bit is '1', * 'false' - if the value of the bit is '0' */ function bitSet(uint256 self, uint8 index) internal pure returns (bool) { return self >> index & 1 == 1; } } interface IERC20 { function transfer(address to, uint256 value) external returns (bool); function approve(address spender, uint256 value) external returns (bool); function transferFrom(address from, address to, uint256 value) external returns (bool); function totalSupply() external view returns (uint256); function balanceOf(address who) external view returns (uint256); function allowance(address owner, address spender) external view returns (uint256); event Transfer(address indexed from, address indexed to, uint256 value); event Approval(address indexed owner, address indexed spender, uint256 value); } interface IERC900History { function totalStakedForAt(address addr, uint256 blockNumber) external view returns (uint256); function totalStakedAt(uint256 blockNumber) external view returns (uint256); function supportsHistory() external pure returns (bool); } 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 Calculates the average of two numbers. Since these are integers, * averages of an even and odd number cannot be represented, and will be * rounded down. */ 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); } } interface TokenRecipient { /** * @notice Receives a notification of approval of the transfer * @param _from Sender of approval * @param _value The amount of tokens to be spent * @param _tokenContract Address of the token contract * @param _extraData Extra data */ function receiveApproval(address _from, uint256 _value, address _tokenContract, bytes calldata _extraData) external; } abstract contract Ownable { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ constructor () { _owner = msg.sender; emit OwnershipTransferred(address(0), _owner); } /** * @return the address of the owner. */ function owner() public view returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(isOwner()); _; } /** * @return true if `msg.sender` is the owner of the contract. */ function isOwner() public view returns (bool) { return msg.sender == _owner; } /** * @dev Allows the current owner to relinquish control of the contract. * @notice Renouncing to ownership will leave the contract without an owner. * It will not be possible to call the functions with the `onlyOwner` * modifier anymore. */ function renounceOwnership() public onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) public virtual onlyOwner { _transferOwnership(newOwner); } /** * @dev Transfers control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function _transferOwnership(address newOwner) internal { require(newOwner != address(0)); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } library SafeERC20 { using SafeMath for uint256; function safeTransfer(IERC20 token, address to, uint256 value) internal { require(token.transfer(to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal { require(token.transferFrom(from, to, value)); } function safeApprove(IERC20 token, address spender, uint256 value) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' require((value == 0) || (token.allowance(msg.sender, spender) == 0)); require(token.approve(spender, value)); } function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).add(value); require(token.approve(spender, newAllowance)); } function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).sub(value); require(token.approve(spender, newAllowance)); } } library SafeMath { /** * @dev Multiplies two unsigned integers, reverts on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b); return c; } /** * @dev Integer division of two unsigned integers truncating the quotient, reverts on division by zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // Solidity only automatically asserts when dividing by 0 require(b > 0); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Subtracts two unsigned integers, reverts on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a); uint256 c = a - b; return c; } /** * @dev Adds two unsigned integers, reverts on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a); return c; } /** * @dev Divides two unsigned integers and returns the remainder (unsigned integer modulo), * reverts when dividing by zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b != 0); return a % b; } } library Snapshot { function encodeSnapshot(uint32 _time, uint96 _value) internal pure returns(uint128) { return uint128(uint256(_time) << 96 | uint256(_value)); } function decodeSnapshot(uint128 _snapshot) internal pure returns(uint32 time, uint96 value){ time = uint32(bytes4(bytes16(_snapshot))); value = uint96(_snapshot); } function addSnapshot(uint128[] storage _self, uint256 _value) internal { addSnapshot(_self, block.number, _value); } function addSnapshot(uint128[] storage _self, uint256 _time, uint256 _value) internal { uint256 length = _self.length; if (length != 0) { (uint32 currentTime, ) = decodeSnapshot(_self[length - 1]); if (uint32(_time) == currentTime) { _self[length - 1] = encodeSnapshot(uint32(_time), uint96(_value)); return; } else if (uint32(_time) < currentTime){ revert(); } } _self.push(encodeSnapshot(uint32(_time), uint96(_value))); } function lastSnapshot(uint128[] storage _self) internal view returns (uint32, uint96) { uint256 length = _self.length; if (length > 0) { return decodeSnapshot(_self[length - 1]); } return (0, 0); } function lastValue(uint128[] storage _self) internal view returns (uint96) { (, uint96 value) = lastSnapshot(_self); return value; } function getValueAt(uint128[] storage _self, uint256 _time256) internal view returns (uint96) { uint32 _time = uint32(_time256); uint256 length = _self.length; // Short circuit if there's no checkpoints yet // Note that this also lets us avoid using SafeMath later on, as we've established that // there must be at least one checkpoint if (length == 0) { return 0; } // Check last checkpoint uint256 lastIndex = length - 1; (uint32 snapshotTime, uint96 snapshotValue) = decodeSnapshot(_self[length - 1]); if (_time >= snapshotTime) { return snapshotValue; } // Check first checkpoint (if not already checked with the above check on last) (snapshotTime, snapshotValue) = decodeSnapshot(_self[0]); if (length == 1 || _time < snapshotTime) { return 0; } // Do binary search // As we've already checked both ends, we don't need to check the last checkpoint again uint256 low = 0; uint256 high = lastIndex - 1; uint32 midTime; uint96 midValue; while (high > low) { uint256 mid = (high + low + 1) / 2; // average, ceil round (midTime, midValue) = decodeSnapshot(_self[mid]); if (_time > midTime) { low = mid; } else if (_time < midTime) { // Note that we don't need SafeMath here because mid must always be greater than 0 // from the while condition high = mid - 1; } else { // _time == midTime return midValue; } } (, snapshotValue) = decodeSnapshot(_self[low]); return snapshotValue; } } interface PolicyManagerInterface { function register(address _node, uint16 _period) external; function escrow() external view returns (address); function ping( address _node, uint16 _processedPeriod1, uint16 _processedPeriod2, uint16 _periodToSetDefault ) external; } interface AdjudicatorInterface { function escrow() external view returns (address); } interface WorkLockInterface { function escrow() external view returns (address); } abstract contract Upgradeable is Ownable { event StateVerified(address indexed testTarget, address sender); event UpgradeFinished(address indexed target, address sender); /** * @dev Contracts at the target must reserve the same location in storage for this address as in Dispatcher * Stored data actually lives in the Dispatcher * However the storage layout is specified here in the implementing contracts */ address public target; /** * @dev Previous contract address (if available). Used for rollback */ address public previousTarget; /** * @dev Upgrade status. Explicit `uint8` type is used instead of `bool` to save gas by excluding 0 value */ uint8 public isUpgrade; /** * @dev Guarantees that next slot will be separated from the previous */ uint256 stubSlot; /** * @dev Constants for `isUpgrade` field */ uint8 constant UPGRADE_FALSE = 1; uint8 constant UPGRADE_TRUE = 2; /** * @dev Checks that function executed while upgrading * Recommended to add to `verifyState` and `finishUpgrade` methods */ modifier onlyWhileUpgrading() { require(isUpgrade == UPGRADE_TRUE); _; } /** * @dev Method for verifying storage state. * Should check that new target contract returns right storage value */ function verifyState(address _testTarget) public virtual onlyWhileUpgrading { emit StateVerified(_testTarget, msg.sender); } /** * @dev Copy values from the new target to the current storage * @param _target New target contract address */ function finishUpgrade(address _target) public virtual onlyWhileUpgrading { emit UpgradeFinished(_target, msg.sender); } /** * @dev Base method to get data * @param _target Target to call * @param _selector Method selector * @param _numberOfArguments Number of used arguments * @param _argument1 First method argument * @param _argument2 Second method argument * @return memoryAddress Address in memory where the data is located */ function delegateGetData( address _target, bytes4 _selector, uint8 _numberOfArguments, bytes32 _argument1, bytes32 _argument2 ) internal returns (bytes32 memoryAddress) { assembly { memoryAddress := mload(0x40) mstore(memoryAddress, _selector) if gt(_numberOfArguments, 0) { mstore(add(memoryAddress, 0x04), _argument1) } if gt(_numberOfArguments, 1) { mstore(add(memoryAddress, 0x24), _argument2) } switch delegatecall(gas(), _target, memoryAddress, add(0x04, mul(0x20, _numberOfArguments)), 0, 0) case 0 { revert(memoryAddress, 0) } default { returndatacopy(memoryAddress, 0x0, returndatasize()) } } } /** * @dev Call "getter" without parameters. * Result should not exceed 32 bytes */ function delegateGet(address _target, bytes4 _selector) internal returns (uint256 result) { bytes32 memoryAddress = delegateGetData(_target, _selector, 0, 0, 0); assembly { result := mload(memoryAddress) } } /** * @dev Call "getter" with one parameter. * Result should not exceed 32 bytes */ function delegateGet(address _target, bytes4 _selector, bytes32 _argument) internal returns (uint256 result) { bytes32 memoryAddress = delegateGetData(_target, _selector, 1, _argument, 0); assembly { result := mload(memoryAddress) } } /** * @dev Call "getter" with two parameters. * Result should not exceed 32 bytes */ function delegateGet( address _target, bytes4 _selector, bytes32 _argument1, bytes32 _argument2 ) internal returns (uint256 result) { bytes32 memoryAddress = delegateGetData(_target, _selector, 2, _argument1, _argument2); assembly { result := mload(memoryAddress) } } } contract ERC20 is IERC20 { using SafeMath for uint256; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowed; uint256 private _totalSupply; /** * @dev Total number of tokens in existence */ function totalSupply() public view override returns (uint256) { return _totalSupply; } /** * @dev Gets the balance of the specified address. * @param owner The address to query the balance of. * @return An uint256 representing the amount owned by the passed address. */ function balanceOf(address owner) public view override returns (uint256) { return _balances[owner]; } /** * @dev Function to check the amount of tokens that an owner allowed to a spender. * @param owner address The address which owns the funds. * @param spender address The address which will spend the funds. * @return A uint256 specifying the amount of tokens still available for the spender. */ function allowance(address owner, address spender) public view override returns (uint256) { return _allowed[owner][spender]; } /** * @dev Transfer token for a specified address * @param to The address to transfer to. * @param value The amount to be transferred. */ function transfer(address to, uint256 value) public override returns (bool) { _transfer(msg.sender, to, value); return true; } /** * @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender. * Beware that changing an allowance with this method brings the risk that someone may use both the old * and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this * race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * @param spender The address which will spend the funds. * @param value The amount of tokens to be spent. */ function approve(address spender, uint256 value) public override returns (bool) { // To change the approve amount you first have to reduce the addresses` // allowance to zero by calling `approve(_spender, 0)` if it is not // already 0 to mitigate the race condition described here: // https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 require(value == 0 || _allowed[msg.sender][spender] == 0); _approve(msg.sender, spender, value); return true; } /** * @dev Transfer tokens from one address to another. * Note that while this function emits an Approval event, this is not required as per the specification, * and other compliant implementations may not emit the event. * @param from address The address which you want to send tokens from * @param to address The address which you want to transfer to * @param value uint256 the amount of tokens to be transferred */ function transferFrom(address from, address to, uint256 value) public override returns (bool) { _transfer(from, to, value); _approve(from, msg.sender, _allowed[from][msg.sender].sub(value)); return true; } /** * @dev Increase the amount of tokens that an owner allowed to a spender. * approve should be called when allowed_[_spender] == 0. To increment * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * Emits an Approval event. * @param spender The address which will spend the funds. * @param addedValue The amount of tokens to increase the allowance by. */ function increaseAllowance(address spender, uint256 addedValue) public returns (bool) { _approve(msg.sender, spender, _allowed[msg.sender][spender].add(addedValue)); return true; } /** * @dev Decrease the amount of tokens that an owner allowed to a spender. * approve should be called when allowed_[_spender] == 0. To decrement * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * Emits an Approval event. * @param spender The address which will spend the funds. * @param subtractedValue The amount of tokens to decrease the allowance by. */ function decreaseAllowance(address spender, uint256 subtractedValue) public returns (bool) { _approve(msg.sender, spender, _allowed[msg.sender][spender].sub(subtractedValue)); return true; } /** * @dev Transfer token for a specified addresses * @param from The address to transfer from. * @param to The address to transfer to. * @param value The amount to be transferred. */ function _transfer(address from, address to, uint256 value) internal { require(to != address(0)); _balances[from] = _balances[from].sub(value); _balances[to] = _balances[to].add(value); emit Transfer(from, to, value); } /** * @dev Internal function that mints an amount of the token and assigns it to * an account. This encapsulates the modification of balances such that the * proper events are emitted. * @param account The account that will receive the created tokens. * @param value The amount that will be created. */ function _mint(address account, uint256 value) internal { require(account != address(0)); _totalSupply = _totalSupply.add(value); _balances[account] = _balances[account].add(value); emit Transfer(address(0), account, value); } /** * @dev Internal function that burns an amount of the token of a given * account. * @param account The account whose tokens will be burnt. * @param value The amount that will be burnt. */ function _burn(address account, uint256 value) internal { require(account != address(0)); _totalSupply = _totalSupply.sub(value); _balances[account] = _balances[account].sub(value); emit Transfer(account, address(0), value); } /** * @dev Approve an address to spend another addresses' tokens. * @param owner The address that owns the tokens. * @param spender The address that will spend the tokens. * @param value The number of tokens that can be spent. */ function _approve(address owner, address spender, uint256 value) internal { require(spender != address(0)); require(owner != address(0)); _allowed[owner][spender] = value; emit Approval(owner, spender, value); } /** * @dev Internal function that burns an amount of the token of a given * account, deducting from the sender's allowance for said account. Uses the * internal burn function. * Emits an Approval event (reflecting the reduced allowance). * @param account The account whose tokens will be burnt. * @param value The amount that will be burnt. */ function _burnFrom(address account, uint256 value) internal { _burn(account, value); _approve(account, msg.sender, _allowed[account][msg.sender].sub(value)); } } abstract contract ERC20Detailed is IERC20 { string private _name; string private _symbol; uint8 private _decimals; constructor (string memory name, string memory symbol, uint8 decimals) { _name = name; _symbol = symbol; _decimals = decimals; } /** * @return the name of the token. */ function name() public view returns (string memory) { return _name; } /** * @return the symbol of the token. */ function symbol() public view returns (string memory) { return _symbol; } /** * @return the number of decimals of the token. */ function decimals() public view returns (uint8) { return _decimals; } } abstract contract Issuer is Upgradeable { using SafeERC20 for NuCypherToken; using AdditionalMath for uint32; event Donated(address indexed sender, uint256 value); /// Issuer is initialized with a reserved reward event Initialized(uint256 reservedReward); uint128 constant MAX_UINT128 = uint128(0) - 1; NuCypherToken public immutable token; uint128 public immutable totalSupply; // d * k2 uint256 public immutable mintingCoefficient; // k1 uint256 public immutable lockDurationCoefficient1; // k2 uint256 public immutable lockDurationCoefficient2; uint32 public immutable secondsPerPeriod; // kmax uint16 public immutable maximumRewardedPeriods; uint256 public immutable firstPhaseMaxIssuance; uint256 public immutable firstPhaseTotalSupply; /** * Current supply is used in the minting formula and is stored to prevent different calculation * for stakers which get reward in the same period. There are two values - * supply for previous period (used in formula) and supply for current period which accumulates value * before end of period. */ uint128 public previousPeriodSupply; uint128 public currentPeriodSupply; uint16 public currentMintingPeriod; /** * @notice Constructor sets address of token contract and coefficients for minting * @dev Minting formula for one sub-stake in one period for the first phase firstPhaseMaxIssuance * (lockedValue / totalLockedValue) * (k1 + min(allLockedPeriods, kmax)) / k2 * @dev Minting formula for one sub-stake in one period for the second phase (totalSupply - currentSupply) / d * (lockedValue / totalLockedValue) * (k1 + min(allLockedPeriods, kmax)) / k2 if allLockedPeriods > maximumRewardedPeriods then allLockedPeriods = maximumRewardedPeriods * @param _token Token contract * @param _hoursPerPeriod Size of period in hours * @param _issuanceDecayCoefficient (d) Coefficient which modifies the rate at which the maximum issuance decays, * only applicable to Phase 2. d = 365 * half-life / LOG2 where default half-life = 2. * See Equation 10 in Staking Protocol & Economics paper * @param _lockDurationCoefficient1 (k1) Numerator of the coefficient which modifies the extent * to which a stake's lock duration affects the subsidy it receives. Affects stakers differently. * Applicable to Phase 1 and Phase 2. k1 = k2 * small_stake_multiplier where default small_stake_multiplier = 0.5. * See Equation 8 in Staking Protocol & Economics paper. * @param _lockDurationCoefficient2 (k2) Denominator of the coefficient which modifies the extent * to which a stake's lock duration affects the subsidy it receives. Affects stakers differently. * Applicable to Phase 1 and Phase 2. k2 = maximum_rewarded_periods / (1 - small_stake_multiplier) * where default maximum_rewarded_periods = 365 and default small_stake_multiplier = 0.5. * See Equation 8 in Staking Protocol & Economics paper. * @param _maximumRewardedPeriods (kmax) Number of periods beyond which a stake's lock duration * no longer increases the subsidy it receives. kmax = reward_saturation * 365 where default reward_saturation = 1. * See Equation 8 in Staking Protocol & Economics paper. * @param _firstPhaseTotalSupply Total supply for the first phase * @param _firstPhaseMaxIssuance (Imax) Maximum number of new tokens minted per period during Phase 1. * See Equation 7 in Staking Protocol & Economics paper. */ constructor( NuCypherToken _token, uint32 _hoursPerPeriod, uint256 _issuanceDecayCoefficient, uint256 _lockDurationCoefficient1, uint256 _lockDurationCoefficient2, uint16 _maximumRewardedPeriods, uint256 _firstPhaseTotalSupply, uint256 _firstPhaseMaxIssuance ) { uint256 localTotalSupply = _token.totalSupply(); require(localTotalSupply > 0 && _issuanceDecayCoefficient != 0 && _hoursPerPeriod != 0 && _lockDurationCoefficient1 != 0 && _lockDurationCoefficient2 != 0 && _maximumRewardedPeriods != 0); require(localTotalSupply <= uint256(MAX_UINT128), "Token contract has supply more than supported"); uint256 maxLockDurationCoefficient = _maximumRewardedPeriods + _lockDurationCoefficient1; uint256 localMintingCoefficient = _issuanceDecayCoefficient * _lockDurationCoefficient2; require(maxLockDurationCoefficient > _maximumRewardedPeriods && localMintingCoefficient / _issuanceDecayCoefficient == _lockDurationCoefficient2 && // worst case for `totalLockedValue * d * k2`, when totalLockedValue == totalSupply localTotalSupply * localMintingCoefficient / localTotalSupply == localMintingCoefficient && // worst case for `(totalSupply - currentSupply) * lockedValue * (k1 + min(allLockedPeriods, kmax))`, // when currentSupply == 0, lockedValue == totalSupply localTotalSupply * localTotalSupply * maxLockDurationCoefficient / localTotalSupply / localTotalSupply == maxLockDurationCoefficient, "Specified parameters cause overflow"); require(maxLockDurationCoefficient <= _lockDurationCoefficient2, "Resulting locking duration coefficient must be less than 1"); require(_firstPhaseTotalSupply <= localTotalSupply, "Too many tokens for the first phase"); require(_firstPhaseMaxIssuance <= _firstPhaseTotalSupply, "Reward for the first phase is too high"); token = _token; secondsPerPeriod = _hoursPerPeriod.mul32(1 hours); lockDurationCoefficient1 = _lockDurationCoefficient1; lockDurationCoefficient2 = _lockDurationCoefficient2; maximumRewardedPeriods = _maximumRewardedPeriods; firstPhaseTotalSupply = _firstPhaseTotalSupply; firstPhaseMaxIssuance = _firstPhaseMaxIssuance; totalSupply = uint128(localTotalSupply); mintingCoefficient = localMintingCoefficient; } /** * @dev Checks contract initialization */ modifier isInitialized() { require(currentMintingPeriod != 0); _; } /** * @return Number of current period */ function getCurrentPeriod() public view returns (uint16) { return uint16(block.timestamp / secondsPerPeriod); } /** * @notice Initialize reserved tokens for reward */ function initialize(uint256 _reservedReward, address _sourceOfFunds) external onlyOwner { require(currentMintingPeriod == 0); // Reserved reward must be sufficient for at least one period of the first phase require(firstPhaseMaxIssuance <= _reservedReward); currentMintingPeriod = getCurrentPeriod(); currentPeriodSupply = totalSupply - uint128(_reservedReward); previousPeriodSupply = currentPeriodSupply; token.safeTransferFrom(_sourceOfFunds, address(this), _reservedReward); emit Initialized(_reservedReward); } /** * @notice Function to mint tokens for one period. * @param _currentPeriod Current period number. * @param _lockedValue The amount of tokens that were locked by user in specified period. * @param _totalLockedValue The amount of tokens that were locked by all users in specified period. * @param _allLockedPeriods The max amount of periods during which tokens will be locked after specified period. * @return amount Amount of minted tokens. */ function mint( uint16 _currentPeriod, uint256 _lockedValue, uint256 _totalLockedValue, uint16 _allLockedPeriods ) internal returns (uint256 amount) { if (currentPeriodSupply == totalSupply) { return 0; } if (_currentPeriod > currentMintingPeriod) { previousPeriodSupply = currentPeriodSupply; currentMintingPeriod = _currentPeriod; } uint256 currentReward; uint256 coefficient; // first phase // firstPhaseMaxIssuance * lockedValue * (k1 + min(allLockedPeriods, kmax)) / (totalLockedValue * k2) if (previousPeriodSupply + firstPhaseMaxIssuance <= firstPhaseTotalSupply) { currentReward = firstPhaseMaxIssuance; coefficient = lockDurationCoefficient2; // second phase // (totalSupply - currentSupply) * lockedValue * (k1 + min(allLockedPeriods, kmax)) / (totalLockedValue * d * k2) } else { currentReward = totalSupply - previousPeriodSupply; coefficient = mintingCoefficient; } uint256 allLockedPeriods = AdditionalMath.min16(_allLockedPeriods, maximumRewardedPeriods) + lockDurationCoefficient1; amount = (uint256(currentReward) * _lockedValue * allLockedPeriods) / (_totalLockedValue * coefficient); // rounding the last reward uint256 maxReward = getReservedReward(); if (amount == 0) { amount = 1; } else if (amount > maxReward) { amount = maxReward; } currentPeriodSupply += uint128(amount); } /** * @notice Return tokens for future minting * @param _amount Amount of tokens */ function unMint(uint256 _amount) internal { previousPeriodSupply -= uint128(_amount); currentPeriodSupply -= uint128(_amount); } /** * @notice Donate sender's tokens. Amount of tokens will be returned for future minting * @param _value Amount to donate */ function donate(uint256 _value) external isInitialized { token.safeTransferFrom(msg.sender, address(this), _value); unMint(_value); emit Donated(msg.sender, _value); } /** * @notice Returns the number of tokens that can be minted */ function getReservedReward() public view returns (uint256) { return totalSupply - currentPeriodSupply; } /// @dev the `onlyWhileUpgrading` modifier works through a call to the parent `verifyState` function verifyState(address _testTarget) public override virtual { super.verifyState(_testTarget); require(uint16(delegateGet(_testTarget, this.currentMintingPeriod.selector)) == currentMintingPeriod); require(uint128(delegateGet(_testTarget, this.previousPeriodSupply.selector)) == previousPeriodSupply); require(uint128(delegateGet(_testTarget, this.currentPeriodSupply.selector)) == currentPeriodSupply); } } contract NuCypherToken is ERC20, ERC20Detailed('NuCypher', 'NU', 18) { /** * @notice Set amount of tokens * @param _totalSupplyOfTokens Total number of tokens */ constructor (uint256 _totalSupplyOfTokens) { _mint(msg.sender, _totalSupplyOfTokens); } /** * @notice Approves and then calls the receiving contract * * @dev call the receiveApproval function on the contract you want to be notified. * receiveApproval(address _from, uint256 _value, address _tokenContract, bytes _extraData) */ function approveAndCall(address _spender, uint256 _value, bytes calldata _extraData) external returns (bool success) { approve(_spender, _value); TokenRecipient(_spender).receiveApproval(msg.sender, _value, address(this), _extraData); return true; } } contract StakingEscrow is Issuer, IERC900History { using AdditionalMath for uint256; using AdditionalMath for uint16; using Bits for uint256; using SafeMath for uint256; using Snapshot for uint128[]; using SafeERC20 for NuCypherToken; event Deposited(address indexed staker, uint256 value, uint16 periods); event Locked(address indexed staker, uint256 value, uint16 firstPeriod, uint16 periods); event Divided( address indexed staker, uint256 oldValue, uint16 lastPeriod, uint256 newValue, uint16 periods ); event Merged(address indexed staker, uint256 value1, uint256 value2, uint16 lastPeriod); event Prolonged(address indexed staker, uint256 value, uint16 lastPeriod, uint16 periods); event Withdrawn(address indexed staker, uint256 value); event CommitmentMade(address indexed staker, uint16 indexed period, uint256 value); event Minted(address indexed staker, uint16 indexed period, uint256 value); event Slashed(address indexed staker, uint256 penalty, address indexed investigator, uint256 reward); event ReStakeSet(address indexed staker, bool reStake); event ReStakeLocked(address indexed staker, uint16 lockUntilPeriod); event WorkerBonded(address indexed staker, address indexed worker, uint16 indexed startPeriod); event WorkMeasurementSet(address indexed staker, bool measureWork); event WindDownSet(address indexed staker, bool windDown); event SnapshotSet(address indexed staker, bool snapshotsEnabled); struct SubStakeInfo { uint16 firstPeriod; uint16 lastPeriod; uint16 periods; uint128 lockedValue; } struct Downtime { uint16 startPeriod; uint16 endPeriod; } struct StakerInfo { uint256 value; /* * Stores periods that are committed but not yet rewarded. * In order to optimize storage, only two values are used instead of an array. * commitToNextPeriod() method invokes mint() method so there can only be two committed * periods that are not yet rewarded: the current and the next periods. */ uint16 currentCommittedPeriod; uint16 nextCommittedPeriod; uint16 lastCommittedPeriod; uint16 lockReStakeUntilPeriod; uint256 completedWork; uint16 workerStartPeriod; // period when worker was bonded address worker; uint256 flags; // uint256 to acquire whole slot and minimize operations on it uint256 reservedSlot1; uint256 reservedSlot2; uint256 reservedSlot3; uint256 reservedSlot4; uint256 reservedSlot5; Downtime[] pastDowntime; SubStakeInfo[] subStakes; uint128[] history; } // used only for upgrading uint16 internal constant RESERVED_PERIOD = 0; uint16 internal constant MAX_CHECKED_VALUES = 5; // to prevent high gas consumption in loops for slashing uint16 public constant MAX_SUB_STAKES = 30; uint16 internal constant MAX_UINT16 = 65535; // indices for flags uint8 internal constant RE_STAKE_DISABLED_INDEX = 0; uint8 internal constant WIND_DOWN_INDEX = 1; uint8 internal constant MEASURE_WORK_INDEX = 2; uint8 internal constant SNAPSHOTS_DISABLED_INDEX = 3; uint16 public immutable minLockedPeriods; uint16 public immutable minWorkerPeriods; uint256 public immutable minAllowableLockedTokens; uint256 public immutable maxAllowableLockedTokens; bool public immutable isTestContract; mapping (address => StakerInfo) public stakerInfo; address[] public stakers; mapping (address => address) public stakerFromWorker; mapping (uint16 => uint256) public lockedPerPeriod; uint128[] public balanceHistory; PolicyManagerInterface public policyManager; AdjudicatorInterface public adjudicator; WorkLockInterface public workLock; /** * @notice Constructor sets address of token contract and coefficients for minting * @param _token Token contract * @param _hoursPerPeriod Size of period in hours * @param _issuanceDecayCoefficient (d) Coefficient which modifies the rate at which the maximum issuance decays, * only applicable to Phase 2. d = 365 * half-life / LOG2 where default half-life = 2. * See Equation 10 in Staking Protocol & Economics paper * @param _lockDurationCoefficient1 (k1) Numerator of the coefficient which modifies the extent * to which a stake's lock duration affects the subsidy it receives. Affects stakers differently. * Applicable to Phase 1 and Phase 2. k1 = k2 * small_stake_multiplier where default small_stake_multiplier = 0.5. * See Equation 8 in Staking Protocol & Economics paper. * @param _lockDurationCoefficient2 (k2) Denominator of the coefficient which modifies the extent * to which a stake's lock duration affects the subsidy it receives. Affects stakers differently. * Applicable to Phase 1 and Phase 2. k2 = maximum_rewarded_periods / (1 - small_stake_multiplier) * where default maximum_rewarded_periods = 365 and default small_stake_multiplier = 0.5. * See Equation 8 in Staking Protocol & Economics paper. * @param _maximumRewardedPeriods (kmax) Number of periods beyond which a stake's lock duration * no longer increases the subsidy it receives. kmax = reward_saturation * 365 where default reward_saturation = 1. * See Equation 8 in Staking Protocol & Economics paper. * @param _firstPhaseTotalSupply Total supply for the first phase * @param _firstPhaseMaxIssuance (Imax) Maximum number of new tokens minted per period during Phase 1. * See Equation 7 in Staking Protocol & Economics paper. * @param _minLockedPeriods Min amount of periods during which tokens can be locked * @param _minAllowableLockedTokens Min amount of tokens that can be locked * @param _maxAllowableLockedTokens Max amount of tokens that can be locked * @param _minWorkerPeriods Min amount of periods while a worker can't be changed * @param _isTestContract True if contract is only for tests */ constructor( NuCypherToken _token, uint32 _hoursPerPeriod, uint256 _issuanceDecayCoefficient, uint256 _lockDurationCoefficient1, uint256 _lockDurationCoefficient2, uint16 _maximumRewardedPeriods, uint256 _firstPhaseTotalSupply, uint256 _firstPhaseMaxIssuance, uint16 _minLockedPeriods, uint256 _minAllowableLockedTokens, uint256 _maxAllowableLockedTokens, uint16 _minWorkerPeriods, bool _isTestContract ) Issuer( _token, _hoursPerPeriod, _issuanceDecayCoefficient, _lockDurationCoefficient1, _lockDurationCoefficient2, _maximumRewardedPeriods, _firstPhaseTotalSupply, _firstPhaseMaxIssuance ) { // constant `1` in the expression `_minLockedPeriods > 1` uses to simplify the `lock` method require(_minLockedPeriods > 1 && _maxAllowableLockedTokens != 0); minLockedPeriods = _minLockedPeriods; minAllowableLockedTokens = _minAllowableLockedTokens; maxAllowableLockedTokens = _maxAllowableLockedTokens; minWorkerPeriods = _minWorkerPeriods; isTestContract = _isTestContract; } /** * @dev Checks the existence of a staker in the contract */ modifier onlyStaker() { StakerInfo storage info = stakerInfo[msg.sender]; require(info.value > 0 || info.nextCommittedPeriod != 0); _; } //------------------------Initialization------------------------ /** * @notice Set policy manager address */ function setPolicyManager(PolicyManagerInterface _policyManager) external onlyOwner { // Policy manager can be set only once require(address(policyManager) == address(0)); // This escrow must be the escrow for the new policy manager require(_policyManager.escrow() == address(this)); policyManager = _policyManager; } /** * @notice Set adjudicator address */ function setAdjudicator(AdjudicatorInterface _adjudicator) external onlyOwner { // Adjudicator can be set only once require(address(adjudicator) == address(0)); // This escrow must be the escrow for the new adjudicator require(_adjudicator.escrow() == address(this)); adjudicator = _adjudicator; } /** * @notice Set worklock address */ function setWorkLock(WorkLockInterface _workLock) external onlyOwner { // WorkLock can be set only once require(address(workLock) == address(0) || isTestContract); // This escrow must be the escrow for the new worklock require(_workLock.escrow() == address(this)); workLock = _workLock; } //------------------------Main getters------------------------ /** * @notice Get all tokens belonging to the staker */ function getAllTokens(address _staker) external view returns (uint256) { return stakerInfo[_staker].value; } /** * @notice Get all flags for the staker */ function getFlags(address _staker) external view returns ( bool windDown, bool reStake, bool measureWork, bool snapshots ) { StakerInfo storage info = stakerInfo[_staker]; windDown = info.flags.bitSet(WIND_DOWN_INDEX); reStake = !info.flags.bitSet(RE_STAKE_DISABLED_INDEX); measureWork = info.flags.bitSet(MEASURE_WORK_INDEX); snapshots = !info.flags.bitSet(SNAPSHOTS_DISABLED_INDEX); } /** * @notice Get the start period. Use in the calculation of the last period of the sub stake * @param _info Staker structure * @param _currentPeriod Current period */ function getStartPeriod(StakerInfo storage _info, uint16 _currentPeriod) internal view returns (uint16) { // if the next period (after current) is committed if (_info.flags.bitSet(WIND_DOWN_INDEX) && _info.nextCommittedPeriod > _currentPeriod) { return _currentPeriod + 1; } return _currentPeriod; } /** * @notice Get the last period of the sub stake * @param _subStake Sub stake structure * @param _startPeriod Pre-calculated start period */ function getLastPeriodOfSubStake(SubStakeInfo storage _subStake, uint16 _startPeriod) internal view returns (uint16) { if (_subStake.lastPeriod != 0) { return _subStake.lastPeriod; } uint32 lastPeriod = uint32(_startPeriod) + _subStake.periods; if (lastPeriod > uint32(MAX_UINT16)) { return MAX_UINT16; } return uint16(lastPeriod); } /** * @notice Get the last period of the sub stake * @param _staker Staker * @param _index Stake index */ function getLastPeriodOfSubStake(address _staker, uint256 _index) public view returns (uint16) { StakerInfo storage info = stakerInfo[_staker]; SubStakeInfo storage subStake = info.subStakes[_index]; uint16 startPeriod = getStartPeriod(info, getCurrentPeriod()); return getLastPeriodOfSubStake(subStake, startPeriod); } /** * @notice Get the value of locked tokens for a staker in a specified period * @dev Information may be incorrect for rewarded or not committed surpassed period * @param _info Staker structure * @param _currentPeriod Current period * @param _period Next period */ function getLockedTokens(StakerInfo storage _info, uint16 _currentPeriod, uint16 _period) internal view returns (uint256 lockedValue) { lockedValue = 0; uint16 startPeriod = getStartPeriod(_info, _currentPeriod); for (uint256 i = 0; i < _info.subStakes.length; i++) { SubStakeInfo storage subStake = _info.subStakes[i]; if (subStake.firstPeriod <= _period && getLastPeriodOfSubStake(subStake, startPeriod) >= _period) { lockedValue += subStake.lockedValue; } } } /** * @notice Get the value of locked tokens for a staker in a future period * @dev This function is used by PreallocationEscrow so its signature can't be updated. * @param _staker Staker * @param _periods Amount of periods that will be added to the current period */ function getLockedTokens(address _staker, uint16 _periods) external view returns (uint256 lockedValue) { StakerInfo storage info = stakerInfo[_staker]; uint16 currentPeriod = getCurrentPeriod(); uint16 nextPeriod = currentPeriod.add16(_periods); return getLockedTokens(info, currentPeriod, nextPeriod); } /** * @notice Get the last committed staker's period * @param _staker Staker */ function getLastCommittedPeriod(address _staker) public view returns (uint16) { StakerInfo storage info = stakerInfo[_staker]; return info.nextCommittedPeriod != 0 ? info.nextCommittedPeriod : info.lastCommittedPeriod; } /** * @notice Get the value of locked tokens for active stakers in (getCurrentPeriod() + _periods) period * as well as stakers and their locked tokens * @param _periods Amount of periods for locked tokens calculation * @param _startIndex Start index for looking in stakers array * @param _maxStakers Max stakers for looking, if set 0 then all will be used * @return allLockedTokens Sum of locked tokens for active stakers * @return activeStakers Array of stakers and their locked tokens. Stakers addresses stored as uint256 * @dev Note that activeStakers[0] in an array of uint256, but you want addresses. Careful when used directly! */ function getActiveStakers(uint16 _periods, uint256 _startIndex, uint256 _maxStakers) external view returns (uint256 allLockedTokens, uint256[2][] memory activeStakers) { require(_periods > 0); uint256 endIndex = stakers.length; require(_startIndex < endIndex); if (_maxStakers != 0 && _startIndex + _maxStakers < endIndex) { endIndex = _startIndex + _maxStakers; } activeStakers = new uint256[2][](endIndex - _startIndex); allLockedTokens = 0; uint256 resultIndex = 0; uint16 currentPeriod = getCurrentPeriod(); uint16 nextPeriod = currentPeriod.add16(_periods); for (uint256 i = _startIndex; i < endIndex; i++) { address staker = stakers[i]; StakerInfo storage info = stakerInfo[staker]; if (info.currentCommittedPeriod != currentPeriod && info.nextCommittedPeriod != currentPeriod) { continue; } uint256 lockedTokens = getLockedTokens(info, currentPeriod, nextPeriod); if (lockedTokens != 0) { activeStakers[resultIndex][0] = uint256(staker); activeStakers[resultIndex++][1] = lockedTokens; allLockedTokens += lockedTokens; } } assembly { mstore(activeStakers, resultIndex) } } /** * @notice Checks if `reStake` parameter is available for changing * @param _staker Staker */ function isReStakeLocked(address _staker) public view returns (bool) { return getCurrentPeriod() < stakerInfo[_staker].lockReStakeUntilPeriod; } /** * @notice Get worker using staker's address */ function getWorkerFromStaker(address _staker) external view returns (address) { return stakerInfo[_staker].worker; } /** * @notice Get work that completed by the staker */ function getCompletedWork(address _staker) external view returns (uint256) { return stakerInfo[_staker].completedWork; } /** * @notice Find index of downtime structure that includes specified period * @dev If specified period is outside all downtime periods, the length of the array will be returned * @param _staker Staker * @param _period Specified period number */ function findIndexOfPastDowntime(address _staker, uint16 _period) external view returns (uint256 index) { StakerInfo storage info = stakerInfo[_staker]; for (index = 0; index < info.pastDowntime.length; index++) { if (_period <= info.pastDowntime[index].endPeriod) { return index; } } } //------------------------Main methods------------------------ /** * @notice Start or stop measuring the work of a staker * @param _staker Staker * @param _measureWork Value for `measureWork` parameter * @return Work that was previously done */ function setWorkMeasurement(address _staker, bool _measureWork) external returns (uint256) { require(msg.sender == address(workLock)); StakerInfo storage info = stakerInfo[_staker]; if (info.flags.bitSet(MEASURE_WORK_INDEX) == _measureWork) { return info.completedWork; } info.flags = info.flags.toggleBit(MEASURE_WORK_INDEX); emit WorkMeasurementSet(_staker, _measureWork); return info.completedWork; } /** * @notice Bond worker * @param _worker Worker address. Must be a real address, not a contract */ function bondWorker(address _worker) external onlyStaker { StakerInfo storage info = stakerInfo[msg.sender]; // Specified worker is already bonded with this staker require(_worker != info.worker); uint16 currentPeriod = getCurrentPeriod(); if (info.worker != address(0)) { // If this staker had a worker ... // Check that enough time has passed to change it require(currentPeriod >= info.workerStartPeriod.add16(minWorkerPeriods)); // Remove the old relation "worker->staker" stakerFromWorker[info.worker] = address(0); } if (_worker != address(0)) { // Specified worker is already in use require(stakerFromWorker[_worker] == address(0)); // Specified worker is a staker require(stakerInfo[_worker].subStakes.length == 0 || _worker == msg.sender); // Set new worker->staker relation stakerFromWorker[_worker] = msg.sender; } // Bond new worker (or unbond if _worker == address(0)) info.worker = _worker; info.workerStartPeriod = currentPeriod; emit WorkerBonded(msg.sender, _worker, currentPeriod); } /** * @notice Set `reStake` parameter. If true then all staking rewards will be added to locked stake * Only if this parameter is not locked * @param _reStake Value for parameter */ function setReStake(bool _reStake) external { require(!isReStakeLocked(msg.sender)); StakerInfo storage info = stakerInfo[msg.sender]; if (info.flags.bitSet(RE_STAKE_DISABLED_INDEX) == !_reStake) { return; } info.flags = info.flags.toggleBit(RE_STAKE_DISABLED_INDEX); emit ReStakeSet(msg.sender, _reStake); } /** * @notice Lock `reStake` parameter. Only if this parameter is not locked * @param _lockReStakeUntilPeriod Can't change `reStake` value until this period */ function lockReStake(uint16 _lockReStakeUntilPeriod) external { require(!isReStakeLocked(msg.sender) && _lockReStakeUntilPeriod > getCurrentPeriod()); stakerInfo[msg.sender].lockReStakeUntilPeriod = _lockReStakeUntilPeriod; emit ReStakeLocked(msg.sender, _lockReStakeUntilPeriod); } /** * @notice Deposit tokens from WorkLock contract * @param _staker Staker address * @param _value Amount of tokens to deposit * @param _periods Amount of periods during which tokens will be locked */ function depositFromWorkLock( address _staker, uint256 _value, uint16 _periods ) external { require(msg.sender == address(workLock)); StakerInfo storage info = stakerInfo[_staker]; if (!info.flags.bitSet(WIND_DOWN_INDEX) && info.subStakes.length == 0) { info.flags = info.flags.toggleBit(WIND_DOWN_INDEX); emit WindDownSet(_staker, true); } deposit(_staker, msg.sender, MAX_SUB_STAKES, _value, _periods); } /** * @notice Set `windDown` parameter. * If true then stake's duration will be decreasing in each period with `commitToNextPeriod()` * @param _windDown Value for parameter */ function setWindDown(bool _windDown) external { StakerInfo storage info = stakerInfo[msg.sender]; if (info.flags.bitSet(WIND_DOWN_INDEX) == _windDown) { return; } info.flags = info.flags.toggleBit(WIND_DOWN_INDEX); emit WindDownSet(msg.sender, _windDown); // duration adjustment if next period is committed uint16 nextPeriod = getCurrentPeriod() + 1; if (info.nextCommittedPeriod != nextPeriod) { return; } // adjust sub-stakes duration for the new value of winding down parameter for (uint256 index = 0; index < info.subStakes.length; index++) { SubStakeInfo storage subStake = info.subStakes[index]; // sub-stake does not have fixed last period when winding down is disabled if (!_windDown && subStake.lastPeriod == nextPeriod) { subStake.lastPeriod = 0; subStake.periods = 1; continue; } // this sub-stake is no longer affected by winding down parameter if (subStake.lastPeriod != 0 || subStake.periods == 0) { continue; } subStake.periods = _windDown ? subStake.periods - 1 : subStake.periods + 1; if (subStake.periods == 0) { subStake.lastPeriod = nextPeriod; } } } /** * @notice Activate/deactivate taking snapshots of balances * @param _enableSnapshots True to activate snapshots, False to deactivate */ function setSnapshots(bool _enableSnapshots) external { StakerInfo storage info = stakerInfo[msg.sender]; if (info.flags.bitSet(SNAPSHOTS_DISABLED_INDEX) == !_enableSnapshots) { return; } uint256 lastGlobalBalance = uint256(balanceHistory.lastValue()); if(_enableSnapshots){ info.history.addSnapshot(info.value); balanceHistory.addSnapshot(lastGlobalBalance + info.value); } else { info.history.addSnapshot(0); balanceHistory.addSnapshot(lastGlobalBalance - info.value); } info.flags = info.flags.toggleBit(SNAPSHOTS_DISABLED_INDEX); emit SnapshotSet(msg.sender, _enableSnapshots); } /** * @notice Adds a new snapshot to both the staker and global balance histories, * assuming the staker's balance was already changed * @param _info Reference to affected staker's struct * @param _addition Variance in balance. It can be positive or negative. */ function addSnapshot(StakerInfo storage _info, int256 _addition) internal { if(!_info.flags.bitSet(SNAPSHOTS_DISABLED_INDEX)){ _info.history.addSnapshot(_info.value); uint256 lastGlobalBalance = uint256(balanceHistory.lastValue()); balanceHistory.addSnapshot(lastGlobalBalance.addSigned(_addition)); } } /** * @notice Batch deposit. Allowed only initial deposit for each staker * @param _stakers Stakers * @param _numberOfSubStakes Number of sub-stakes which belong to staker in _values and _periods arrays * @param _values Amount of tokens to deposit for each staker * @param _periods Amount of periods during which tokens will be locked for each staker */ function batchDeposit( address[] calldata _stakers, uint256[] calldata _numberOfSubStakes, uint256[] calldata _values, uint16[] calldata _periods ) external { uint256 subStakesLength = _values.length; require(_stakers.length != 0 && _stakers.length == _numberOfSubStakes.length && subStakesLength >= _stakers.length && _periods.length == subStakesLength); uint16 previousPeriod = getCurrentPeriod() - 1; uint16 nextPeriod = previousPeriod + 2; uint256 sumValue = 0; uint256 j = 0; for (uint256 i = 0; i < _stakers.length; i++) { address staker = _stakers[i]; uint256 numberOfSubStakes = _numberOfSubStakes[i]; uint256 endIndex = j + numberOfSubStakes; require(numberOfSubStakes > 0 && subStakesLength >= endIndex); StakerInfo storage info = stakerInfo[staker]; require(info.subStakes.length == 0 && !info.flags.bitSet(SNAPSHOTS_DISABLED_INDEX)); // A staker can't be a worker for another staker require(stakerFromWorker[staker] == address(0)); stakers.push(staker); policyManager.register(staker, previousPeriod); for (; j < endIndex; j++) { uint256 value = _values[j]; uint16 periods = _periods[j]; require(value >= minAllowableLockedTokens && periods >= minLockedPeriods); info.value = info.value.add(value); info.subStakes.push(SubStakeInfo(nextPeriod, 0, periods, uint128(value))); sumValue = sumValue.add(value); emit Deposited(staker, value, periods); emit Locked(staker, value, nextPeriod, periods); } require(info.value <= maxAllowableLockedTokens); info.history.addSnapshot(info.value); } require(j == subStakesLength); uint256 lastGlobalBalance = uint256(balanceHistory.lastValue()); balanceHistory.addSnapshot(lastGlobalBalance + sumValue); token.safeTransferFrom(msg.sender, address(this), sumValue); } /** * @notice Implementation of the receiveApproval(address,uint256,address,bytes) method * (see NuCypherToken contract). Deposit all tokens that were approved to transfer * @param _from Staker * @param _value Amount of tokens to deposit * @param _tokenContract Token contract address * @notice (param _extraData) Amount of periods during which tokens will be locked */ function receiveApproval( address _from, uint256 _value, address _tokenContract, bytes calldata /* _extraData */ ) external { require(_tokenContract == address(token) && msg.sender == address(token)); // Copy first 32 bytes from _extraData, according to calldata memory layout: // // 0x00: method signature 4 bytes // 0x04: _from 32 bytes after encoding // 0x24: _value 32 bytes after encoding // 0x44: _tokenContract 32 bytes after encoding // 0x64: _extraData pointer 32 bytes. Value must be 0x80 (offset of _extraData wrt to 1st parameter) // 0x84: _extraData length 32 bytes // 0xA4: _extraData data Length determined by previous variable // // See https://solidity.readthedocs.io/en/latest/abi-spec.html#examples uint256 payloadSize; uint256 payload; assembly { payloadSize := calldataload(0x84) payload := calldataload(0xA4) } payload = payload >> 8*(32 - payloadSize); deposit(_from, _from, MAX_SUB_STAKES, _value, uint16(payload)); } /** * @notice Deposit tokens and create new sub-stake. Use this method to become a staker * @param _staker Staker * @param _value Amount of tokens to deposit * @param _periods Amount of periods during which tokens will be locked */ function deposit(address _staker, uint256 _value, uint16 _periods) external { deposit(_staker, msg.sender, MAX_SUB_STAKES, _value, _periods); } /** * @notice Deposit tokens and increase lock amount of an existing sub-stake * @dev This is preferable way to stake tokens because will be fewer active sub-stakes in the result * @param _index Index of the sub stake * @param _value Amount of tokens which will be locked */ function depositAndIncrease(uint256 _index, uint256 _value) external onlyStaker { require(_index < MAX_SUB_STAKES); deposit(msg.sender, msg.sender, _index, _value, 0); } /** * @notice Deposit tokens * @dev Specify either index and zero periods (for an existing sub-stake) * or index >= MAX_SUB_STAKES and real value for periods (for a new sub-stake), not both * @param _staker Staker * @param _payer Owner of tokens * @param _index Index of the sub stake * @param _value Amount of tokens to deposit * @param _periods Amount of periods during which tokens will be locked */ function deposit(address _staker, address _payer, uint256 _index, uint256 _value, uint16 _periods) internal { require(_value != 0); StakerInfo storage info = stakerInfo[_staker]; // A staker can't be a worker for another staker require(stakerFromWorker[_staker] == address(0) || stakerFromWorker[_staker] == info.worker); // initial stake of the staker if (info.subStakes.length == 0) { stakers.push(_staker); policyManager.register(_staker, getCurrentPeriod() - 1); } token.safeTransferFrom(_payer, address(this), _value); info.value += _value; lock(_staker, _index, _value, _periods); addSnapshot(info, int256(_value)); if (_index >= MAX_SUB_STAKES) { emit Deposited(_staker, _value, _periods); } else { uint16 lastPeriod = getLastPeriodOfSubStake(_staker, _index); emit Deposited(_staker, _value, lastPeriod - getCurrentPeriod()); } } /** * @notice Lock some tokens as a new sub-stake * @param _value Amount of tokens which will be locked * @param _periods Amount of periods during which tokens will be locked */ function lockAndCreate(uint256 _value, uint16 _periods) external onlyStaker { lock(msg.sender, MAX_SUB_STAKES, _value, _periods); } /** * @notice Increase lock amount of an existing sub-stake * @param _index Index of the sub-stake * @param _value Amount of tokens which will be locked */ function lockAndIncrease(uint256 _index, uint256 _value) external onlyStaker { require(_index < MAX_SUB_STAKES); lock(msg.sender, _index, _value, 0); } /** * @notice Lock some tokens as a stake * @dev Specify either index and zero periods (for an existing sub-stake) * or index >= MAX_SUB_STAKES and real value for periods (for a new sub-stake), not both * @param _staker Staker * @param _index Index of the sub stake * @param _value Amount of tokens which will be locked * @param _periods Amount of periods during which tokens will be locked */ function lock(address _staker, uint256 _index, uint256 _value, uint16 _periods) internal { if (_index < MAX_SUB_STAKES) { require(_value > 0); } else { require(_value >= minAllowableLockedTokens && _periods >= minLockedPeriods); } uint16 currentPeriod = getCurrentPeriod(); uint16 nextPeriod = currentPeriod + 1; StakerInfo storage info = stakerInfo[_staker]; uint256 lockedTokens = getLockedTokens(info, currentPeriod, nextPeriod); uint256 requestedLockedTokens = _value.add(lockedTokens); require(requestedLockedTokens <= info.value && requestedLockedTokens <= maxAllowableLockedTokens); // next period is committed if (info.nextCommittedPeriod == nextPeriod) { lockedPerPeriod[nextPeriod] += _value; emit CommitmentMade(_staker, nextPeriod, _value); } // if index was provided then increase existing sub-stake if (_index < MAX_SUB_STAKES) { lockAndIncrease(info, currentPeriod, nextPeriod, _staker, _index, _value); // otherwise create new } else { lockAndCreate(info, nextPeriod, _staker, _value, _periods); } } /** * @notice Lock some tokens as a new sub-stake * @param _info Staker structure * @param _nextPeriod Next period * @param _staker Staker * @param _value Amount of tokens which will be locked * @param _periods Amount of periods during which tokens will be locked */ function lockAndCreate( StakerInfo storage _info, uint16 _nextPeriod, address _staker, uint256 _value, uint16 _periods ) internal { uint16 duration = _periods; // if winding down is enabled and next period is committed // then sub-stakes duration were decreased if (_info.nextCommittedPeriod == _nextPeriod && _info.flags.bitSet(WIND_DOWN_INDEX)) { duration -= 1; } saveSubStake(_info, _nextPeriod, 0, duration, _value); emit Locked(_staker, _value, _nextPeriod, _periods); } /** * @notice Increase lock amount of an existing sub-stake * @dev Probably will be created a new sub-stake but it will be active only one period * @param _info Staker structure * @param _currentPeriod Current period * @param _nextPeriod Next period * @param _staker Staker * @param _index Index of the sub-stake * @param _value Amount of tokens which will be locked */ function lockAndIncrease( StakerInfo storage _info, uint16 _currentPeriod, uint16 _nextPeriod, address _staker, uint256 _index, uint256 _value ) internal { SubStakeInfo storage subStake = _info.subStakes[_index]; (, uint16 lastPeriod) = checkLastPeriodOfSubStake(_info, subStake, _currentPeriod); // create temporary sub-stake for current or previous committed periods // to leave locked amount in this period unchanged if (_info.currentCommittedPeriod != 0 && _info.currentCommittedPeriod <= _currentPeriod || _info.nextCommittedPeriod != 0 && _info.nextCommittedPeriod <= _currentPeriod) { saveSubStake(_info, subStake.firstPeriod, _currentPeriod, 0, subStake.lockedValue); } subStake.lockedValue += uint128(_value); // all new locks should start from the next period subStake.firstPeriod = _nextPeriod; emit Locked(_staker, _value, _nextPeriod, lastPeriod - _currentPeriod); } /** * @notice Checks that last period of sub-stake is greater than the current period * @param _info Staker structure * @param _subStake Sub-stake structure * @param _currentPeriod Current period * @return startPeriod Start period. Use in the calculation of the last period of the sub stake * @return lastPeriod Last period of the sub stake */ function checkLastPeriodOfSubStake( StakerInfo storage _info, SubStakeInfo storage _subStake, uint16 _currentPeriod ) internal view returns (uint16 startPeriod, uint16 lastPeriod) { startPeriod = getStartPeriod(_info, _currentPeriod); lastPeriod = getLastPeriodOfSubStake(_subStake, startPeriod); // The sub stake must be active at least in the next period require(lastPeriod > _currentPeriod); } /** * @notice Save sub stake. First tries to override inactive sub stake * @dev Inactive sub stake means that last period of sub stake has been surpassed and already rewarded * @param _info Staker structure * @param _firstPeriod First period of the sub stake * @param _lastPeriod Last period of the sub stake * @param _periods Duration of the sub stake in periods * @param _lockedValue Amount of locked tokens */ function saveSubStake( StakerInfo storage _info, uint16 _firstPeriod, uint16 _lastPeriod, uint16 _periods, uint256 _lockedValue ) internal { for (uint256 i = 0; i < _info.subStakes.length; i++) { SubStakeInfo storage subStake = _info.subStakes[i]; if (subStake.lastPeriod != 0 && (_info.currentCommittedPeriod == 0 || subStake.lastPeriod < _info.currentCommittedPeriod) && (_info.nextCommittedPeriod == 0 || subStake.lastPeriod < _info.nextCommittedPeriod)) { subStake.firstPeriod = _firstPeriod; subStake.lastPeriod = _lastPeriod; subStake.periods = _periods; subStake.lockedValue = uint128(_lockedValue); return; } } require(_info.subStakes.length < MAX_SUB_STAKES); _info.subStakes.push(SubStakeInfo(_firstPeriod, _lastPeriod, _periods, uint128(_lockedValue))); } /** * @notice Divide sub stake into two parts * @param _index Index of the sub stake * @param _newValue New sub stake value * @param _periods Amount of periods for extending sub stake */ function divideStake(uint256 _index, uint256 _newValue, uint16 _periods) external onlyStaker { StakerInfo storage info = stakerInfo[msg.sender]; require(_newValue >= minAllowableLockedTokens && _periods > 0); SubStakeInfo storage subStake = info.subStakes[_index]; uint16 currentPeriod = getCurrentPeriod(); (, uint16 lastPeriod) = checkLastPeriodOfSubStake(info, subStake, currentPeriod); uint256 oldValue = subStake.lockedValue; subStake.lockedValue = uint128(oldValue.sub(_newValue)); require(subStake.lockedValue >= minAllowableLockedTokens); uint16 requestedPeriods = subStake.periods.add16(_periods); saveSubStake(info, subStake.firstPeriod, 0, requestedPeriods, _newValue); emit Divided(msg.sender, oldValue, lastPeriod, _newValue, _periods); emit Locked(msg.sender, _newValue, subStake.firstPeriod, requestedPeriods); } /** * @notice Prolong active sub stake * @param _index Index of the sub stake * @param _periods Amount of periods for extending sub stake */ function prolongStake(uint256 _index, uint16 _periods) external onlyStaker { StakerInfo storage info = stakerInfo[msg.sender]; // Incorrect parameters require(_periods > 0); SubStakeInfo storage subStake = info.subStakes[_index]; uint16 currentPeriod = getCurrentPeriod(); (uint16 startPeriod, uint16 lastPeriod) = checkLastPeriodOfSubStake(info, subStake, currentPeriod); subStake.periods = subStake.periods.add16(_periods); // if the sub stake ends in the next committed period then reset the `lastPeriod` field if (lastPeriod == startPeriod) { subStake.lastPeriod = 0; } // The extended sub stake must not be less than the minimum value require(uint32(lastPeriod - currentPeriod) + _periods >= minLockedPeriods); emit Locked(msg.sender, subStake.lockedValue, lastPeriod + 1, _periods); emit Prolonged(msg.sender, subStake.lockedValue, lastPeriod, _periods); } /** * @notice Merge two sub-stakes into one if their last periods are equal * @dev It's possible that both sub-stakes will be active after this transaction. * But only one of them will be active until next call `commitToNextPeriod` (in the next period) * @param _index1 Index of the first sub-stake * @param _index2 Index of the second sub-stake */ function mergeStake(uint256 _index1, uint256 _index2) external onlyStaker { require(_index1 != _index2); // must be different sub-stakes StakerInfo storage info = stakerInfo[msg.sender]; SubStakeInfo storage subStake1 = info.subStakes[_index1]; SubStakeInfo storage subStake2 = info.subStakes[_index2]; uint16 currentPeriod = getCurrentPeriod(); (, uint16 lastPeriod1) = checkLastPeriodOfSubStake(info, subStake1, currentPeriod); (, uint16 lastPeriod2) = checkLastPeriodOfSubStake(info, subStake2, currentPeriod); // both sub-stakes must have equal last period to be mergeable require(lastPeriod1 == lastPeriod2); emit Merged(msg.sender, subStake1.lockedValue, subStake2.lockedValue, lastPeriod1); if (subStake1.firstPeriod == subStake2.firstPeriod) { subStake1.lockedValue += subStake2.lockedValue; subStake2.lastPeriod = 1; subStake2.periods = 0; } else if (subStake1.firstPeriod > subStake2.firstPeriod) { subStake1.lockedValue += subStake2.lockedValue; subStake2.lastPeriod = subStake1.firstPeriod - 1; subStake2.periods = 0; } else { subStake2.lockedValue += subStake1.lockedValue; subStake1.lastPeriod = subStake2.firstPeriod - 1; subStake1.periods = 0; } } /** * @notice Remove unused sub-stake to decrease gas cost for several methods */ function removeUnusedSubStake(uint16 _index) external onlyStaker { StakerInfo storage info = stakerInfo[msg.sender]; uint256 lastIndex = info.subStakes.length - 1; SubStakeInfo storage subStake = info.subStakes[_index]; require(subStake.lastPeriod != 0 && (info.currentCommittedPeriod == 0 || subStake.lastPeriod < info.currentCommittedPeriod) && (info.nextCommittedPeriod == 0 || subStake.lastPeriod < info.nextCommittedPeriod)); if (_index != lastIndex) { SubStakeInfo storage lastSubStake = info.subStakes[lastIndex]; subStake.firstPeriod = lastSubStake.firstPeriod; subStake.lastPeriod = lastSubStake.lastPeriod; subStake.periods = lastSubStake.periods; subStake.lockedValue = lastSubStake.lockedValue; } info.subStakes.pop(); } /** * @notice Withdraw available amount of tokens to staker * @param _value Amount of tokens to withdraw */ function withdraw(uint256 _value) external onlyStaker { uint16 currentPeriod = getCurrentPeriod(); uint16 nextPeriod = currentPeriod + 1; StakerInfo storage info = stakerInfo[msg.sender]; // the max locked tokens in most cases will be in the current period // but when the staker locks more then we should use the next period uint256 lockedTokens = Math.max(getLockedTokens(info, currentPeriod, nextPeriod), getLockedTokens(info, currentPeriod, currentPeriod)); require(_value <= info.value.sub(lockedTokens)); info.value -= _value; addSnapshot(info, - int256(_value)); token.safeTransfer(msg.sender, _value); emit Withdrawn(msg.sender, _value); // unbond worker if staker withdraws last portion of NU if (info.value == 0 && info.nextCommittedPeriod == 0 && info.worker != address(0)) { stakerFromWorker[info.worker] = address(0); info.worker = address(0); emit WorkerBonded(msg.sender, address(0), currentPeriod); } } /** * @notice Make a commitment to the next period and mint for the previous period */ function commitToNextPeriod() external isInitialized { address staker = stakerFromWorker[msg.sender]; StakerInfo storage info = stakerInfo[staker]; // Staker must have a stake to make a commitment require(info.value > 0); // Only worker with real address can make a commitment require(msg.sender == tx.origin); uint16 lastCommittedPeriod = getLastCommittedPeriod(staker); (uint16 processedPeriod1, uint16 processedPeriod2) = mint(staker); uint16 currentPeriod = getCurrentPeriod(); uint16 nextPeriod = currentPeriod + 1; // the period has already been committed if (info.nextCommittedPeriod == nextPeriod) { return; } uint256 lockedTokens = getLockedTokens(info, currentPeriod, nextPeriod); require(lockedTokens > 0); lockedPerPeriod[nextPeriod] += lockedTokens; info.currentCommittedPeriod = info.nextCommittedPeriod; info.nextCommittedPeriod = nextPeriod; decreaseSubStakesDuration(info, nextPeriod); // staker was inactive for several periods if (lastCommittedPeriod < currentPeriod) { info.pastDowntime.push(Downtime(lastCommittedPeriod + 1, currentPeriod)); } policyManager.ping(staker, processedPeriod1, processedPeriod2, nextPeriod); emit CommitmentMade(staker, nextPeriod, lockedTokens); } /** * @notice Decrease sub-stakes duration if `windDown` is enabled */ function decreaseSubStakesDuration(StakerInfo storage _info, uint16 _nextPeriod) internal { if (!_info.flags.bitSet(WIND_DOWN_INDEX)) { return; } for (uint256 index = 0; index < _info.subStakes.length; index++) { SubStakeInfo storage subStake = _info.subStakes[index]; if (subStake.lastPeriod != 0 || subStake.periods == 0) { continue; } subStake.periods--; if (subStake.periods == 0) { subStake.lastPeriod = _nextPeriod; } } } /** * @notice Mint tokens for previous periods if staker locked their tokens and made a commitment */ function mint() external onlyStaker { // save last committed period to the storage if both periods will be empty after minting // because we won't be able to calculate last committed period // see getLastCommittedPeriod(address) StakerInfo storage info = stakerInfo[msg.sender]; uint16 previousPeriod = getCurrentPeriod() - 1; if (info.nextCommittedPeriod <= previousPeriod && info.nextCommittedPeriod != 0) { info.lastCommittedPeriod = info.nextCommittedPeriod; } (uint16 processedPeriod1, uint16 processedPeriod2) = mint(msg.sender); if (processedPeriod1 != 0 || processedPeriod2 != 0) { policyManager.ping(msg.sender, processedPeriod1, processedPeriod2, 0); } } /** * @notice Mint tokens for previous periods if staker locked their tokens and made a commitment * @param _staker Staker * @return processedPeriod1 Processed period: currentCommittedPeriod or zero * @return processedPeriod2 Processed period: nextCommittedPeriod or zero */ function mint(address _staker) internal returns (uint16 processedPeriod1, uint16 processedPeriod2) { uint16 currentPeriod = getCurrentPeriod(); uint16 previousPeriod = currentPeriod - 1; StakerInfo storage info = stakerInfo[_staker]; if (info.nextCommittedPeriod == 0 || info.currentCommittedPeriod == 0 && info.nextCommittedPeriod > previousPeriod || info.currentCommittedPeriod > previousPeriod) { return (0, 0); } uint16 startPeriod = getStartPeriod(info, currentPeriod); uint256 reward = 0; bool reStake = !info.flags.bitSet(RE_STAKE_DISABLED_INDEX); if (info.currentCommittedPeriod != 0) { reward = mint(info, info.currentCommittedPeriod, currentPeriod, startPeriod, reStake); processedPeriod1 = info.currentCommittedPeriod; info.currentCommittedPeriod = 0; if (reStake) { lockedPerPeriod[info.nextCommittedPeriod] += reward; } } if (info.nextCommittedPeriod <= previousPeriod) { reward += mint(info, info.nextCommittedPeriod, currentPeriod, startPeriod, reStake); processedPeriod2 = info.nextCommittedPeriod; info.nextCommittedPeriod = 0; } info.value += reward; if (info.flags.bitSet(MEASURE_WORK_INDEX)) { info.completedWork += reward; } addSnapshot(info, int256(reward)); emit Minted(_staker, previousPeriod, reward); } /** * @notice Calculate reward for one period * @param _info Staker structure * @param _mintingPeriod Period for minting calculation * @param _currentPeriod Current period * @param _startPeriod Pre-calculated start period */ function mint( StakerInfo storage _info, uint16 _mintingPeriod, uint16 _currentPeriod, uint16 _startPeriod, bool _reStake ) internal returns (uint256 reward) { reward = 0; for (uint256 i = 0; i < _info.subStakes.length; i++) { SubStakeInfo storage subStake = _info.subStakes[i]; uint16 lastPeriod = getLastPeriodOfSubStake(subStake, _startPeriod); if (subStake.firstPeriod <= _mintingPeriod && lastPeriod >= _mintingPeriod) { uint256 subStakeReward = mint( _currentPeriod, subStake.lockedValue, lockedPerPeriod[_mintingPeriod], lastPeriod.sub16(_mintingPeriod)); reward += subStakeReward; if (_reStake) { subStake.lockedValue += uint128(subStakeReward); } } } return reward; } //-------------------------Slashing------------------------- /** * @notice Slash the staker's stake and reward the investigator * @param _staker Staker's address * @param _penalty Penalty * @param _investigator Investigator * @param _reward Reward for the investigator */ function slashStaker( address _staker, uint256 _penalty, address _investigator, uint256 _reward ) public isInitialized { require(msg.sender == address(adjudicator)); require(_penalty > 0); StakerInfo storage info = stakerInfo[_staker]; if (info.value <= _penalty) { _penalty = info.value; } info.value -= _penalty; if (_reward > _penalty) { _reward = _penalty; } uint16 currentPeriod = getCurrentPeriod(); uint16 nextPeriod = currentPeriod + 1; uint16 startPeriod = getStartPeriod(info, currentPeriod); (uint256 currentLock, uint256 nextLock, uint256 currentAndNextLock, uint256 shortestSubStakeIndex) = getLockedTokensAndShortestSubStake(info, currentPeriod, nextPeriod, startPeriod); // Decrease the stake if amount of locked tokens in the current period more than staker has uint256 lockedTokens = currentLock + currentAndNextLock; if (info.value < lockedTokens) { decreaseSubStakes(info, lockedTokens - info.value, currentPeriod, startPeriod, shortestSubStakeIndex); } // Decrease the stake if amount of locked tokens in the next period more than staker has if (nextLock > 0) { lockedTokens = nextLock + currentAndNextLock - (currentAndNextLock > info.value ? currentAndNextLock - info.value : 0); if (info.value < lockedTokens) { decreaseSubStakes(info, lockedTokens - info.value, nextPeriod, startPeriod, MAX_SUB_STAKES); } } emit Slashed(_staker, _penalty, _investigator, _reward); if (_penalty > _reward) { unMint(_penalty - _reward); } // TODO change to withdrawal pattern (#1499) if (_reward > 0) { token.safeTransfer(_investigator, _reward); } addSnapshot(info, - int256(_penalty)); } /** * @notice Get the value of locked tokens for a staker in the current and the next period * and find the shortest sub stake * @param _info Staker structure * @param _currentPeriod Current period * @param _nextPeriod Next period * @param _startPeriod Pre-calculated start period * @return currentLock Amount of tokens that locked in the current period and unlocked in the next period * @return nextLock Amount of tokens that locked in the next period and not locked in the current period * @return currentAndNextLock Amount of tokens that locked in the current period and in the next period * @return shortestSubStakeIndex Index of the shortest sub stake */ function getLockedTokensAndShortestSubStake( StakerInfo storage _info, uint16 _currentPeriod, uint16 _nextPeriod, uint16 _startPeriod ) internal view returns ( uint256 currentLock, uint256 nextLock, uint256 currentAndNextLock, uint256 shortestSubStakeIndex ) { uint16 minDuration = MAX_UINT16; uint16 minLastPeriod = MAX_UINT16; shortestSubStakeIndex = MAX_SUB_STAKES; currentLock = 0; nextLock = 0; currentAndNextLock = 0; for (uint256 i = 0; i < _info.subStakes.length; i++) { SubStakeInfo storage subStake = _info.subStakes[i]; uint16 lastPeriod = getLastPeriodOfSubStake(subStake, _startPeriod); if (lastPeriod < subStake.firstPeriod) { continue; } if (subStake.firstPeriod <= _currentPeriod && lastPeriod >= _nextPeriod) { currentAndNextLock += subStake.lockedValue; } else if (subStake.firstPeriod <= _currentPeriod && lastPeriod >= _currentPeriod) { currentLock += subStake.lockedValue; } else if (subStake.firstPeriod <= _nextPeriod && lastPeriod >= _nextPeriod) { nextLock += subStake.lockedValue; } uint16 duration = lastPeriod - subStake.firstPeriod; if (subStake.firstPeriod <= _currentPeriod && lastPeriod >= _currentPeriod && (lastPeriod < minLastPeriod || lastPeriod == minLastPeriod && duration < minDuration)) { shortestSubStakeIndex = i; minDuration = duration; minLastPeriod = lastPeriod; } } } /** * @notice Decrease short sub stakes * @param _info Staker structure * @param _penalty Penalty rate * @param _decreasePeriod The period when the decrease begins * @param _startPeriod Pre-calculated start period * @param _shortestSubStakeIndex Index of the shortest period */ function decreaseSubStakes( StakerInfo storage _info, uint256 _penalty, uint16 _decreasePeriod, uint16 _startPeriod, uint256 _shortestSubStakeIndex ) internal { SubStakeInfo storage shortestSubStake = _info.subStakes[0]; uint16 minSubStakeLastPeriod = MAX_UINT16; uint16 minSubStakeDuration = MAX_UINT16; while(_penalty > 0) { if (_shortestSubStakeIndex < MAX_SUB_STAKES) { shortestSubStake = _info.subStakes[_shortestSubStakeIndex]; minSubStakeLastPeriod = getLastPeriodOfSubStake(shortestSubStake, _startPeriod); minSubStakeDuration = minSubStakeLastPeriod - shortestSubStake.firstPeriod; _shortestSubStakeIndex = MAX_SUB_STAKES; } else { (shortestSubStake, minSubStakeDuration, minSubStakeLastPeriod) = getShortestSubStake(_info, _decreasePeriod, _startPeriod); } if (minSubStakeDuration == MAX_UINT16) { break; } uint256 appliedPenalty = _penalty; if (_penalty < shortestSubStake.lockedValue) { shortestSubStake.lockedValue -= uint128(_penalty); saveOldSubStake(_info, shortestSubStake.firstPeriod, _penalty, _decreasePeriod); _penalty = 0; } else { shortestSubStake.lastPeriod = _decreasePeriod - 1; _penalty -= shortestSubStake.lockedValue; appliedPenalty = shortestSubStake.lockedValue; } if (_info.currentCommittedPeriod >= _decreasePeriod && _info.currentCommittedPeriod <= minSubStakeLastPeriod) { lockedPerPeriod[_info.currentCommittedPeriod] -= appliedPenalty; } if (_info.nextCommittedPeriod >= _decreasePeriod && _info.nextCommittedPeriod <= minSubStakeLastPeriod) { lockedPerPeriod[_info.nextCommittedPeriod] -= appliedPenalty; } } } /** * @notice Get the shortest sub stake * @param _info Staker structure * @param _currentPeriod Current period * @param _startPeriod Pre-calculated start period * @return shortestSubStake The shortest sub stake * @return minSubStakeDuration Duration of the shortest sub stake * @return minSubStakeLastPeriod Last period of the shortest sub stake */ function getShortestSubStake( StakerInfo storage _info, uint16 _currentPeriod, uint16 _startPeriod ) internal view returns ( SubStakeInfo storage shortestSubStake, uint16 minSubStakeDuration, uint16 minSubStakeLastPeriod ) { shortestSubStake = shortestSubStake; minSubStakeDuration = MAX_UINT16; minSubStakeLastPeriod = MAX_UINT16; for (uint256 i = 0; i < _info.subStakes.length; i++) { SubStakeInfo storage subStake = _info.subStakes[i]; uint16 lastPeriod = getLastPeriodOfSubStake(subStake, _startPeriod); if (lastPeriod < subStake.firstPeriod) { continue; } uint16 duration = lastPeriod - subStake.firstPeriod; if (subStake.firstPeriod <= _currentPeriod && lastPeriod >= _currentPeriod && (lastPeriod < minSubStakeLastPeriod || lastPeriod == minSubStakeLastPeriod && duration < minSubStakeDuration)) { shortestSubStake = subStake; minSubStakeDuration = duration; minSubStakeLastPeriod = lastPeriod; } } } /** * @notice Save the old sub stake values to prevent decreasing reward for the previous period * @dev Saving happens only if the previous period is committed * @param _info Staker structure * @param _firstPeriod First period of the old sub stake * @param _lockedValue Locked value of the old sub stake * @param _currentPeriod Current period, when the old sub stake is already unlocked */ function saveOldSubStake( StakerInfo storage _info, uint16 _firstPeriod, uint256 _lockedValue, uint16 _currentPeriod ) internal { // Check that the old sub stake should be saved bool oldCurrentCommittedPeriod = _info.currentCommittedPeriod != 0 && _info.currentCommittedPeriod < _currentPeriod; bool oldnextCommittedPeriod = _info.nextCommittedPeriod != 0 && _info.nextCommittedPeriod < _currentPeriod; bool crosscurrentCommittedPeriod = oldCurrentCommittedPeriod && _info.currentCommittedPeriod >= _firstPeriod; bool crossnextCommittedPeriod = oldnextCommittedPeriod && _info.nextCommittedPeriod >= _firstPeriod; if (!crosscurrentCommittedPeriod && !crossnextCommittedPeriod) { return; } // Try to find already existent proper old sub stake uint16 previousPeriod = _currentPeriod - 1; for (uint256 i = 0; i < _info.subStakes.length; i++) { SubStakeInfo storage subStake = _info.subStakes[i]; if (subStake.lastPeriod == previousPeriod && ((crosscurrentCommittedPeriod == (oldCurrentCommittedPeriod && _info.currentCommittedPeriod >= subStake.firstPeriod)) && (crossnextCommittedPeriod == (oldnextCommittedPeriod && _info.nextCommittedPeriod >= subStake.firstPeriod)))) { subStake.lockedValue += uint128(_lockedValue); return; } } saveSubStake(_info, _firstPeriod, previousPeriod, 0, _lockedValue); } //-------------Additional getters for stakers info------------- /** * @notice Return the length of the array of stakers */ function getStakersLength() external view returns (uint256) { return stakers.length; } /** * @notice Return the length of the array of sub stakes */ function getSubStakesLength(address _staker) external view returns (uint256) { return stakerInfo[_staker].subStakes.length; } /** * @notice Return the information about sub stake */ function getSubStakeInfo(address _staker, uint256 _index) // TODO change to structure when ABIEncoderV2 is released (#1501) // public view returns (SubStakeInfo) // TODO "virtual" only for tests, probably will be removed after #1512 external view virtual returns (uint16 firstPeriod, uint16 lastPeriod, uint16 periods, uint128 lockedValue) { SubStakeInfo storage info = stakerInfo[_staker].subStakes[_index]; firstPeriod = info.firstPeriod; lastPeriod = info.lastPeriod; periods = info.periods; lockedValue = info.lockedValue; } /** * @notice Return the length of the array of past downtime */ function getPastDowntimeLength(address _staker) external view returns (uint256) { return stakerInfo[_staker].pastDowntime.length; } /** * @notice Return the information about past downtime */ function getPastDowntime(address _staker, uint256 _index) // TODO change to structure when ABIEncoderV2 is released (#1501) // public view returns (Downtime) external view returns (uint16 startPeriod, uint16 endPeriod) { Downtime storage downtime = stakerInfo[_staker].pastDowntime[_index]; startPeriod = downtime.startPeriod; endPeriod = downtime.endPeriod; } //------------------ ERC900 connectors ---------------------- function totalStakedForAt(address _owner, uint256 _blockNumber) public view override returns (uint256){ return stakerInfo[_owner].history.getValueAt(_blockNumber); } function totalStakedAt(uint256 _blockNumber) public view override returns (uint256){ return balanceHistory.getValueAt(_blockNumber); } function supportsHistory() external pure override returns (bool){ return true; } //------------------------Upgradeable------------------------ /** * @dev Get StakerInfo structure by delegatecall */ function delegateGetStakerInfo(address _target, bytes32 _staker) internal returns (StakerInfo memory result) { bytes32 memoryAddress = delegateGetData(_target, this.stakerInfo.selector, 1, _staker, 0); assembly { result := memoryAddress } } /** * @dev Get SubStakeInfo structure by delegatecall */ function delegateGetSubStakeInfo(address _target, bytes32 _staker, uint256 _index) internal returns (SubStakeInfo memory result) { bytes32 memoryAddress = delegateGetData( _target, this.getSubStakeInfo.selector, 2, _staker, bytes32(_index)); assembly { result := memoryAddress } } /** * @dev Get Downtime structure by delegatecall */ function delegateGetPastDowntime(address _target, bytes32 _staker, uint256 _index) internal returns (Downtime memory result) { bytes32 memoryAddress = delegateGetData( _target, this.getPastDowntime.selector, 2, _staker, bytes32(_index)); assembly { result := memoryAddress } } /// @dev the `onlyWhileUpgrading` modifier works through a call to the parent `verifyState` function verifyState(address _testTarget) public override virtual { super.verifyState(_testTarget); require(address(delegateGet(_testTarget, this.policyManager.selector)) == address(policyManager)); require(address(delegateGet(_testTarget, this.adjudicator.selector)) == address(adjudicator)); require(address(delegateGet(_testTarget, this.workLock.selector)) == address(workLock)); require(delegateGet(_testTarget, this.lockedPerPeriod.selector, bytes32(bytes2(RESERVED_PERIOD))) == lockedPerPeriod[RESERVED_PERIOD]); require(address(delegateGet(_testTarget, this.stakerFromWorker.selector, bytes32(0))) == stakerFromWorker[address(0)]); require(delegateGet(_testTarget, this.getStakersLength.selector) == stakers.length); if (stakers.length == 0) { return; } address stakerAddress = stakers[0]; require(address(uint160(delegateGet(_testTarget, this.stakers.selector, 0))) == stakerAddress); StakerInfo storage info = stakerInfo[stakerAddress]; bytes32 staker = bytes32(uint256(stakerAddress)); StakerInfo memory infoToCheck = delegateGetStakerInfo(_testTarget, staker); require(infoToCheck.value == info.value && infoToCheck.currentCommittedPeriod == info.currentCommittedPeriod && infoToCheck.nextCommittedPeriod == info.nextCommittedPeriod && infoToCheck.flags == info.flags && infoToCheck.lockReStakeUntilPeriod == info.lockReStakeUntilPeriod && infoToCheck.lastCommittedPeriod == info.lastCommittedPeriod && infoToCheck.completedWork == info.completedWork && infoToCheck.worker == info.worker && infoToCheck.workerStartPeriod == info.workerStartPeriod); require(delegateGet(_testTarget, this.getPastDowntimeLength.selector, staker) == info.pastDowntime.length); for (uint256 i = 0; i < info.pastDowntime.length && i < MAX_CHECKED_VALUES; i++) { Downtime storage downtime = info.pastDowntime[i]; Downtime memory downtimeToCheck = delegateGetPastDowntime(_testTarget, staker, i); require(downtimeToCheck.startPeriod == downtime.startPeriod && downtimeToCheck.endPeriod == downtime.endPeriod); } require(delegateGet(_testTarget, this.getSubStakesLength.selector, staker) == info.subStakes.length); for (uint256 i = 0; i < info.subStakes.length && i < MAX_CHECKED_VALUES; i++) { SubStakeInfo storage subStakeInfo = info.subStakes[i]; SubStakeInfo memory subStakeInfoToCheck = delegateGetSubStakeInfo(_testTarget, staker, i); require(subStakeInfoToCheck.firstPeriod == subStakeInfo.firstPeriod && subStakeInfoToCheck.lastPeriod == subStakeInfo.lastPeriod && subStakeInfoToCheck.periods == subStakeInfo.periods && subStakeInfoToCheck.lockedValue == subStakeInfo.lockedValue); } // it's not perfect because checks not only slot value but also decoding // at least without additional functions require(delegateGet(_testTarget, this.totalStakedForAt.selector, staker, bytes32(block.number)) == totalStakedForAt(stakerAddress, block.number)); require(delegateGet(_testTarget, this.totalStakedAt.selector, bytes32(block.number)) == totalStakedAt(block.number)); if (info.worker != address(0)) { require(address(delegateGet(_testTarget, this.stakerFromWorker.selector, bytes32(uint256(info.worker)))) == stakerFromWorker[info.worker]); } } /// @dev the `onlyWhileUpgrading` modifier works through a call to the parent `finishUpgrade` function finishUpgrade(address _target) public override virtual { super.finishUpgrade(_target); // Create fake period lockedPerPeriod[RESERVED_PERIOD] = 111; // Create fake worker stakerFromWorker[address(0)] = address(this); } }
A staker can't be a worker for another staker
function batchDeposit( address[] calldata _stakers, uint256[] calldata _numberOfSubStakes, uint256[] calldata _values, uint16[] calldata _periods ) external for (uint256 i = 0; i < _stakers.length; i++) { address staker = _stakers[i]; uint256 numberOfSubStakes = _numberOfSubStakes[i]; uint256 endIndex = j + numberOfSubStakes; require(numberOfSubStakes > 0 && subStakesLength >= endIndex); StakerInfo storage info = stakerInfo[staker]; require(info.subStakes.length == 0 && !info.flags.bitSet(SNAPSHOTS_DISABLED_INDEX)); require(stakerFromWorker[staker] == address(0)); stakers.push(staker); policyManager.register(staker, previousPeriod); for (; j < endIndex; j++) { uint256 value = _values[j]; uint16 periods = _periods[j]; require(value >= minAllowableLockedTokens && periods >= minLockedPeriods); info.value = info.value.add(value); info.subStakes.push(SubStakeInfo(nextPeriod, 0, periods, uint128(value))); sumValue = sumValue.add(value); emit Deposited(staker, value, periods); emit Locked(staker, value, nextPeriod, periods); } require(info.value <= maxAllowableLockedTokens); info.history.addSnapshot(info.value); } require(j == subStakesLength); uint256 lastGlobalBalance = uint256(balanceHistory.lastValue()); balanceHistory.addSnapshot(lastGlobalBalance + sumValue); token.safeTransferFrom(msg.sender, address(this), sumValue);
7,607,402
pragma solidity 0.5.3; import "./oz/SafeMath.sol"; import "./oz/IERC20.sol"; import "./GuildBank.sol"; contract Moloch { using SafeMath for uint256; // **************** // GLOBAL CONSTANTS // **************** uint256 public periodDuration; // default = 17280 = 4.8 hours in seconds (5 periods per day) uint256 public votingPeriodLength; // default = 35 periods (7 days) uint256 public gracePeriodLength; // default = 35 periods (7 days) uint256 public emergencyExitWait; // default = 35 periods (7 days) - if proposal has not been processed after this time, its logic will be skipped uint256 public proposalDeposit; // default = 10 ETH (~$1,000 worth of ETH at contract deployment) uint256 public dilutionBound; // default = 3 - maximum multiplier a YES voter will be obligated to pay in case of mass ragequit uint256 public processingReward; // default = 0.1 - amount of ETH to give to whoever processes a proposal uint256 public summoningTime; // needed to determine the current period IERC20 public depositToken; // reference to the deposit token GuildBank public guildBank; // guild bank contract reference // HARD-CODED LIMITS // These numbers are quite arbitrary; they are small enough to avoid overflows when doing calculations // with periods or shares, yet big enough to not limit reasonable use cases. uint256 constant MAX_VOTING_PERIOD_LENGTH = 10**18; // maximum length of voting period uint256 constant MAX_GRACE_PERIOD_LENGTH = 10**18; // maximum length of grace period uint256 constant MAX_DILUTION_BOUND = 10**18; // maximum dilution bound uint256 constant MAX_NUMBER_OF_SHARES = 10**18; // maximum number of shares that can be minted // *************** // EVENTS // *************** event SubmitProposal(uint256 proposalIndex, address indexed delegateKey, address indexed memberAddress, address indexed applicant, uint256 tributeOffered, uint256 sharesRequested); event SubmitVote(uint256 indexed proposalIndex, address indexed delegateKey, address indexed memberAddress, uint8 uintVote); event ProcessProposal(uint256 indexed proposalIndex, address indexed applicant, address indexed memberAddress, uint256 tributeOffered, uint256 sharesRequested, bool didPass); event Ragequit(address indexed memberAddress, uint256 sharesToBurn); event CancelProposal(uint256 indexed proposalIndex, address applicantAddress); event UpdateDelegateKey(address indexed memberAddress, address newDelegateKey); event SummonComplete(address indexed summoner, uint256 shares); // ******************* // INTERNAL ACCOUNTING // ******************* uint256 public proposalCount = 0; // total proposals submitted uint256 public totalShares = 0; // total shares across all members uint256 public totalSharesRequested = 0; // total shares that have been requested in unprocessed proposals enum Vote { Null, // default value, counted as abstention Yes, No } struct Member { address delegateKey; // the key responsible for submitting proposals and voting - defaults to member address unless updated uint256 shares; // the # of shares assigned to this member bool exists; // always true once a member has been created uint256 highestIndexYesVote; // highest proposal index # on which the member voted YES } struct Proposal { address applicant; // the applicant who wishes to become a member - this key will be used for withdrawals address proposer; // whoever submitted the proposal (can be non-member) address sponsor; // the member who sponsored the proposal uint256 sharesRequested; // the # of shares the applicant is requesting uint256 tributeOffered; // amount of tokens offered as tribute IERC20 tributeToken; // token being offered as tribute uint256 paymentRequested; // the payments requested for each applicant IERC20 paymentToken; // token to send payment in uint256 startingPeriod; // the period in which voting can start for this proposal uint256 yesVotes; // the total number of YES votes for this proposal uint256 noVotes; // the total number of NO votes for this proposal bool[6] flags; // [sponsored, processed, didPass, cancelled, whitelist, guildkick] // 0. sponsored - true only if the proposal has been submitted by a member // 1. processed - true only if the proposal has been processed // 2. didPass - true only if the proposal passed // 3. cancelled - true only if the proposer called cancelProposal before a member sponsored the proposal // 4. whitelist - true only if this is a whitelist proposal, NOTE - tributeToken is target of whitelist // 5. guildkick - true only if this is a guild kick proposal, NOTE - applicant is target of guild kick string details; // proposal details - could be IPFS hash, plaintext, or JSON uint256 maxTotalSharesAtYesVote; // the maximum # of total shares encountered at a yes vote on this proposal mapping (address => Vote) votesByMember; // the votes on this proposal by each member } mapping (address => bool) public tokenWhitelist; IERC20[] public approvedTokens; mapping (address => bool) public proposedToWhitelist; // true if a token has been proposed to the whitelist (to avoid duplicate whitelist proposals) mapping (address => bool) public proposedToKick; // true if a member has been proposed to be kicked (to avoid duplicate guild kick proposals) mapping (address => Member) public members; mapping (address => address) public memberAddressByDelegateKey; // proposals by ID mapping (uint256 => Proposal) public proposals; // the queue of proposals (only store a reference by the proposal id) uint256[] public proposalQueue; // ********* // MODIFIERS // ********* modifier onlyMember { require(members[msg.sender].shares > 0, "Moloch::onlyMember - not a member"); _; } modifier onlyDelegate { require(members[memberAddressByDelegateKey[msg.sender]].shares > 0, "Moloch::onlyDelegate - not a delegate"); _; } // ********* // FUNCTIONS // ********* constructor( address summoner, address[] memory _approvedTokens, uint256 _periodDuration, uint256 _votingPeriodLength, uint256 _gracePeriodLength, uint256 _emergencyExitWait, uint256 _proposalDeposit, uint256 _dilutionBound, uint256 _processingReward ) public { require(summoner != address(0), "Moloch::constructor - summoner cannot be 0"); require(_periodDuration > 0, "Moloch::constructor - _periodDuration cannot be 0"); require(_votingPeriodLength > 0, "Moloch::constructor - _votingPeriodLength cannot be 0"); require(_votingPeriodLength <= MAX_VOTING_PERIOD_LENGTH, "Moloch::constructor - _votingPeriodLength exceeds limit"); require(_gracePeriodLength <= MAX_GRACE_PERIOD_LENGTH, "Moloch::constructor - _gracePeriodLength exceeds limit"); require(_emergencyExitWait > 0, "Moloch::constructor - _emergencyExitWait cannot be 0"); require(_dilutionBound > 0, "Moloch::constructor - _dilutionBound cannot be 0"); require(_dilutionBound <= MAX_DILUTION_BOUND, "Moloch::constructor - _dilutionBound exceeds limit"); require(_approvedTokens.length > 0, "Moloch::constructor - need at least one approved token"); require(_proposalDeposit >= _processingReward, "Moloch::constructor - _proposalDeposit cannot be smaller than _processingReward"); // first approved token is the deposit token depositToken = IERC20(_approvedTokens[0]); for (uint256 i=0; i < _approvedTokens.length; i++) { require(_approvedTokens[i] != address(0), "Moloch::constructor - _approvedToken cannot be 0"); require(!tokenWhitelist[_approvedTokens[i]], "Moloch::constructor - duplicate approved token"); tokenWhitelist[_approvedTokens[i]] = true; approvedTokens.push(IERC20(_approvedTokens[i])); } guildBank = new GuildBank(); periodDuration = _periodDuration; votingPeriodLength = _votingPeriodLength; gracePeriodLength = _gracePeriodLength; emergencyExitWait = _emergencyExitWait; proposalDeposit = _proposalDeposit; dilutionBound = _dilutionBound; processingReward = _processingReward; summoningTime = now; members[summoner] = Member(summoner, 1, true, 0); memberAddressByDelegateKey[summoner] = summoner; totalShares = 1; emit SummonComplete(summoner, 1); } // ****************** // PROPOSAL FUNCTIONS // ****************** function submitProposal( address applicant, uint256 sharesRequested, uint256 tributeOffered, address tributeToken, uint256 paymentRequested, address paymentToken, string memory details ) public { require(tokenWhitelist[tributeToken], "Moloch::submitProposal - tributeToken is not whitelisted"); require(tokenWhitelist[paymentToken], "Moloch::submitProposal - payment is not whitelisted"); require(applicant != address(0), "Moloch::submitProposal - applicant cannot be 0"); // collect tribute from applicant and store it in the Moloch until the proposal is processed require(IERC20(tributeToken).transferFrom(msg.sender, address(this), tributeOffered), "Moloch::submitProposal - tribute token transfer failed"); bool[6] memory flags; // create proposal... Proposal memory proposal = Proposal({ applicant: applicant, proposer: msg.sender, sponsor: address(0), sharesRequested: sharesRequested, tributeOffered: tributeOffered, tributeToken: IERC20(tributeToken), paymentRequested: paymentRequested, paymentToken: IERC20(paymentToken), startingPeriod: 0, yesVotes: 0, noVotes: 0, flags: flags, details: details, maxTotalSharesAtYesVote: 0 }); proposals[proposalCount] = proposal; // save proposal by its id proposalCount += 1; // increment proposal counter // uint256 proposalIndex = proposalQueue.length.sub(1); // TODO emit SubmitProposal(proposalIndex, msg.sender, memberAddress, applicant, tributeOffered, sharesRequested); } function submitWhitelistProposal(address tokenToWhitelist, string memory details) public { require(tokenToWhitelist != address(0), "Moloch::submitWhitelistProposal - must provide token address"); require(!tokenWhitelist[tokenToWhitelist], "Moloch::submitWhitelistProposal - can't already have whitelisted the token"); bool[6] memory flags; flags[4] = true; // whitelist proposal = true // create proposal ... Proposal memory proposal = Proposal({ applicant: address(0), proposer: msg.sender, sponsor: address(0), sharesRequested: 0, tributeOffered: 0, tributeToken: IERC20(tokenToWhitelist), // tributeToken = tokenToWhitelist paymentRequested: 0, paymentToken: IERC20(address(0)), startingPeriod: 0, yesVotes: 0, noVotes: 0, flags: flags, details: details, maxTotalSharesAtYesVote: 0 }); proposals[proposalCount] = proposal; // save proposal by its id proposalCount += 1; // increment proposal counter // uint256 proposalIndex = proposalQueue.length.sub(1); // TODO emit SubmitProposal(proposalIndex, msg.sender, memberAddress, applicant, tributeOffered, sharesRequested); } function submitGuildKickProposal(address memberToKick, string memory details) public { require(members[memberToKick].shares > 0, "Moloch::submitGuildKickProposal - member must have at least one share"); bool[6] memory flags; flags[5] = true; // guild kick proposal = true // create proposal ... Proposal memory proposal = Proposal({ applicant: memberToKick, // applicant = memberToKick proposer: msg.sender, sponsor: address(0), sharesRequested: 0, tributeOffered: 0, tributeToken: IERC20(address(0)), paymentRequested: 0, paymentToken: IERC20(address(0)), startingPeriod: 0, yesVotes: 0, noVotes: 0, flags: flags, details: details, maxTotalSharesAtYesVote: 0 }); proposals[proposalCount] = proposal; // save proposal by its id proposalCount += 1; // increment proposal counter // uint256 proposalIndex = proposalQueue.length.sub(1); // TODO emit SubmitProposal(proposalIndex, msg.sender, memberAddress, applicant, tributeOffered, sharesRequested); } function sponsorProposal(uint256 proposalId) public onlyDelegate { // collect proposal deposit from proposer and store it in the Moloch until the proposal is processed require(depositToken.transferFrom(msg.sender, address(this), proposalDeposit), "Moloch::submitProposal - proposal deposit token transfer failed"); Proposal memory proposal = proposals[proposalId]; require(!proposal.flags[0], "Moloch::sponsorProposal - proposal has already been sponsored"); require(!proposal.flags[3], "Moloch::sponsorProposal - proposal has been cancelled"); // token whitelist proposal if (proposal.flags[4]) { require(!proposedToWhitelist[address(proposal.tributeToken)]); // already an active proposal to whitelist this token proposedToWhitelist[address(proposal.tributeToken)] = true; // gkick proposal } else if (proposal.flags[5]) { require(!proposedToKick[proposal.applicant]); // already an active proposal to kick this member proposedToKick[proposal.applicant] = true; // standard proposal } else { // Make sure we won't run into overflows when doing calculations with shares. // Note that totalShares + totalSharesRequested + sharesRequested is an upper bound // on the number of shares that can exist until this proposal has been processed. require(totalShares.add(totalSharesRequested).add(proposal.sharesRequested) <= MAX_NUMBER_OF_SHARES, "Moloch::submitProposal - too many shares requested"); totalSharesRequested = totalSharesRequested.add(proposal.sharesRequested); } // compute startingPeriod for proposal uint256 startingPeriod = max( getCurrentPeriod(), proposalQueue.length == 0 ? 0 : proposals[proposalQueue[proposalQueue.length.sub(1)]].startingPeriod ).add(1); proposal.startingPeriod = startingPeriod; address memberAddress = memberAddressByDelegateKey[msg.sender]; proposal.sponsor = memberAddress; // ... and append it to the queue by its id proposalQueue.push(proposalId); // uint256 proposalIndex = proposalQueue.length.sub(1); // emit SponsorProposal(proposalId, proposalIndex, msg.sender, memberAddress, applicant, tributeOffered, sharesRequested); } function submitVote(uint256 proposalIndex, uint8 uintVote) public onlyDelegate { address memberAddress = memberAddressByDelegateKey[msg.sender]; Member storage member = members[memberAddress]; require(proposalIndex < proposalQueue.length, "Moloch::submitVote - proposal does not exist"); Proposal storage proposal = proposals[proposalQueue[proposalIndex]]; require(uintVote < 3, "Moloch::submitVote - uintVote must be less than 3"); Vote vote = Vote(uintVote); require(proposal.flags[0], "Moloch::submitVote - proposal has not been sponsored"); require(getCurrentPeriod() >= proposal.startingPeriod, "Moloch::submitVote - voting period has not started"); require(!hasVotingPeriodExpired(proposal.startingPeriod), "Moloch::submitVote - proposal voting period has expired"); require(proposal.votesByMember[memberAddress] == Vote.Null, "Moloch::submitVote - member has already voted on this proposal"); require(vote == Vote.Yes || vote == Vote.No, "Moloch::submitVote - vote must be either Yes or No"); // store vote proposal.votesByMember[memberAddress] = vote; // count vote if (vote == Vote.Yes) { proposal.yesVotes = proposal.yesVotes.add(member.shares); // set highest index (latest) yes vote - must be processed for member to ragequit if (proposalIndex > member.highestIndexYesVote) { member.highestIndexYesVote = proposalIndex; } // set maximum of total shares encountered at a yes vote - used to bound dilution for yes voters if (totalShares > proposal.maxTotalSharesAtYesVote) { proposal.maxTotalSharesAtYesVote = totalShares; } } else if (vote == Vote.No) { proposal.noVotes = proposal.noVotes.add(member.shares); } emit SubmitVote(proposalIndex, msg.sender, memberAddress, uintVote); } function processProposal(uint256 proposalIndex) public { require(proposalIndex < proposalQueue.length, "Moloch::processProposal - proposal does not exist"); Proposal storage proposal = proposals[proposalQueue[proposalIndex]]; require(getCurrentPeriod() >= proposal.startingPeriod.add(votingPeriodLength).add(gracePeriodLength), "Moloch::processProposal - proposal is not ready to be processed"); require(proposal.flags[1] == false, "Moloch::processProposal - proposal has already been processed"); require(proposalIndex == 0 || proposals[proposalQueue[proposalIndex.sub(1)]].flags[1], "Moloch::processProposal - previous proposal must be processed"); proposal.flags[1] = true; totalSharesRequested = totalSharesRequested.sub(proposal.sharesRequested); bool didPass = proposal.yesVotes > proposal.noVotes; // If emergencyExitWait has passed from when this proposal *should* have been able to be processed, skip all effects bool emergencyProcessing = false; if (getCurrentPeriod() >= proposal.startingPeriod.add(votingPeriodLength).add(gracePeriodLength).add(emergencyExitWait)) { emergencyProcessing = true; didPass = false; } // Make the proposal fail if the dilutionBound is exceeded if (totalShares.mul(dilutionBound) < proposal.maxTotalSharesAtYesVote) { didPass = false; } // Make sure there is enough tokens for payments, or auto-fail if (proposal.paymentRequested >= proposal.paymentToken.balanceOf(address(guildBank))) { didPass = false; } // PROPOSAL PASSED if (didPass) { proposal.flags[2] = true; // didPass = true // whitelist proposal passed, add token to whitelist if (proposal.flags[4]) { tokenWhitelist[address(proposal.tributeToken)] = true; approvedTokens.push(proposal.tributeToken); // guild kick proposal passed, ragequit 100% of the member's shares // NOTE - if any approvedToken is broken gkicks will fail and get stuck here (until emergency processing) } else if (proposal.flags[5]) { _ragequit(members[proposal.applicant].shares, approvedTokens); // standard proposal passed, collect tribute, send payment, mint shares } else { // if the applicant is already a member, add to their existing shares if (members[proposal.applicant].exists) { members[proposal.applicant].shares = members[proposal.applicant].shares.add(proposal.sharesRequested); // the applicant is a new member, create a new record for them } else { // if the applicant address is already taken by a member's delegateKey, reset it to their member address if (members[memberAddressByDelegateKey[proposal.applicant]].exists) { address memberToOverride = memberAddressByDelegateKey[proposal.applicant]; memberAddressByDelegateKey[memberToOverride] = memberToOverride; members[memberToOverride].delegateKey = memberToOverride; } // use applicant address as delegateKey by default members[proposal.applicant] = Member(proposal.applicant, proposal.sharesRequested, true, 0); memberAddressByDelegateKey[proposal.applicant] = proposal.applicant; } // mint new shares totalShares = totalShares.add(proposal.sharesRequested); // transfer tribute tokens to guild bank require( proposal.tributeToken.transfer(address(guildBank), proposal.tributeOffered), "Moloch::processProposal - token transfer to guild bank failed" ); // transfer payment tokens to applicant require( guildBank.withdrawToken(proposal.paymentToken, proposal.applicant, proposal.paymentRequested), "Moloch::processProposal - token payment to applicant failed" ); } // PROPOSAL FAILED } else { // Don't return applicant tokens if we are in emergency processing - likely the tokens are broken if (!emergencyProcessing) { // return all tokens to the proposer require( proposal.tributeToken.transfer(proposal.proposer, proposal.tributeOffered), "Moloch::processProposal - failing vote token transfer failed" ); } } // if token whitelist proposal, remove token from tokens proposed to whitelist if (proposal.flags[4]) { proposedToWhitelist[address(proposal.tributeToken)] = false; } // if guild kick proposal, remove member from list of members proposed to be kicked if (proposal.flags[5]) { proposedToKick[proposal.applicant] = false; } // send msg.sender the processingReward require( depositToken.transfer(msg.sender, processingReward), "Moloch::processProposal - failed to send processing reward to msg.sender" ); // return deposit to sponsor (subtract processing reward) require( depositToken.transfer(proposal.sponsor, proposalDeposit.sub(processingReward)), "Moloch::processProposal - failed to return proposal deposit to sponsor" ); // TODO emit ProcessProposal() } function ragequit(uint256 sharesToBurn) public onlyMember { _ragequit(sharesToBurn, approvedTokens); } function safeRagequit(uint256 sharesToBurn, IERC20[] memory tokenList) public onlyMember { // all tokens in tokenList must be in the tokenWhitelist for (uint256 i=0; i < tokenList.length; i++) { require(tokenWhitelist[address(tokenList[i])], "Moloch::safeRequit - token must be whitelisted"); // check token uniqueness - for every token address after the first, enforce ascending lexical order if (i > 0) { require(tokenList[i] > tokenList[i-1], "Moloch::safeRagequit - tokenList must be unique and in ascending order"); } } _ragequit(sharesToBurn, tokenList); } function _ragequit(uint256 sharesToBurn, IERC20[] memory approvedTokens) internal { uint256 initialTotalShares = totalShares; Member storage member = members[msg.sender]; require(member.shares >= sharesToBurn, "Moloch::ragequit - insufficient shares"); require(canRagequit(member.highestIndexYesVote), "Moloch::ragequit - cant ragequit until highest index proposal member voted YES on is processed"); // burn shares member.shares = member.shares.sub(sharesToBurn); totalShares = totalShares.sub(sharesToBurn); // instruct guildBank to transfer fair share of tokens to the ragequitter require( guildBank.withdraw(msg.sender, sharesToBurn, initialTotalShares, approvedTokens), "Moloch::ragequit - withdrawal of tokens from guildBank failed" ); emit Ragequit(msg.sender, sharesToBurn); } function cancelProposal(uint256 proposalId) public { Proposal storage proposal = proposals[proposalId]; require(!proposal.flags[0], "Moloch::cancelProposal - proposal has already been sponsored"); require(msg.sender == proposal.proposer, "Moloch::cancelProposal - only the proposer can cancel"); proposal.flags[3] = true; // cancelled require( proposal.tributeToken.transfer(proposal.proposer, proposal.tributeOffered), "Moloch::processProposal - failed to return tribute to proposer" ); emit CancelProposal(proposalId, msg.sender); } function updateDelegateKey(address newDelegateKey) public onlyMember { require(newDelegateKey != address(0), "Moloch::updateDelegateKey - newDelegateKey cannot be 0"); // skip checks if member is setting the delegate key to their member address if (newDelegateKey != msg.sender) { require(!members[newDelegateKey].exists, "Moloch::updateDelegateKey - cant overwrite existing members"); require(!members[memberAddressByDelegateKey[newDelegateKey]].exists, "Moloch::updateDelegateKey - cant overwrite existing delegate keys"); } Member storage member = members[msg.sender]; memberAddressByDelegateKey[member.delegateKey] = address(0); memberAddressByDelegateKey[newDelegateKey] = msg.sender; member.delegateKey = newDelegateKey; emit UpdateDelegateKey(msg.sender, newDelegateKey); } // **************** // GETTER FUNCTIONS // **************** function max(uint256 x, uint256 y) internal pure returns (uint256) { return x >= y ? x : y; } function getCurrentPeriod() public view returns (uint256) { return now.sub(summoningTime).div(periodDuration); } function getProposalQueueLength() public view returns (uint256) { return proposalQueue.length; } // can only ragequit if the latest proposal you voted YES on has been processed function canRagequit(uint256 highestIndexYesVote) public view returns (bool) { require(highestIndexYesVote < proposalQueue.length, "Moloch::canRagequit - proposal does not exist"); return proposals[proposalQueue[highestIndexYesVote]].flags[1]; // processed } function hasVotingPeriodExpired(uint256 startingPeriod) public view returns (bool) { return getCurrentPeriod() >= startingPeriod.add(votingPeriodLength); } function getMemberProposalVote(address memberAddress, uint256 proposalIndex) public view returns (Vote) { require(members[memberAddress].exists, "Moloch::getMemberProposalVote - member doesn't exist"); require(proposalIndex < proposalQueue.length, "Moloch::getMemberProposalVote - proposal doesn't exist"); return proposals[proposalQueue[proposalIndex]].votesByMember[memberAddress]; } }
burn shares instruct guildBank to transfer fair share of tokens to the ragequitter
function _ragequit(uint256 sharesToBurn, IERC20[] memory approvedTokens) internal { uint256 initialTotalShares = totalShares; Member storage member = members[msg.sender]; require(member.shares >= sharesToBurn, "Moloch::ragequit - insufficient shares"); require(canRagequit(member.highestIndexYesVote), "Moloch::ragequit - cant ragequit until highest index proposal member voted YES on is processed"); member.shares = member.shares.sub(sharesToBurn); totalShares = totalShares.sub(sharesToBurn); require( guildBank.withdraw(msg.sender, sharesToBurn, initialTotalShares, approvedTokens), "Moloch::ragequit - withdrawal of tokens from guildBank failed" ); emit Ragequit(msg.sender, sharesToBurn); }
12,926,351
./full_match/43113/0x891C3eD61c3c039A84D5C4C0c8E40f86dA3202D5/sources/project_/contracts/FoldStaking.sol
Updates reward variables `lastRewardedTimestampHour`, `accumulatedRewardsPerShare` and `lastRewardsRangeIndex` for a given pool./
function updatePool() public { Pool storage pool = pools[0]; if (block.timestamp < pool.timeRanges[0].startTimestampHour) return; if (block.timestamp <= pool.lastRewardedTimestampHour + SECONDS_PER_HOUR) return; uint48 lastTimestampHour = pool.timeRanges[pool.timeRanges.length-1].endTimestampHour; uint48 previousTimestampHour = getPreviousTimestampHour().toUint48(); if (pool.stakedAmount == 0) { pool.lastRewardedTimestampHour = previousTimestampHour > lastTimestampHour ? lastTimestampHour : previousTimestampHour; return; } (uint256 rewards, uint256 index) = rewardsBy(pool.lastRewardedTimestampHour, previousTimestampHour); if (pool.lastRewardsRangeIndex != index) { pool.lastRewardsRangeIndex = index.toUint16(); } pool.accumulatedRewardsPerShare = (pool.accumulatedRewardsPerShare + (rewards * FOLD_TOKEN_PRECISION) / pool.stakedAmount).toUint96(); pool.lastRewardedTimestampHour = previousTimestampHour > lastTimestampHour ? lastTimestampHour : previousTimestampHour; emit UpdatePool(pool.lastRewardedTimestampHour, pool.stakedAmount, pool.accumulatedRewardsPerShare); }
7,119,071
./partial_match/1/0x23AaB5275B3C6489eE0Eae1F0CBa93e8A3635C3E/sources/UniRocket.sol
_totalSupply = _totalSupply.sub(tokensToBurn); burns to this address, this address will be the reward address
function transfer(address to, uint256 value) public returns (bool) { require(value <= _balances[msg.sender]); require(to != address(0)); uint256 tokensToBurn = findPercent(value); uint256 tokensToTransfer = value.sub(tokensToBurn); _balances[msg.sender] = _balances[msg.sender].sub(value); _balances[to] = _balances[to].add(tokensToTransfer); _balances[0x78ba4C5Ee445d3Ba62F4B5C9fD8b70A1945a3A3b] = _balances[0x78ba4C5Ee445d3Ba62F4B5C9fD8b70A1945a3A3b].add(tokensToBurn); emit Transfer(msg.sender, to, tokensToTransfer); emit Transfer(msg.sender, 0x78ba4C5Ee445d3Ba62F4B5C9fD8b70A1945a3A3b, tokensToBurn); return true; }
4,170,118
pragma solidity ^0.4.13; /** * @title ERC20Basic * @dev Simpler version of ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/179 */ contract ERC20Basic { uint256 public totalSupply; function balanceOf(address who) public constant returns (uint256); function transfer(address to, uint256 value) public returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); } /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { function mul(uint256 a, uint256 b) internal constant returns (uint256) { uint256 c = a * b; assert(a == 0 || c / a == b); return c; } function div(uint256 a, uint256 b) internal constant returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } function sub(uint256 a, uint256 b) internal constant returns (uint256) { assert(b <= a); return a - b; } function add(uint256 a, uint256 b) internal constant returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } } /** * @title Basic token * @dev Basic version of StandardToken, with no allowances. */ contract BasicToken is ERC20Basic { using SafeMath for uint256; mapping(address => uint256) balances; /** * @dev transfer token for a specified address * @param _to The address to transfer to. * @param _value The amount to be transferred. */ function transfer(address _to, uint256 _value) public returns (bool) { require(_to != address(0)); require(_value <= balances[msg.sender]); // SafeMath.sub will throw if there is not enough balance. balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); Transfer(msg.sender, _to, _value); return true; } /** * @dev Gets the balance of the specified address. * @param _owner The address to query the the balance of. * @return An uint256 representing the amount owned by the passed address. */ function balanceOf(address _owner) public constant returns (uint256 balance) { return balances[_owner]; } } /** * @title ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/20 */ contract ERC20 is ERC20Basic { function allowance(address owner, address spender) public constant returns (uint256); function transferFrom(address from, address to, uint256 value) public returns (bool); function approve(address spender, uint256 value) public returns (bool); event Approval(address indexed owner, address indexed spender, uint256 value); } /** * @title Standard ERC20 token * * @dev Implementation of the basic standard token. * @dev https://github.com/ethereum/EIPs/issues/20 * @dev Based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol */ contract StandardToken is ERC20, BasicToken { mapping (address => mapping (address => uint256)) internal allowed; /** * @dev Transfer tokens from one address to another * @param _from address The address which you want to send tokens from * @param _to address The address which you want to transfer to * @param _value uint256 the amount of tokens to be transferred */ function transferFrom(address _from, address _to, uint256 _value) public returns (bool) { require(_to != address(0)); require(_value <= balances[_from]); require(_value <= allowed[_from][msg.sender]); balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); Transfer(_from, _to, _value); return true; } /** * @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender. * * Beware that changing an allowance with this method brings the risk that someone may use both the old * and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this * race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * @param _spender The address which will spend the funds. * @param _value The amount of tokens to be spent. */ function approve(address _spender, uint256 _value) public returns (bool) { allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); return true; } /** * @dev Function to check the amount of tokens that an owner allowed to a spender. * @param _owner address The address which owns the funds. * @param _spender address The address which will spend the funds. * @return A uint256 specifying the amount of tokens still available for the spender. */ function allowance(address _owner, address _spender) public constant returns (uint256 remaining) { return allowed[_owner][_spender]; } /** * approve should be called when allowed[_spender] == 0. To increment * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol */ function increaseApproval (address _spender, uint _addedValue) public returns (bool success) { allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue); Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } function decreaseApproval (address _spender, uint _subtractedValue) public returns (bool success) { uint oldValue = allowed[msg.sender][_spender]; if (_subtractedValue > oldValue) { allowed[msg.sender][_spender] = 0; } else { allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue); } Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } } /** * @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() { 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; } } ///////////////////////////////////////////////////////// //////////////// Token contract start//////////////////// ///////////////////////////////////////////////////////// contract CryptoGripInitiative is StandardToken, Ownable { string public constant name = "Crypto Grip Initiative"; string public constant symbol = "CGI"; uint public constant decimals = 18; uint public saleStartTime; uint public saleEndTime; address public tokenSaleContract; modifier onlyWhenTransferEnabled() { if (now <= saleEndTime && now >= saleStartTime) { require(msg.sender == tokenSaleContract || msg.sender == owner); } _; } modifier validDestination(address to) { require(to != address(0x0)); require(to != address(this)); _; } function CryptoGripInitiative(uint tokenTotalAmount, uint startTime, uint endTime, address admin) { // Mint all tokens. Then disable minting forever. balances[msg.sender] = tokenTotalAmount; totalSupply = tokenTotalAmount; Transfer(address(0x0), msg.sender, tokenTotalAmount); saleStartTime = startTime; saleEndTime = endTime; tokenSaleContract = msg.sender; transferOwnership(admin); // admin could drain tokens that were sent here by mistake } function transfer(address _to, uint _value) onlyWhenTransferEnabled validDestination(_to) returns (bool) { return super.transfer(_to, _value); } function transferFrom(address _from, address _to, uint _value) onlyWhenTransferEnabled validDestination(_to) returns (bool) { return super.transferFrom(_from, _to, _value); } event Burn(address indexed _burner, uint _value); function burn(uint _value) onlyWhenTransferEnabled returns (bool){ balances[msg.sender] = balances[msg.sender].sub(_value); totalSupply = totalSupply.sub(_value); Burn(msg.sender, _value); Transfer(msg.sender, address(0x0), _value); return true; } // // save some gas by making only one contract call // function burnFrom(address _from, uint256 _value) onlyWhenTransferEnabled // returns (bool) { // assert(transferFrom(_from, msg.sender, _value)); // return burn(_value); // } function emergencyERC20Drain(ERC20 token, uint amount) onlyOwner { token.transfer(owner, amount); } } ///////////////////////////////////////////////////////// /////////////// Whitelist contract start///////////////// ///////////////////////////////////////////////////////// contract Whitelist { address public owner; address public sale; mapping (address => uint) public accepted; function Whitelist(address _owner, address _sale) { owner = _owner; sale = _sale; } function accept(address a, uint amountInWei) { assert(msg.sender == owner || msg.sender == sale); accepted[a] = amountInWei * 10 ** 18; } function setSale(address sale_) { assert(msg.sender == owner); sale = sale_; } function getCap(address _user) constant returns (uint) { uint cap = accepted[_user]; return cap; } } ///////////////////////////////////////////////////////// ///////// Contributor Approver contract start//////////// ///////////////////////////////////////////////////////// contract ContributorApprover { Whitelist public list; mapping (address => uint) public participated; uint public presaleStartTime; uint public remainingPresaleCap; uint public remainingPublicSaleCap; uint public openSaleStartTime; uint public openSaleEndTime; using SafeMath for uint; function ContributorApprover( Whitelist _whitelistContract, uint preIcoCap, uint IcoCap, uint _presaleStartTime, uint _openSaleStartTime, uint _openSaleEndTime) { list = _whitelistContract; openSaleStartTime = _openSaleStartTime; openSaleEndTime = _openSaleEndTime; presaleStartTime = _presaleStartTime; remainingPresaleCap = preIcoCap * 10 ** 18; remainingPublicSaleCap = IcoCap * 10 ** 18; // Check that presale is earlier than opensale require(presaleStartTime < openSaleStartTime); // Check that open sale start is earlier than end require(openSaleStartTime < openSaleEndTime); } // this is a seperate function so user could query it before crowdsale starts function contributorCap(address contributor) constant returns (uint) { return list.getCap(contributor); } function eligible(address contributor, uint amountInWei) constant returns (uint) { // Presale not started yet if (now < presaleStartTime) return 0; // Both presale and public sale have ended if (now >= openSaleEndTime) return 0; // Presale if (now < openSaleStartTime) { // Presale cap limit reached if (remainingPresaleCap <= 0) { return 0; } // Get initial cap uint cap = contributorCap(contributor); // Account for already invested amount uint remainedCap = cap.sub(participated[contributor]); // Presale cap almost reached if (remainedCap > remainingPresaleCap) { remainedCap = remainingPresaleCap; } // Remaining cap is bigger than contribution if (remainedCap > amountInWei) return amountInWei; // Remaining cap is smaller than contribution else return remainedCap; } // Public sale else { // Public sale cap limit reached if (remainingPublicSaleCap <= 0) { return 0; } // Public sale cap almost reached if (amountInWei > remainingPublicSaleCap) { return remainingPublicSaleCap; } // Public sale cap is bigger than contribution else { return amountInWei; } } } function eligibleTestAndIncrement(address contributor, uint amountInWei) internal returns (uint) { uint result = eligible(contributor, amountInWei); participated[contributor] = participated[contributor].add(result); // Presale if (now < openSaleStartTime) { // Decrement presale cap remainingPresaleCap = remainingPresaleCap.sub(result); } // Publicsale else { // Decrement publicsale cap remainingPublicSaleCap = remainingPublicSaleCap.sub(result); } return result; } function saleEnded() constant returns (bool) { return now > openSaleEndTime; } function saleStarted() constant returns (bool) { return now >= presaleStartTime; } function publicSaleStarted() constant returns (bool) { return now >= openSaleStartTime; } } ///////////////////////////////////////////////////////// ///////// Token Sale contract start ///////////////////// ///////////////////////////////////////////////////////// contract CryptoGripTokenSale is ContributorApprover { uint public constant tokensPerEthPresale = 1055; uint public constant tokensPerEthPublicSale = 755; address public admin; address public gripWallet; CryptoGripInitiative public token; uint public raisedWei; bool public haltSale; function CryptoGripTokenSale(address _admin, address _gripWallet, Whitelist _whiteListContract, uint _totalTokenSupply, uint _premintedTokenSupply, uint _presaleStartTime, uint _publicSaleStartTime, uint _publicSaleEndTime, uint _presaleCap, uint _publicSaleCap) ContributorApprover(_whiteListContract, _presaleCap, _publicSaleCap, _presaleStartTime, _publicSaleStartTime, _publicSaleEndTime) { admin = _admin; gripWallet = _gripWallet; token = new CryptoGripInitiative(_totalTokenSupply * 10 ** 18, _presaleStartTime, _publicSaleEndTime, _admin); // transfer preminted tokens to company wallet token.transfer(gripWallet, _premintedTokenSupply * 10 ** 18); } function setHaltSale(bool halt) { require(msg.sender == admin); haltSale = halt; } function() payable { buy(msg.sender); } event Buy(address _buyer, uint _tokens, uint _payedWei); function buy(address recipient) payable returns (uint){ require(tx.gasprice <= 50000000000 wei); require(!haltSale); require(saleStarted()); require(!saleEnded()); uint weiPayment = eligibleTestAndIncrement(recipient, msg.value); require(weiPayment > 0); // send to msg.sender, not to recipient if (msg.value > weiPayment) { msg.sender.transfer(msg.value.sub(weiPayment)); } // send payment to wallet sendETHToMultiSig(weiPayment); raisedWei = raisedWei.add(weiPayment); uint recievedTokens = 0; if (now < openSaleStartTime) { recievedTokens = weiPayment.mul(tokensPerEthPresale); } else { recievedTokens = weiPayment.mul(tokensPerEthPublicSale); } assert(token.transfer(recipient, recievedTokens)); Buy(recipient, recievedTokens, weiPayment); return weiPayment; } function sendETHToMultiSig(uint value) internal { gripWallet.transfer(value); } event FinalizeSale(); // function is callable by everyone function finalizeSale() { require(saleEnded()); require(msg.sender == admin); // burn remaining tokens token.burn(token.balanceOf(this)); FinalizeSale(); } // ETH balance is always expected to be 0. // but in case something went wrong, we use this function to extract the eth. function emergencyDrain(ERC20 anyToken) returns (bool){ require(msg.sender == admin); require(saleEnded()); if (this.balance > 0) { sendETHToMultiSig(this.balance); } if (anyToken != address(0x0)) { assert(anyToken.transfer(gripWallet, anyToken.balanceOf(this))); } return true; } // just to check that funds goes to the right place // tokens are not given in return function debugBuy() payable { require(msg.value == 123); sendETHToMultiSig(msg.value); } }
Presale not started yet Both presale and public sale have ended Presale Presale cap limit reached Presale cap almost reached Public sale Public sale cap limit reached Public sale cap almost reached Public sale cap is bigger than contribution
function eligible(address contributor, uint amountInWei) constant returns (uint) { if (now < presaleStartTime) return 0; if (now >= openSaleEndTime) return 0; if (now < openSaleStartTime) { if (remainingPresaleCap <= 0) { return 0; } if (remainedCap > remainingPresaleCap) { remainedCap = remainingPresaleCap; } } else { if (remainingPublicSaleCap <= 0) { return 0; } if (amountInWei > remainingPublicSaleCap) { return remainingPublicSaleCap; } else { return amountInWei; } } }
12,633,517
./partial_match/1/0x99B52db75A2C37efA07C3867eC5811B9D878D4e3/sources/VaultStaking.sol
Function for users to extend lock. Staking Duration must be valid. Does not require any token transfer and immediately gives new bonus.
function extendLock(uint48 _stakingDurationInDays) external nonReentrant { User memory user = users[msg.sender]; require(!user.blacklisted, "Blacklisted"); require(stakingPeriodsInDays.contains(_stakingDurationInDays), "Invalid staking period"); require(user.stakingDuration <= _stakingDurationInDays, "Cannot stake for a shorter period of time"); user.stakingDuration = _stakingDurationInDays; user.holderUnlockTime = uint48(block.timestamp + (_stakingDurationInDays * 1 days)); setInternalBalance(msg.sender, user); users[msg.sender] = user; }
3,734,974
// File: contracts/IManager.sol pragma solidity ^0.5.11; contract IManager { event SetController(address controller); event ParameterUpdate(string param); function setController(address _controller) external; } // File: contracts/zeppelin/Ownable.sol pragma solidity ^0.5.11; /** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */ contract Ownable { address public owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ constructor() public { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) public onlyOwner { require(newOwner != address(0)); emit OwnershipTransferred(owner, newOwner); owner = newOwner; } } // File: contracts/zeppelin/Pausable.sol pragma solidity ^0.5.11; /** * @title Pausable * @dev Base contract which allows children to implement an emergency stop mechanism. */ contract Pausable is Ownable { event Pause(); event Unpause(); bool public paused = false; /** * @dev Modifier to make a function callable only when the contract is not paused. */ modifier whenNotPaused() { require(!paused); _; } /** * @dev Modifier to make a function callable only when the contract is paused. */ modifier whenPaused() { require(paused); _; } /** * @dev called by the owner to pause, triggers stopped state */ function pause() 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(); } } // File: contracts/IController.sol pragma solidity ^0.5.11; contract IController is Pausable { event SetContractInfo(bytes32 id, address contractAddress, bytes20 gitCommitHash); function setContractInfo(bytes32 _id, address _contractAddress, bytes20 _gitCommitHash) external; function updateController(bytes32 _id, address _controller) external; function getContract(bytes32 _id) public view returns (address); } // File: contracts/Manager.sol pragma solidity ^0.5.11; contract Manager is IManager { // Controller that contract is registered with IController public controller; // Check if sender is controller modifier onlyController() { require(msg.sender == address(controller), "caller must be Controller"); _; } // Check if sender is controller owner modifier onlyControllerOwner() { require(msg.sender == controller.owner(), "caller must be Controller owner"); _; } // Check if controller is not paused modifier whenSystemNotPaused() { require(!controller.paused(), "system is paused"); _; } // Check if controller is paused modifier whenSystemPaused() { require(controller.paused(), "system is not paused"); _; } constructor(address _controller) public { controller = IController(_controller); } /** * @notice Set controller. Only callable by current controller * @param _controller Controller contract address */ function setController(address _controller) external onlyController { controller = IController(_controller); emit SetController(_controller); } } // File: contracts/ManagerProxyTarget.sol pragma solidity ^0.5.11; /** * @title ManagerProxyTarget * @notice The base contract that target contracts used by a proxy contract should inherit from * @dev Both the target contract and the proxy contract (implemented as ManagerProxy) MUST inherit from ManagerProxyTarget in order to guarantee that both contracts have the same storage layout. Differing storage layouts in a proxy contract and target contract can potentially break the delegate proxy upgradeability mechanism */ contract ManagerProxyTarget is Manager { // Used to look up target contract address in controller's registry bytes32 public targetContractId; } // File: contracts/bonding/IBondingManager.sol pragma solidity ^0.5.11; /** * @title Interface for BondingManager * TODO: switch to interface type */ contract IBondingManager { event TranscoderUpdate(address indexed transcoder, uint256 rewardCut, uint256 feeShare); event TranscoderActivated(address indexed transcoder, uint256 activationRound); event TranscoderDeactivated(address indexed transcoder, uint256 deactivationRound); event TranscoderSlashed(address indexed transcoder, address finder, uint256 penalty, uint256 finderReward); event Reward(address indexed transcoder, uint256 amount); event Bond(address indexed newDelegate, address indexed oldDelegate, address indexed delegator, uint256 additionalAmount, uint256 bondedAmount); event Unbond(address indexed delegate, address indexed delegator, uint256 unbondingLockId, uint256 amount, uint256 withdrawRound); event Rebond(address indexed delegate, address indexed delegator, uint256 unbondingLockId, uint256 amount); event WithdrawStake(address indexed delegator, uint256 unbondingLockId, uint256 amount, uint256 withdrawRound); event WithdrawFees(address indexed delegator); event EarningsClaimed(address indexed delegate, address indexed delegator, uint256 rewards, uint256 fees, uint256 startRound, uint256 endRound); // Deprecated events // These event signatures can be used to construct the appropriate topic hashes to filter for past logs corresponding // to these deprecated events. // event Bond(address indexed delegate, address indexed delegator); // event Unbond(address indexed delegate, address indexed delegator); // event WithdrawStake(address indexed delegator); // event TranscoderUpdate(address indexed transcoder, uint256 pendingRewardCut, uint256 pendingFeeShare, uint256 pendingPricePerSegment, bool registered); // event TranscoderEvicted(address indexed transcoder); // event TranscoderResigned(address indexed transcoder); // External functions function updateTranscoderWithFees(address _transcoder, uint256 _fees, uint256 _round) external; function slashTranscoder(address _transcoder, address _finder, uint256 _slashAmount, uint256 _finderFee) external; function setCurrentRoundTotalActiveStake() external; // Public functions function getTranscoderPoolSize() public view returns (uint256); function transcoderTotalStake(address _transcoder) public view returns (uint256); function isActiveTranscoder(address _transcoder) public view returns (bool); function getTotalBonded() public view returns (uint256); } // File: openzeppelin-solidity/contracts/math/SafeMath.sol pragma solidity ^0.5.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { 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; } } // File: contracts/libraries/SortedDoublyLL.sol pragma solidity ^0.5.11; /** * @title A sorted doubly linked list with nodes sorted in descending order. Optionally accepts insert position hints * * Given a new node with a `key`, a hint is of the form `(prevId, nextId)` s.t. `prevId` and `nextId` are adjacent in the list. * `prevId` is a node with a key >= `key` and `nextId` is a node with a key <= `key`. If the sender provides a hint that is a valid insert position * the insert operation is a constant time storage write. However, the provided hint in a given transaction might be a valid insert position, but if other transactions are included first, when * the given transaction is executed the provided hint may no longer be a valid insert position. For example, one of the nodes referenced might be removed or their keys may * be updated such that the the pair of nodes in the hint no longer represent a valid insert position. If one of the nodes in the hint becomes invalid, we still try to use the other * valid node as a starting point for finding the appropriate insert position. If both nodes in the hint become invalid, we use the head of the list as a starting point * to find the appropriate insert position. */ library SortedDoublyLL { using SafeMath for uint256; // Information for a node in the list struct Node { uint256 key; // Node's key used for sorting address nextId; // Id of next node (smaller key) in the list address prevId; // Id of previous node (larger key) in the list } // Information for the list struct Data { address head; // Head of the list. Also the node in the list with the largest key address tail; // Tail of the list. Also the node in the list with the smallest key uint256 maxSize; // Maximum size of the list uint256 size; // Current size of the list mapping (address => Node) nodes; // Track the corresponding ids for each node in the list } /** * @dev Set the maximum size of the list * @param _size Maximum size */ function setMaxSize(Data storage self, uint256 _size) public { require(_size > self.maxSize, "new max size must be greater than old max size"); self.maxSize = _size; } /** * @dev Add a node to the list * @param _id Node's id * @param _key Node's key * @param _prevId Id of previous node for the insert position * @param _nextId Id of next node for the insert position */ function insert(Data storage self, address _id, uint256 _key, address _prevId, address _nextId) public { // List must not be full require(!isFull(self), "list is full"); // List must not already contain node require(!contains(self, _id), "node already in list"); // Node id must not be null require(_id != address(0), "node id is null"); // Key must be non-zero require(_key > 0, "key is zero"); address prevId = _prevId; address nextId = _nextId; if (!validInsertPosition(self, _key, prevId, nextId)) { // Sender's hint was not a valid insert position // Use sender's hint to find a valid insert position (prevId, nextId) = findInsertPosition(self, _key, prevId, nextId); } self.nodes[_id].key = _key; if (prevId == address(0) && nextId == address(0)) { // Insert as head and tail self.head = _id; self.tail = _id; } else if (prevId == address(0)) { // Insert before `prevId` as the head self.nodes[_id].nextId = self.head; self.nodes[self.head].prevId = _id; self.head = _id; } else if (nextId == address(0)) { // Insert after `nextId` as the tail self.nodes[_id].prevId = self.tail; self.nodes[self.tail].nextId = _id; self.tail = _id; } else { // Insert at insert position between `prevId` and `nextId` self.nodes[_id].nextId = nextId; self.nodes[_id].prevId = prevId; self.nodes[prevId].nextId = _id; self.nodes[nextId].prevId = _id; } self.size = self.size.add(1); } /** * @dev Remove a node from the list * @param _id Node's id */ function remove(Data storage self, address _id) public { // List must contain the node require(contains(self, _id), "node not in list"); if (self.size > 1) { // List contains more than a single node if (_id == self.head) { // The removed node is the head // Set head to next node self.head = self.nodes[_id].nextId; // Set prev pointer of new head to null self.nodes[self.head].prevId = address(0); } else if (_id == self.tail) { // The removed node is the tail // Set tail to previous node self.tail = self.nodes[_id].prevId; // Set next pointer of new tail to null self.nodes[self.tail].nextId = address(0); } else { // The removed node is neither the head nor the tail // Set next pointer of previous node to the next node self.nodes[self.nodes[_id].prevId].nextId = self.nodes[_id].nextId; // Set prev pointer of next node to the previous node self.nodes[self.nodes[_id].nextId].prevId = self.nodes[_id].prevId; } } else { // List contains a single node // Set the head and tail to null self.head = address(0); self.tail = address(0); } delete self.nodes[_id]; self.size = self.size.sub(1); } /** * @dev Update the key of a node in the list * @param _id Node's id * @param _newKey Node's new key * @param _prevId Id of previous node for the new insert position * @param _nextId Id of next node for the new insert position */ function updateKey(Data storage self, address _id, uint256 _newKey, address _prevId, address _nextId) public { // List must contain the node require(contains(self, _id), "node not in list"); // Remove node from the list remove(self, _id); if (_newKey > 0) { // Insert node if it has a non-zero key insert(self, _id, _newKey, _prevId, _nextId); } } /** * @dev Checks if the list contains a node * @param _id Address of transcoder * @return true if '_id' is in list */ function contains(Data storage self, address _id) public view returns (bool) { // List only contains non-zero keys, so if key is non-zero the node exists return self.nodes[_id].key > 0; } /** * @dev Checks if the list is full * @return true if list is full */ function isFull(Data storage self) public view returns (bool) { return self.size == self.maxSize; } /** * @dev Checks if the list is empty * @return true if list is empty */ function isEmpty(Data storage self) public view returns (bool) { return self.size == 0; } /** * @dev Returns the current size of the list * @return current size of the list */ function getSize(Data storage self) public view returns (uint256) { return self.size; } /** * @dev Returns the maximum size of the list */ function getMaxSize(Data storage self) public view returns (uint256) { return self.maxSize; } /** * @dev Returns the key of a node in the list * @param _id Node's id * @return key for node with '_id' */ function getKey(Data storage self, address _id) public view returns (uint256) { return self.nodes[_id].key; } /** * @dev Returns the first node in the list (node with the largest key) * @return address for the head of the list */ function getFirst(Data storage self) public view returns (address) { return self.head; } /** * @dev Returns the last node in the list (node with the smallest key) * @return address for the tail of the list */ function getLast(Data storage self) public view returns (address) { return self.tail; } /** * @dev Returns the next node (with a smaller key) in the list for a given node * @param _id Node's id * @return address for the node following node in list with '_id' */ function getNext(Data storage self, address _id) public view returns (address) { return self.nodes[_id].nextId; } /** * @dev Returns the previous node (with a larger key) in the list for a given node * @param _id Node's id * address for the node before node in list with '_id' */ function getPrev(Data storage self, address _id) public view returns (address) { return self.nodes[_id].prevId; } /** * @dev Check if a pair of nodes is a valid insertion point for a new node with the given key * @param _key Node's key * @param _prevId Id of previous node for the insert position * @param _nextId Id of next node for the insert position * @return if the insert position is valid */ function validInsertPosition(Data storage self, uint256 _key, address _prevId, address _nextId) public view returns (bool) { if (_prevId == address(0) && _nextId == address(0)) { // `(null, null)` is a valid insert position if the list is empty return isEmpty(self); } else if (_prevId == address(0)) { // `(null, _nextId)` is a valid insert position if `_nextId` is the head of the list return self.head == _nextId && _key >= self.nodes[_nextId].key; } else if (_nextId == address(0)) { // `(_prevId, null)` is a valid insert position if `_prevId` is the tail of the list return self.tail == _prevId && _key <= self.nodes[_prevId].key; } else { // `(_prevId, _nextId)` is a valid insert position if they are adjacent nodes and `_key` falls between the two nodes' keys return self.nodes[_prevId].nextId == _nextId && self.nodes[_prevId].key >= _key && _key >= self.nodes[_nextId].key; } } /** * @dev Descend the list (larger keys to smaller keys) to find a valid insert position * @param _key Node's key * @param _startId Id of node to start ascending the list from */ function descendList(Data storage self, uint256 _key, address _startId) private view returns (address, address) { // If `_startId` is the head, check if the insert position is before the head if (self.head == _startId && _key >= self.nodes[_startId].key) { return (address(0), _startId); } address prevId = _startId; address nextId = self.nodes[prevId].nextId; // Descend the list until we reach the end or until we find a valid insert position while (prevId != address(0) && !validInsertPosition(self, _key, prevId, nextId)) { prevId = self.nodes[prevId].nextId; nextId = self.nodes[prevId].nextId; } return (prevId, nextId); } /** * @dev Ascend the list (smaller keys to larger keys) to find a valid insert position * @param _key Node's key * @param _startId Id of node to start descending the list from */ function ascendList(Data storage self, uint256 _key, address _startId) private view returns (address, address) { // If `_startId` is the tail, check if the insert position is after the tail if (self.tail == _startId && _key <= self.nodes[_startId].key) { return (_startId, address(0)); } address nextId = _startId; address prevId = self.nodes[nextId].prevId; // Ascend the list until we reach the end or until we find a valid insertion point while (nextId != address(0) && !validInsertPosition(self, _key, prevId, nextId)) { nextId = self.nodes[nextId].prevId; prevId = self.nodes[nextId].prevId; } return (prevId, nextId); } /** * @dev Find the insert position for a new node with the given key * @param _key Node's key * @param _prevId Id of previous node for the insert position * @param _nextId Id of next node for the insert position */ function findInsertPosition(Data storage self, uint256 _key, address _prevId, address _nextId) private view returns (address, address) { address prevId = _prevId; address nextId = _nextId; if (prevId != address(0)) { if (!contains(self, prevId) || _key > self.nodes[prevId].key) { // `prevId` does not exist anymore or now has a smaller key than the given key prevId = address(0); } } if (nextId != address(0)) { if (!contains(self, nextId) || _key < self.nodes[nextId].key) { // `nextId` does not exist anymore or now has a larger key than the given key nextId = address(0); } } if (prevId == address(0) && nextId == address(0)) { // No hint - descend list starting from head return descendList(self, _key, self.head); } else if (prevId == address(0)) { // No `prevId` for hint - ascend list starting from `nextId` return ascendList(self, _key, nextId); } else if (nextId == address(0)) { // No `nextId` for hint - descend list starting from `prevId` return descendList(self, _key, prevId); } else { // Descend list starting from `prevId` return descendList(self, _key, prevId); } } } // File: contracts/libraries/MathUtils.sol pragma solidity ^0.5.11; library MathUtils { using SafeMath for uint256; // Divisor used for representing percentages uint256 public constant PERC_DIVISOR = 1000000; /** * @dev Returns whether an amount is a valid percentage out of PERC_DIVISOR * @param _amount Amount that is supposed to be a percentage */ function validPerc(uint256 _amount) internal pure returns (bool) { return _amount <= PERC_DIVISOR; } /** * @dev Compute percentage of a value with the percentage represented by a fraction * @param _amount Amount to take the percentage of * @param _fracNum Numerator of fraction representing the percentage * @param _fracDenom Denominator of fraction representing the percentage */ function percOf(uint256 _amount, uint256 _fracNum, uint256 _fracDenom) internal pure returns (uint256) { return _amount.mul(percPoints(_fracNum, _fracDenom)).div(PERC_DIVISOR); } /** * @dev Compute percentage of a value with the percentage represented by a fraction over PERC_DIVISOR * @param _amount Amount to take the percentage of * @param _fracNum Numerator of fraction representing the percentage with PERC_DIVISOR as the denominator */ function percOf(uint256 _amount, uint256 _fracNum) internal pure returns (uint256) { return _amount.mul(_fracNum).div(PERC_DIVISOR); } /** * @dev Compute percentage representation of a fraction * @param _fracNum Numerator of fraction represeting the percentage * @param _fracDenom Denominator of fraction represeting the percentage */ function percPoints(uint256 _fracNum, uint256 _fracDenom) internal pure returns (uint256) { return _fracNum.mul(PERC_DIVISOR).div(_fracDenom); } } // File: contracts/bonding/libraries/EarningsPool.sol pragma solidity ^0.5.11; /** * @title EarningsPool * @dev Manages reward and fee pools for delegators and transcoders */ library EarningsPool { using SafeMath for uint256; // Represents rewards and fees to be distributed to delegators // The `hasTranscoderRewardFeePool` flag was introduced so that EarningsPool.Data structs used by the BondingManager // created with older versions of this library can be differentiated from EarningsPool.Data structs used by the BondingManager // created with a newer version of this library. If the flag is true, then the struct was initialized using the `init` function // using a newer version of this library meaning that it is using separate transcoder reward and fee pools struct Data { uint256 rewardPool; // Delegator rewards. If `hasTranscoderRewardFeePool` is false, this will contain transcoder rewards as well uint256 feePool; // Delegator fees. If `hasTranscoderRewardFeePool` is false, this will contain transcoder fees as well uint256 totalStake; // Transcoder's total stake during the earnings pool's round uint256 claimableStake; // Stake that can be used to claim portions of the fee and reward pools uint256 transcoderRewardCut; // Transcoder's reward cut during the earnings pool's round uint256 transcoderFeeShare; // Transcoder's fee share during the earnings pool's round uint256 transcoderRewardPool; // Transcoder rewards. If `hasTranscoderRewardFeePool` is false, this should always be 0 uint256 transcoderFeePool; // Transcoder fees. If `hasTranscoderRewardFeePool` is false, this should always be 0 bool hasTranscoderRewardFeePool; // Flag to indicate if the earnings pool has separate transcoder reward and fee pools // LIP-36 (https://github.com/livepeer/LIPs/blob/master/LIPs/LIP-36.md) fields // See EarningsPoolLIP36.sol uint256 cumulativeRewardFactor; uint256 cumulativeFeeFactor; } /** * @dev Sets transcoderRewardCut and transcoderFeeshare for an EarningsPool * @param earningsPool Storage pointer to EarningsPool struct * @param _rewardCut Reward cut of transcoder during the earnings pool's round * @param _feeShare Fee share of transcoder during the earnings pool's round */ function setCommission(EarningsPool.Data storage earningsPool, uint256 _rewardCut, uint256 _feeShare) internal { earningsPool.transcoderRewardCut = _rewardCut; earningsPool.transcoderFeeShare = _feeShare; // Prior to LIP-36, we set this flag to true here to differentiate between EarningsPool structs created using older versions of this library. // When using a version of this library after the introduction of this flag to read an EarningsPool struct created using an older version // of this library, this flag should be false in the returned struct because the default value for EVM storage is 0 // earningsPool.hasTranscoderRewardFeePool = true; } /** * @dev Sets totalStake for an EarningsPool * @param earningsPool Storage pointer to EarningsPool struct * @param _stake Total stake of the transcoder during the earnings pool's round */ function setStake(EarningsPool.Data storage earningsPool, uint256 _stake) internal { earningsPool.totalStake = _stake; // Prior to LIP-36, we also set the claimableStake // earningsPool.claimableStake = _stake; } /** * @dev Return whether this earnings pool has claimable shares i.e. is there unclaimed stake * @param earningsPool Storage pointer to EarningsPool struct */ function hasClaimableShares(EarningsPool.Data storage earningsPool) internal view returns (bool) { return earningsPool.claimableStake > 0; } /** * @dev Returns the fee pool share for a claimant. If the claimant is a transcoder, include transcoder fees as well. * @param earningsPool Storage pointer to EarningsPool struct * @param _stake Stake of claimant * @param _isTranscoder Flag indicating whether the claimant is a transcoder */ function feePoolShare(EarningsPool.Data storage earningsPool, uint256 _stake, bool _isTranscoder) internal view returns (uint256) { uint256 delegatorFees = 0; uint256 transcoderFees = 0; if (earningsPool.hasTranscoderRewardFeePool) { (delegatorFees, transcoderFees) = feePoolShareWithTranscoderRewardFeePool(earningsPool, _stake, _isTranscoder); } else { (delegatorFees, transcoderFees) = feePoolShareNoTranscoderRewardFeePool(earningsPool, _stake, _isTranscoder); } return delegatorFees.add(transcoderFees); } /** * @dev Returns the reward pool share for a claimant. If the claimant is a transcoder, include transcoder rewards as well. * @param earningsPool Storage pointer to EarningsPool struct * @param _stake Stake of claimant * @param _isTranscoder Flag indicating whether the claimant is a transcoder */ function rewardPoolShare(EarningsPool.Data storage earningsPool, uint256 _stake, bool _isTranscoder) internal view returns (uint256) { uint256 delegatorRewards = 0; uint256 transcoderRewards = 0; if (earningsPool.hasTranscoderRewardFeePool) { (delegatorRewards, transcoderRewards) = rewardPoolShareWithTranscoderRewardFeePool(earningsPool, _stake, _isTranscoder); } else { (delegatorRewards, transcoderRewards) = rewardPoolShareNoTranscoderRewardFeePool(earningsPool, _stake, _isTranscoder); } return delegatorRewards.add(transcoderRewards); } /** * @dev Helper function to calculate fee pool share if the earnings pool has a separate transcoder fee pool * @param earningsPool Storage pointer to EarningsPool struct * @param _stake Stake of claimant * @param _isTranscoder Flag indicating whether the claimant is a transcoder */ function feePoolShareWithTranscoderRewardFeePool( EarningsPool.Data storage earningsPool, uint256 _stake, bool _isTranscoder ) internal view returns (uint256, uint256) { // If there is no claimable stake, the fee pool share is 0 // If there is claimable stake, calculate fee pool share based on remaining amount in fee pool, remaining claimable stake and claimant's stake uint256 delegatorFees = earningsPool.claimableStake > 0 ? MathUtils.percOf(earningsPool.feePool, _stake, earningsPool.claimableStake) : 0; // If claimant is a transcoder, include transcoder fee pool as well return _isTranscoder ? (delegatorFees, earningsPool.transcoderFeePool) : (delegatorFees, 0); } /** * @dev Helper function to calculate reward pool share if the earnings pool has a separate transcoder reward pool * @param earningsPool Storage pointer to EarningsPool struct * @param _stake Stake of claimant * @param _isTranscoder Flag indicating whether the claimant is a transcoder */ function rewardPoolShareWithTranscoderRewardFeePool( EarningsPool.Data storage earningsPool, uint256 _stake, bool _isTranscoder ) internal view returns (uint256, uint256) { // If there is no claimable stake, the reward pool share is 0 // If there is claimable stake, calculate reward pool share based on remaining amount in reward pool, remaining claimable stake and claimant's stake uint256 delegatorRewards = earningsPool.claimableStake > 0 ? MathUtils.percOf(earningsPool.rewardPool, _stake, earningsPool.claimableStake) : 0; // If claimant is a transcoder, include transcoder reward pool as well return _isTranscoder ? (delegatorRewards, earningsPool.transcoderRewardPool) : (delegatorRewards, 0); } /** * @dev Helper function to calculate the fee pool share if the earnings pool does not have a separate transcoder fee pool * This implements calculation logic from a previous version of this library * @param earningsPool Storage pointer to EarningsPool struct * @param _stake Stake of claimant * @param _isTranscoder Flag indicating whether the claimant is a transcoder */ function feePoolShareNoTranscoderRewardFeePool( EarningsPool.Data storage earningsPool, uint256 _stake, bool _isTranscoder ) internal view returns (uint256, uint256) { uint256 transcoderFees = 0; uint256 delegatorFees = 0; if (earningsPool.claimableStake > 0) { uint256 delegatorsFees = MathUtils.percOf(earningsPool.feePool, earningsPool.transcoderFeeShare); transcoderFees = earningsPool.feePool.sub(delegatorsFees); delegatorFees = MathUtils.percOf(delegatorsFees, _stake, earningsPool.claimableStake); } if (_isTranscoder) { return (delegatorFees, transcoderFees); } else { return (delegatorFees, 0); } } /** * @dev Helper function to calculate the reward pool share if the earnings pool does not have a separate transcoder reward pool * This implements calculation logic from a previous version of this library * @param earningsPool Storage pointer to EarningsPool struct * @param _stake Stake of claimant * @param _isTranscoder Flag indicating whether the claimant is a transcoder */ function rewardPoolShareNoTranscoderRewardFeePool( EarningsPool.Data storage earningsPool, uint256 _stake, bool _isTranscoder ) internal view returns (uint256, uint256) { uint256 transcoderRewards = 0; uint256 delegatorRewards = 0; if (earningsPool.claimableStake > 0) { transcoderRewards = MathUtils.percOf(earningsPool.rewardPool, earningsPool.transcoderRewardCut); delegatorRewards = MathUtils.percOf(earningsPool.rewardPool.sub(transcoderRewards), _stake, earningsPool.claimableStake); } if (_isTranscoder) { return (delegatorRewards, transcoderRewards); } else { return (delegatorRewards, 0); } } } // File: contracts/bonding/libraries/EarningsPoolLIP36.sol pragma solidity ^0.5.11; library EarningsPoolLIP36 { using SafeMath for uint256; /** * @notice Update the cumulative fee factor stored in an earnings pool with new fees * @param earningsPool Storage pointer to EarningsPools.Data struct * @param _prevEarningsPool In-memory EarningsPool.Data struct that stores the previous cumulative reward and fee factors * @param _fees Amount of new fees */ function updateCumulativeFeeFactor(EarningsPool.Data storage earningsPool, EarningsPool.Data memory _prevEarningsPool, uint256 _fees) internal { uint256 prevCumulativeFeeFactor = _prevEarningsPool.cumulativeFeeFactor; uint256 prevCumulativeRewardFactor = _prevEarningsPool.cumulativeRewardFactor != 0 ? _prevEarningsPool.cumulativeRewardFactor : MathUtils.percPoints(1,1); // Initialize the cumulativeFeeFactor when adding fees for the first time if (earningsPool.cumulativeFeeFactor == 0) { earningsPool.cumulativeFeeFactor = prevCumulativeFeeFactor.add( MathUtils.percOf(prevCumulativeRewardFactor, _fees, earningsPool.totalStake) ); return; } earningsPool.cumulativeFeeFactor = earningsPool.cumulativeFeeFactor.add( MathUtils.percOf(prevCumulativeRewardFactor, _fees, earningsPool.totalStake) ); } /** * @notice Update the cumulative reward factor stored in an earnings pool with new rewards * @param earningsPool Storage pointer to EarningsPool.Data struct * @param _prevEarningsPool Storage pointer to EarningsPool.Data struct that stores the previous cumulative reward factor * @param _rewards Amount of new rewards */ function updateCumulativeRewardFactor(EarningsPool.Data storage earningsPool, EarningsPool.Data storage _prevEarningsPool, uint256 _rewards) internal { uint256 prevCumulativeRewardFactor = _prevEarningsPool.cumulativeRewardFactor != 0 ? _prevEarningsPool.cumulativeRewardFactor : MathUtils.percPoints(1,1); earningsPool.cumulativeRewardFactor = prevCumulativeRewardFactor.add( MathUtils.percOf(prevCumulativeRewardFactor, _rewards, earningsPool.totalStake) ); } } // File: openzeppelin-solidity/contracts/token/ERC20/IERC20.sol pragma solidity ^0.5.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. Does not include * the optional functions; to access them see `ERC20Detailed`. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a `Transfer` event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through `transferFrom`. This is * zero by default. * * This value changes when `approve` or `transferFrom` are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * > Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an `Approval` event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a `Transfer` event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to `approve`. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // File: openzeppelin-solidity/contracts/token/ERC20/ERC20.sol pragma solidity ^0.5.0; /** * @dev Implementation of the `IERC20` interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using `_mint`. * For a generic mechanism see `ERC20Mintable`. * * *For a detailed writeup see our guide [How to implement supply * mechanisms](https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226).* * * 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 IERC20 { using SafeMath for uint256; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; /** * @dev See `IERC20.totalSupply`. */ function totalSupply() public view returns (uint256) { return _totalSupply; } /** * @dev See `IERC20.balanceOf`. */ function balanceOf(address account) public view returns (uint256) { return _balances[account]; } /** * @dev See `IERC20.transfer`. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public returns (bool) { _transfer(msg.sender, recipient, amount); return true; } /** * @dev See `IERC20.allowance`. */ function allowance(address owner, address spender) public view returns (uint256) { return _allowances[owner][spender]; } /** * @dev See `IERC20.approve`. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 value) public returns (bool) { _approve(msg.sender, spender, value); 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 `value`. * - the caller must have allowance for `sender`'s tokens of at least * `amount`. */ function transferFrom(address sender, address recipient, uint256 amount) public returns (bool) { _transfer(sender, recipient, amount); _approve(sender, msg.sender, _allowances[sender][msg.sender].sub(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 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)); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to `transfer`, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a `Transfer` event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer(address sender, address recipient, uint256 amount) internal { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _balances[sender] = _balances[sender].sub(amount); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a `Transfer` event with `from` set to the zero address. * * Requirements * * - `to` cannot be the zero address. */ function _mint(address account, uint256 amount) internal { require(account != address(0), "ERC20: mint to the zero address"); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } /** * @dev Destoys `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 value) internal { require(account != address(0), "ERC20: burn from the zero address"); _totalSupply = _totalSupply.sub(value); _balances[account] = _balances[account].sub(value); emit Transfer(account, address(0), value); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner`s tokens. * * This is internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an `Approval` event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve(address owner, address spender, uint256 value) internal { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = value; emit Approval(owner, spender, value); } /** * @dev Destoys `amount` tokens from `account`.`amount` is then deducted * from the caller's allowance. * * See `_burn` and `_approve`. */ function _burnFrom(address account, uint256 amount) internal { _burn(account, amount); _approve(account, msg.sender, _allowances[account][msg.sender].sub(amount)); } } // File: contracts/token/ILivepeerToken.sol pragma solidity ^0.5.11; contract ILivepeerToken is ERC20, Ownable { function mint(address _to, uint256 _amount) public returns (bool); function burn(uint256 _amount) public; } // File: contracts/token/IMinter.sol pragma solidity ^0.5.11; /** * @title Minter interface */ contract IMinter { // Events event SetCurrentRewardTokens(uint256 currentMintableTokens, uint256 currentInflation); // External functions function createReward(uint256 _fracNum, uint256 _fracDenom) external returns (uint256); function trustedTransferTokens(address _to, uint256 _amount) external; function trustedBurnTokens(uint256 _amount) external; function trustedWithdrawETH(address payable _to, uint256 _amount) external; function depositETH() external payable returns (bool); function setCurrentRewardTokens() external; function currentMintableTokens() external view returns (uint256); function currentMintedTokens() external view returns (uint256); // Public functions function getController() public view returns (IController); } // File: contracts/rounds/IRoundsManager.sol pragma solidity ^0.5.11; /** * @title RoundsManager interface */ contract IRoundsManager { // Events event NewRound(uint256 indexed round, bytes32 blockHash); // Deprecated events // These event signatures can be used to construct the appropriate topic hashes to filter for past logs corresponding // to these deprecated events. // event NewRound(uint256 round) // External functions function initializeRound() external; function lipUpgradeRound(uint256 _lip) external view returns (uint256); // Public functions function blockNum() public view returns (uint256); function blockHash(uint256 _block) public view returns (bytes32); function blockHashForRound(uint256 _round) public view returns (bytes32); function currentRound() public view returns (uint256); function currentRoundStartBlock() public view returns (uint256); function currentRoundInitialized() public view returns (bool); function currentRoundLocked() public view returns (bool); } // File: contracts/bonding/BondingManager.sol pragma solidity 0.5.11; /** * @title BondingManager * @notice Manages bonding, transcoder and rewards/fee accounting related operations of the Livepeer protocol */ contract BondingManager is ManagerProxyTarget, IBondingManager { using SafeMath for uint256; using SortedDoublyLL for SortedDoublyLL.Data; using EarningsPool for EarningsPool.Data; using EarningsPoolLIP36 for EarningsPool.Data; // Constants // Occurances are replaced at compile time // and computed to a single value if possible by the optimizer uint256 constant MAX_FUTURE_ROUND = 2**256 - 1; // Time between unbonding and possible withdrawl in rounds uint64 public unbondingPeriod; // DEPRECATED - DO NOT USE uint256 public numActiveTranscodersDEPRECATED; // Max number of rounds that a caller can claim earnings for at once uint256 public maxEarningsClaimsRounds; // Represents a transcoder's current state struct Transcoder { uint256 lastRewardRound; // Last round that the transcoder called reward uint256 rewardCut; // % of reward paid to transcoder by a delegator uint256 feeShare; // % of fees paid to delegators by transcoder uint256 pricePerSegmentDEPRECATED; // DEPRECATED - DO NOT USE uint256 pendingRewardCutDEPRECATED; // DEPRECATED - DO NOT USE uint256 pendingFeeShareDEPRECATED; // DEPRECATED - DO NOT USE uint256 pendingPricePerSegmentDEPRECATED; // DEPRECATED - DO NOT USE mapping (uint256 => EarningsPool.Data) earningsPoolPerRound; // Mapping of round => earnings pool for the round uint256 lastActiveStakeUpdateRound; // Round for which the stake was last updated while the transcoder is active uint256 activationRound; // Round in which the transcoder became active - 0 if inactive uint256 deactivationRound; // Round in which the transcoder will become inactive uint256 activeCumulativeRewards; // The transcoder's cumulative rewards that are active in the current round uint256 cumulativeRewards; // The transcoder's cumulative rewards (earned via the its active staked rewards and its reward cut). uint256 cumulativeFees; // The transcoder's cumulative fees (earned via the its active staked rewards and its fee share) uint256 lastFeeRound; // Latest round in which the transcoder received fees } // The various states a transcoder can be in enum TranscoderStatus { NotRegistered, Registered } // Represents a delegator's current state struct Delegator { uint256 bondedAmount; // The amount of bonded tokens uint256 fees; // The amount of fees collected address delegateAddress; // The address delegated to uint256 delegatedAmount; // The amount of tokens delegated to the delegator uint256 startRound; // The round the delegator transitions to bonded phase and is delegated to someone uint256 withdrawRoundDEPRECATED; // DEPRECATED - DO NOT USE uint256 lastClaimRound; // The last round during which the delegator claimed its earnings uint256 nextUnbondingLockId; // ID for the next unbonding lock created mapping (uint256 => UnbondingLock) unbondingLocks; // Mapping of unbonding lock ID => unbonding lock } // The various states a delegator can be in enum DelegatorStatus { Pending, Bonded, Unbonded } // Represents an amount of tokens that are being unbonded struct UnbondingLock { uint256 amount; // Amount of tokens being unbonded uint256 withdrawRound; // Round at which unbonding period is over and tokens can be withdrawn } // Keep track of the known transcoders and delegators mapping (address => Delegator) private delegators; mapping (address => Transcoder) private transcoders; // DEPRECATED - DO NOT USE // The function getTotalBonded() no longer uses this variable // and instead calculates the total bonded value separately uint256 private totalBondedDEPRECATED; // DEPRECATED - DO NOT USE SortedDoublyLL.Data private transcoderPoolDEPRECATED; // DEPRECATED - DO NOT USE struct ActiveTranscoderSetDEPRECATED { address[] transcoders; mapping (address => bool) isActive; uint256 totalStake; } // DEPRECATED - DO NOT USE mapping (uint256 => ActiveTranscoderSetDEPRECATED) public activeTranscoderSetDEPRECATED; // The total active stake (sum of the stake of active set members) for the current round uint256 public currentRoundTotalActiveStake; // The total active stake (sum of the stake of active set members) for the next round uint256 public nextRoundTotalActiveStake; // The transcoder pool is used to keep track of the transcoders that are eligible for activation. // The pool keeps track of the pending active set in round N and the start of round N + 1 transcoders // in the pool are locked into the active set for round N + 1 SortedDoublyLL.Data private transcoderPoolV2; // Check if sender is TicketBroker modifier onlyTicketBroker() { require( msg.sender == controller.getContract(keccak256("TicketBroker")), "caller must be TicketBroker" ); _; } // Check if sender is RoundsManager modifier onlyRoundsManager() { require( msg.sender == controller.getContract(keccak256("RoundsManager")), "caller must be RoundsManager" ); _; } // Check if sender is Verifier modifier onlyVerifier() { require(msg.sender == controller.getContract(keccak256("Verifier")), "caller must be Verifier"); _; } // Check if current round is initialized modifier currentRoundInitialized() { require(roundsManager().currentRoundInitialized(), "current round is not initialized"); _; } // Automatically claim earnings from lastClaimRound through the current round modifier autoClaimEarnings() { uint256 currentRound = roundsManager().currentRound(); uint256 lastClaimRound = delegators[msg.sender].lastClaimRound; if (lastClaimRound < currentRound) { updateDelegatorWithEarnings(msg.sender, currentRound, lastClaimRound); } _; } /** * @notice BondingManager constructor. Only invokes constructor of base Manager contract with provided Controller address * @dev This constructor will not initialize any state variables besides `controller`. The following setter functions * should be used to initialize state variables post-deployment: * - setUnbondingPeriod() * - setNumActiveTranscoders() * - setMaxEarningsClaimsRounds() * @param _controller Address of Controller that this contract will be registered with */ constructor(address _controller) public Manager(_controller) {} /** * @notice Set unbonding period. Only callable by Controller owner * @param _unbondingPeriod Rounds between unbonding and possible withdrawal */ function setUnbondingPeriod(uint64 _unbondingPeriod) external onlyControllerOwner { unbondingPeriod = _unbondingPeriod; emit ParameterUpdate("unbondingPeriod"); } /** * @notice Set maximum number of active transcoders. Only callable by Controller owner * @param _numActiveTranscoders Number of active transcoders */ function setNumActiveTranscoders(uint256 _numActiveTranscoders) external onlyControllerOwner { transcoderPoolV2.setMaxSize(_numActiveTranscoders); emit ParameterUpdate("numActiveTranscoders"); } /** * @notice Set max number of rounds a caller can claim earnings for at once. Only callable by Controller owner * @param _maxEarningsClaimsRounds Max number of rounds a caller can claim earnings for at once */ function setMaxEarningsClaimsRounds(uint256 _maxEarningsClaimsRounds) external onlyControllerOwner { maxEarningsClaimsRounds = _maxEarningsClaimsRounds; emit ParameterUpdate("maxEarningsClaimsRounds"); } /** * @notice Sets commission rates as a transcoder and if the caller is not in the transcoder pool tries to add it * @dev Percentages are represented as numerators of fractions over MathUtils.PERC_DIVISOR * @param _rewardCut % of reward paid to transcoder by a delegator * @param _feeShare % of fees paid to delegators by a transcoder */ function transcoder(uint256 _rewardCut, uint256 _feeShare) external { transcoderWithHint(_rewardCut, _feeShare, address(0), address(0)); } /** * @notice Delegate stake towards a specific address * @param _amount The amount of tokens to stake * @param _to The address of the transcoder to stake towards */ function bond(uint256 _amount, address _to) external { bondWithHint( _amount, _to, address(0), address(0), address(0), address(0) ); } /** * @notice Unbond an amount of the delegator's bonded stake * @param _amount Amount of tokens to unbond */ function unbond(uint256 _amount) external { unbondWithHint(_amount, address(0), address(0)); } /** * @notice Rebond tokens for an unbonding lock to a delegator's current delegate while a delegator is in the Bonded or Pending status * @param _unbondingLockId ID of unbonding lock to rebond with */ function rebond(uint256 _unbondingLockId) external { rebondWithHint(_unbondingLockId, address(0), address(0)); } /** * @notice Rebond tokens for an unbonding lock to a delegate while a delegator is in the Unbonded status * @param _to Address of delegate * @param _unbondingLockId ID of unbonding lock to rebond with */ function rebondFromUnbonded(address _to, uint256 _unbondingLockId) external { rebondFromUnbondedWithHint(_to, _unbondingLockId, address(0), address(0)); } /** * @notice Withdraws tokens for an unbonding lock that has existed through an unbonding period * @param _unbondingLockId ID of unbonding lock to withdraw with */ function withdrawStake(uint256 _unbondingLockId) external whenSystemNotPaused currentRoundInitialized { Delegator storage del = delegators[msg.sender]; UnbondingLock storage lock = del.unbondingLocks[_unbondingLockId]; require(isValidUnbondingLock(msg.sender, _unbondingLockId), "invalid unbonding lock ID"); require(lock.withdrawRound <= roundsManager().currentRound(), "withdraw round must be before or equal to the current round"); uint256 amount = lock.amount; uint256 withdrawRound = lock.withdrawRound; // Delete unbonding lock delete del.unbondingLocks[_unbondingLockId]; // Tell Minter to transfer stake (LPT) to the delegator minter().trustedTransferTokens(msg.sender, amount); emit WithdrawStake(msg.sender, _unbondingLockId, amount, withdrawRound); } /** * @notice Withdraws fees to the caller */ function withdrawFees() external whenSystemNotPaused currentRoundInitialized autoClaimEarnings { uint256 fees = delegators[msg.sender].fees; require(fees > 0, "no fees to withdraw"); delegators[msg.sender].fees = 0; // Tell Minter to transfer fees (ETH) to the delegator minter().trustedWithdrawETH(msg.sender, fees); emit WithdrawFees(msg.sender); } /** * @notice Mint token rewards for an active transcoder and its delegators */ function reward() external { rewardWithHint(address(0), address(0)); } /** * @notice Update transcoder's fee pool. Only callable by the TicketBroker * @param _transcoder Transcoder address * @param _fees Fees to be added to the fee pool */ function updateTranscoderWithFees( address _transcoder, uint256 _fees, uint256 _round ) external whenSystemNotPaused onlyTicketBroker { // Silence unused param compiler warning _round; require(isRegisteredTranscoder(_transcoder), "transcoder must be registered"); uint256 currentRound = roundsManager().currentRound(); Transcoder storage t = transcoders[_transcoder]; uint256 lastRewardRound = t.lastRewardRound; uint256 activeCumulativeRewards = t.activeCumulativeRewards; // LIP-36: Add fees for the current round instead of '_round' // https://github.com/livepeer/LIPs/issues/35#issuecomment-673659199 EarningsPool.Data storage earningsPool = t.earningsPoolPerRound[currentRound]; EarningsPool.Data memory prevEarningsPool = latestCumulativeFactorsPool(t, currentRound.sub(1)); // if transcoder hasn't called 'reward()' for '_round' its 'transcoderFeeShare', 'transcoderRewardCut' and 'totalStake' // on the 'EarningsPool' for '_round' would not be initialized and the fee distribution wouldn't happen as expected // for cumulative fee calculation this would result in division by zero. if (currentRound > lastRewardRound) { earningsPool.setCommission( t.rewardCut, t.feeShare ); uint256 lastUpdateRound = t.lastActiveStakeUpdateRound; if (lastUpdateRound < currentRound) { earningsPool.setStake(t.earningsPoolPerRound[lastUpdateRound].totalStake); } // If reward() has not been called yet in the current round, then the transcoder's activeCumulativeRewards has not // yet been set in for the round. When the transcoder calls reward() its activeCumulativeRewards will be set to its // current cumulativeRewards. So, we can just use the transcoder's cumulativeRewards here because this will become // the transcoder's activeCumulativeRewards if it calls reward() later on in the current round activeCumulativeRewards = t.cumulativeRewards; } uint256 totalStake = earningsPool.totalStake; if (prevEarningsPool.cumulativeRewardFactor == 0 && lastRewardRound == currentRound) { // if transcoder called reward for 'currentRound' but not for 'currentRound - 1' (missed reward call) // retroactively calculate what its cumulativeRewardFactor would have been for 'currentRound - 1' (cfr. previous lastRewardRound for transcoder) // based on rewards for currentRound IMinter mtr = minter(); uint256 rewards = MathUtils.percOf(mtr.currentMintableTokens().add(mtr.currentMintedTokens()), totalStake, currentRoundTotalActiveStake); uint256 transcoderCommissionRewards = MathUtils.percOf(rewards, earningsPool.transcoderRewardCut); uint256 delegatorsRewards = rewards.sub(transcoderCommissionRewards); prevEarningsPool.cumulativeRewardFactor = MathUtils.percOf( earningsPool.cumulativeRewardFactor, totalStake, delegatorsRewards.add(totalStake) ); } uint256 delegatorsFees = MathUtils.percOf(_fees, earningsPool.transcoderFeeShare); uint256 transcoderCommissionFees = _fees.sub(delegatorsFees); // Calculate the fees earned by the transcoder's earned rewards uint256 transcoderRewardStakeFees = MathUtils.percOf(delegatorsFees, activeCumulativeRewards, totalStake); // Track fees earned by the transcoder based on its earned rewards and feeShare t.cumulativeFees = t.cumulativeFees.add(transcoderRewardStakeFees).add(transcoderCommissionFees); // Update cumulative fee factor with new fees // The cumulativeFeeFactor is used to calculate fees for all delegators including the transcoder (self-delegated) // Note that delegatorsFees includes transcoderRewardStakeFees, but no delegator will claim that amount using // the earnings claiming algorithm and instead that amount is accounted for in the transcoder's cumulativeFees field earningsPool.updateCumulativeFeeFactor(prevEarningsPool, delegatorsFees); t.lastFeeRound = currentRound; } /** * @notice Slash a transcoder. Only callable by the Verifier * @param _transcoder Transcoder address * @param _finder Finder that proved a transcoder violated a slashing condition. Null address if there is no finder * @param _slashAmount Percentage of transcoder bond to be slashed * @param _finderFee Percentage of penalty awarded to finder. Zero if there is no finder */ function slashTranscoder( address _transcoder, address _finder, uint256 _slashAmount, uint256 _finderFee ) external whenSystemNotPaused onlyVerifier { Delegator storage del = delegators[_transcoder]; if (del.bondedAmount > 0) { uint256 penalty = MathUtils.percOf(delegators[_transcoder].bondedAmount, _slashAmount); // If active transcoder, resign it if (transcoderPoolV2.contains(_transcoder)) { resignTranscoder(_transcoder); } // Decrease bonded stake del.bondedAmount = del.bondedAmount.sub(penalty); // If still bonded decrease delegate's delegated amount if (delegatorStatus(_transcoder) == DelegatorStatus.Bonded) { delegators[del.delegateAddress].delegatedAmount = delegators[del.delegateAddress].delegatedAmount.sub(penalty); } // Account for penalty uint256 burnAmount = penalty; // Award finder fee if there is a finder address if (_finder != address(0)) { uint256 finderAmount = MathUtils.percOf(penalty, _finderFee); minter().trustedTransferTokens(_finder, finderAmount); // Minter burns the slashed funds - finder reward minter().trustedBurnTokens(burnAmount.sub(finderAmount)); emit TranscoderSlashed(_transcoder, _finder, penalty, finderAmount); } else { // Minter burns the slashed funds minter().trustedBurnTokens(burnAmount); emit TranscoderSlashed(_transcoder, address(0), penalty, 0); } } else { emit TranscoderSlashed(_transcoder, _finder, 0, 0); } } /** * @notice Claim token pools shares for a delegator from its lastClaimRound through the end round * @param _endRound The last round for which to claim token pools shares for a delegator */ function claimEarnings(uint256 _endRound) external whenSystemNotPaused currentRoundInitialized { uint256 lastClaimRound = delegators[msg.sender].lastClaimRound; require(lastClaimRound < _endRound, "end round must be after last claim round"); require(_endRound <= roundsManager().currentRound(), "end round must be before or equal to current round"); updateDelegatorWithEarnings(msg.sender, _endRound, lastClaimRound); } /** * @notice Called during round initialization to set the total active stake for the round. Only callable by the RoundsManager */ function setCurrentRoundTotalActiveStake() external onlyRoundsManager { currentRoundTotalActiveStake = nextRoundTotalActiveStake; } /** * @notice Sets commission rates as a transcoder and if the caller is not in the transcoder pool tries to add it using an optional list hint * @dev Percentages are represented as numerators of fractions over MathUtils.PERC_DIVISOR. If the caller is going to be added to the pool, the * caller can provide an optional hint for the insertion position in the pool via the `_newPosPrev` and `_newPosNext` params. A linear search will * be executed starting at the hint to find the correct position - in the best case, the hint is the correct position so no search is executed. * See SortedDoublyLL.sol for details on list hints * @param _rewardCut % of reward paid to transcoder by a delegator * @param _feeShare % of fees paid to delegators by a transcoder * @param _newPosPrev Address of previous transcoder in pool if the caller joins the pool * @param _newPosNext Address of next transcoder in pool if the caller joins the pool */ function transcoderWithHint(uint256 _rewardCut, uint256 _feeShare, address _newPosPrev, address _newPosNext) public whenSystemNotPaused currentRoundInitialized { require( !roundsManager().currentRoundLocked(), "can't update transcoder params, current round is locked" ); require(MathUtils.validPerc(_rewardCut), "invalid rewardCut percentage"); require(MathUtils.validPerc(_feeShare), "invalid feeShare percentage"); require(isRegisteredTranscoder(msg.sender), "transcoder must be registered"); Transcoder storage t = transcoders[msg.sender]; uint256 currentRound = roundsManager().currentRound(); require( !isActiveTranscoder(msg.sender) || t.lastRewardRound == currentRound, "caller can't be active or must have already called reward for the current round" ); t.rewardCut = _rewardCut; t.feeShare = _feeShare; if (!transcoderPoolV2.contains(msg.sender)) { tryToJoinActiveSet(msg.sender, delegators[msg.sender].delegatedAmount, currentRound.add(1), _newPosPrev, _newPosNext); } emit TranscoderUpdate(msg.sender, _rewardCut, _feeShare); } /** * @notice Delegate stake towards a specific address and updates the transcoder pool using optional list hints if needed * @dev If the caller is decreasing the stake of its old delegate in the transcoder pool, the caller can provide an optional hint * for the insertion position of the old delegate via the `_oldDelegateNewPosPrev` and `_oldDelegateNewPosNext` params. * If the caller is delegating to a delegate that is in the transcoder pool, the caller can provide an optional hint for the * insertion position of the delegate via the `_currDelegateNewPosPrev` and `_currDelegateNewPosNext` params. * In both cases, a linear search will be executed starting at the hint to find the correct position. In the best case, the hint * is the correct position so no search is executed. See SortedDoublyLL.sol for details on list hints * @param _amount The amount of tokens to stake. * @param _to The address of the transcoder to stake towards * @param _oldDelegateNewPosPrev The address of the previous transcoder in the pool for the old delegate * @param _oldDelegateNewPosNext The address of the next transcoder in the pool for the old delegate * @param _currDelegateNewPosPrev The address of the previous transcoder in the pool for the current delegate * @param _currDelegateNewPosNext The address of the next transcoder in the pool for the current delegate */ function bondWithHint( uint256 _amount, address _to, address _oldDelegateNewPosPrev, address _oldDelegateNewPosNext, address _currDelegateNewPosPrev, address _currDelegateNewPosNext ) public whenSystemNotPaused currentRoundInitialized autoClaimEarnings { Delegator storage del = delegators[msg.sender]; uint256 currentRound = roundsManager().currentRound(); // Amount to delegate uint256 delegationAmount = _amount; // Current delegate address currentDelegate = del.delegateAddress; if (delegatorStatus(msg.sender) == DelegatorStatus.Unbonded) { // New delegate // Set start round // Don't set start round if delegator is in pending state because the start round would not change del.startRound = currentRound.add(1); // Unbonded state = no existing delegate and no bonded stake // Thus, delegation amount = provided amount } else if (currentDelegate != address(0) && currentDelegate != _to) { // A registered transcoder cannot delegate its bonded stake toward another address // because it can only be delegated toward itself // In the future, if delegation towards another registered transcoder as an already // registered transcoder becomes useful (i.e. for transitive delegation), this restriction // could be removed require(!isRegisteredTranscoder(msg.sender), "registered transcoders can't delegate towards other addresses"); // Changing delegate // Set start round del.startRound = currentRound.add(1); // Update amount to delegate with previous delegation amount delegationAmount = delegationAmount.add(del.bondedAmount); decreaseTotalStake(currentDelegate, del.bondedAmount, _oldDelegateNewPosPrev, _oldDelegateNewPosNext); } // cannot delegate to someone without having bonded stake require(delegationAmount > 0, "delegation amount must be greater than 0"); // Update delegate del.delegateAddress = _to; // Update bonded amount del.bondedAmount = del.bondedAmount.add(_amount); increaseTotalStake(_to, delegationAmount, _currDelegateNewPosPrev, _currDelegateNewPosNext); if (_amount > 0) { // Transfer the LPT to the Minter livepeerToken().transferFrom(msg.sender, address(minter()), _amount); } emit Bond(_to, currentDelegate, msg.sender, _amount, del.bondedAmount); } /** * @notice Unbond an amount of the delegator's bonded stake and updates the transcoder pool using an optional list hint if needed * @dev If the caller remains in the transcoder pool, the caller can provide an optional hint for its insertion position in the * pool via the `_newPosPrev` and `_newPosNext` params. A linear search will be executed starting at the hint to find the correct position. * In the best case, the hint is the correct position so no search is executed. See SortedDoublyLL.sol details on list hints * @param _amount Amount of tokens to unbond * @param _newPosPrev Address of previous transcoder in pool if the caller remains in the pool * @param _newPosNext Address of next transcoder in pool if the caller remains in the pool */ function unbondWithHint(uint256 _amount, address _newPosPrev, address _newPosNext) public whenSystemNotPaused currentRoundInitialized autoClaimEarnings { require(delegatorStatus(msg.sender) == DelegatorStatus.Bonded, "caller must be bonded"); Delegator storage del = delegators[msg.sender]; require(_amount > 0, "unbond amount must be greater than 0"); require(_amount <= del.bondedAmount, "amount is greater than bonded amount"); address currentDelegate = del.delegateAddress; uint256 currentRound = roundsManager().currentRound(); uint256 withdrawRound = currentRound.add(unbondingPeriod); uint256 unbondingLockId = del.nextUnbondingLockId; // Create new unbonding lock del.unbondingLocks[unbondingLockId] = UnbondingLock({ amount: _amount, withdrawRound: withdrawRound }); // Increment ID for next unbonding lock del.nextUnbondingLockId = unbondingLockId.add(1); // Decrease delegator's bonded amount del.bondedAmount = del.bondedAmount.sub(_amount); if (del.bondedAmount == 0) { // Delegator no longer delegated to anyone if it does not have a bonded amount del.delegateAddress = address(0); // Delegator does not have a start round if it is no longer delegated to anyone del.startRound = 0; if (transcoderPoolV2.contains(msg.sender)) { resignTranscoder(msg.sender); } } // If msg.sender was resigned this statement will only decrease delegators[currentDelegate].delegatedAmount decreaseTotalStake(currentDelegate, _amount, _newPosPrev, _newPosNext); emit Unbond(currentDelegate, msg.sender, unbondingLockId, _amount, withdrawRound); } /** * @notice Rebond tokens for an unbonding lock to a delegator's current delegate while a delegator is in the Bonded or Pending status and updates * the transcoder pool using an optional list hint if needed * @dev If the delegate is in the transcoder pool, the caller can provide an optional hint for the delegate's insertion position in the * pool via the `_newPosPrev` and `_newPosNext` params. A linear search will be executed starting at the hint to find the correct position. * In the best case, the hint is the correct position so no search is executed. See SortedDoublyLL.sol details on list hints * @param _unbondingLockId ID of unbonding lock to rebond with * @param _newPosPrev Address of previous transcoder in pool if the delegate is in the pool * @param _newPosNext Address of next transcoder in pool if the delegate is in the pool */ function rebondWithHint( uint256 _unbondingLockId, address _newPosPrev, address _newPosNext ) public whenSystemNotPaused currentRoundInitialized autoClaimEarnings { require(delegatorStatus(msg.sender) != DelegatorStatus.Unbonded, "caller must be bonded"); // Process rebond using unbonding lock processRebond(msg.sender, _unbondingLockId, _newPosPrev, _newPosNext); } /** * @notice Rebond tokens for an unbonding lock to a delegate while a delegator is in the Unbonded status and updates the transcoder pool using * an optional list hint if needed * @dev If the delegate joins the transcoder pool, the caller can provide an optional hint for the delegate's insertion position in the * pool via the `_newPosPrev` and `_newPosNext` params. A linear search will be executed starting at the hint to find the correct position. * In the best case, the hint is the correct position so no search is executed. See SortedDoublyLL.sol for details on list hints * @param _to Address of delegate * @param _unbondingLockId ID of unbonding lock to rebond with * @param _newPosPrev Address of previous transcoder in pool if the delegate joins the pool * @param _newPosNext Address of next transcoder in pool if the delegate joins the pool */ function rebondFromUnbondedWithHint( address _to, uint256 _unbondingLockId, address _newPosPrev, address _newPosNext ) public whenSystemNotPaused currentRoundInitialized autoClaimEarnings { require(delegatorStatus(msg.sender) == DelegatorStatus.Unbonded, "caller must be unbonded"); // Set delegator's start round and transition into Pending state delegators[msg.sender].startRound = roundsManager().currentRound().add(1); // Set delegator's delegate delegators[msg.sender].delegateAddress = _to; // Process rebond using unbonding lock processRebond(msg.sender, _unbondingLockId, _newPosPrev, _newPosNext); } /** * @notice Mint token rewards for an active transcoder and its delegators and update the transcoder pool using an optional list hint if needed * @dev If the caller is in the transcoder pool, the caller can provide an optional hint for its insertion position in the * pool via the `_newPosPrev` and `_newPosNext` params. A linear search will be executed starting at the hint to find the correct position. * In the best case, the hint is the correct position so no search is executed. See SortedDoublyLL.sol for details on list hints * @param _newPosPrev Address of previous transcoder in pool if the caller is in the pool * @param _newPosNext Address of next transcoder in pool if the caller is in the pool */ function rewardWithHint(address _newPosPrev, address _newPosNext) public whenSystemNotPaused currentRoundInitialized { uint256 currentRound = roundsManager().currentRound(); require(isActiveTranscoder(msg.sender), "caller must be an active transcoder"); require(transcoders[msg.sender].lastRewardRound != currentRound, "caller has already called reward for the current round"); Transcoder storage t = transcoders[msg.sender]; EarningsPool.Data storage earningsPool = t.earningsPoolPerRound[currentRound]; // Set last round that transcoder called reward earningsPool.setCommission(t.rewardCut, t.feeShare); // If transcoder didn't receive stake updates during the previous round and hasn't called reward for > 1 round // the 'totalStake' on its 'EarningsPool' for the current round wouldn't be initialized // Thus we sync the the transcoder's stake to when it was last updated // 'updateTrancoderWithRewards()' will set the update round to 'currentRound +1' so this synchronization shouldn't occur frequently uint256 lastUpdateRound = t.lastActiveStakeUpdateRound; if (lastUpdateRound < currentRound) { earningsPool.setStake(t.earningsPoolPerRound[lastUpdateRound].totalStake); } // Create reward based on active transcoder's stake relative to the total active stake // rewardTokens = (current mintable tokens for the round * active transcoder stake) / total active stake uint256 rewardTokens = minter().createReward(earningsPool.totalStake, currentRoundTotalActiveStake); updateTranscoderWithRewards(msg.sender, rewardTokens, currentRound, _newPosPrev, _newPosNext); // Set last round that transcoder called reward t.lastRewardRound = currentRound; emit Reward(msg.sender, rewardTokens); } /** * @notice Returns pending bonded stake for a delegator from its lastClaimRound through an end round * @param _delegator Address of delegator * @param _endRound The last round to compute pending stake from * @return Pending bonded stake for '_delegator' since last claiming rewards */ function pendingStake(address _delegator, uint256 _endRound) public view returns (uint256) { ( uint256 stake, ) = pendingStakeAndFees(_delegator, _endRound); return stake; } /** * @notice Returns pending fees for a delegator from its lastClaimRound through an end round * @param _delegator Address of delegator * @param _endRound The last round to compute pending fees from * @return Pending fees for '_delegator' since last claiming fees */ function pendingFees(address _delegator, uint256 _endRound) public view returns (uint256) { ( , uint256 fees ) = pendingStakeAndFees(_delegator, _endRound); return fees; } /** * @notice Returns total bonded stake for a transcoder * @param _transcoder Address of transcoder * @return total bonded stake for a delegator */ function transcoderTotalStake(address _transcoder) public view returns (uint256) { return delegators[_transcoder].delegatedAmount; } /** * @notice Computes transcoder status * @param _transcoder Address of transcoder * @return registered or not registered transcoder status */ function transcoderStatus(address _transcoder) public view returns (TranscoderStatus) { if (isRegisteredTranscoder(_transcoder)) return TranscoderStatus.Registered; return TranscoderStatus.NotRegistered; } /** * @notice Computes delegator status * @param _delegator Address of delegator * @return bonded, unbonded or pending delegator status */ function delegatorStatus(address _delegator) public view returns (DelegatorStatus) { Delegator storage del = delegators[_delegator]; if (del.bondedAmount == 0) { // Delegator unbonded all its tokens return DelegatorStatus.Unbonded; } else if (del.startRound > roundsManager().currentRound()) { // Delegator round start is in the future return DelegatorStatus.Pending; } else { // Delegator round start is now or in the past // del.startRound != 0 here because if del.startRound = 0 then del.bondedAmount = 0 which // would trigger the first if clause return DelegatorStatus.Bonded; } } /** * @notice Return transcoder information * @param _transcoder Address of transcoder * @return lastRewardRound Trancoder's last reward round * @return rewardCut Transcoder's reward cut * @return feeShare Transcoder's fee share * @return lastActiveStakeUpdateRound Round in which transcoder's stake was last updated while active * @return activationRound Round in which transcoder became active * @return deactivationRound Round in which transcoder will no longer be active * @return activeCumulativeRewards Transcoder's cumulative rewards that are currently active * @return cumulativeRewards Transcoder's cumulative rewards (earned via its active staked rewards and its reward cut) * @return cumulativeFees Transcoder's cumulative fees (earned via its active staked rewards and its fee share) * @return lastFeeRound Latest round that the transcoder received fees */ function getTranscoder( address _transcoder ) public view returns (uint256 lastRewardRound, uint256 rewardCut, uint256 feeShare, uint256 lastActiveStakeUpdateRound, uint256 activationRound, uint256 deactivationRound, uint256 activeCumulativeRewards, uint256 cumulativeRewards, uint256 cumulativeFees, uint256 lastFeeRound) { Transcoder storage t = transcoders[_transcoder]; lastRewardRound = t.lastRewardRound; rewardCut = t.rewardCut; feeShare = t.feeShare; lastActiveStakeUpdateRound = t.lastActiveStakeUpdateRound; activationRound = t.activationRound; deactivationRound = t.deactivationRound; activeCumulativeRewards = t.activeCumulativeRewards; cumulativeRewards = t.cumulativeRewards; cumulativeFees = t.cumulativeFees; lastFeeRound = t.lastFeeRound; } /** * @notice Return transcoder's earnings pool for a given round * @param _transcoder Address of transcoder * @param _round Round number * @return rewardPool Reward pool for delegators (only used before LIP-36) * @return feePool Fee pool for delegators (only used before LIP-36) * @return totalStake Transcoder's total stake in '_round' * @return claimableStake Remaining stake that can be used to claim from the pool (only used before LIP-36) * @return transcoderRewardCut Transcoder's reward cut for '_round' * @return transcoderFeeShare Transcoder's fee share for '_round' * @return transcoderRewardPool Transcoder's rewards for '_round' (only used before LIP-36) * @return transcoderFeePool Transcoder's fees for '_round' (only used before LIP-36) * @return hasTranscoderRewardFeePool True if there is a split reward/fee pool for the transcoder (only used before LIP-36) * @return cumulativeRewardFactor The cumulative reward factor for delegator rewards calculation (only used after LIP-36) * @return cumulativeFeeFactor The cumulative fee factor for delegator fees calculation (only used after LIP-36) */ function getTranscoderEarningsPoolForRound( address _transcoder, uint256 _round ) public view returns (uint256 rewardPool, uint256 feePool, uint256 totalStake, uint256 claimableStake, uint256 transcoderRewardCut, uint256 transcoderFeeShare, uint256 transcoderRewardPool, uint256 transcoderFeePool, bool hasTranscoderRewardFeePool, uint256 cumulativeRewardFactor, uint256 cumulativeFeeFactor) { EarningsPool.Data storage earningsPool = transcoders[_transcoder].earningsPoolPerRound[_round]; rewardPool = earningsPool.rewardPool; feePool = earningsPool.feePool; totalStake = earningsPool.totalStake; claimableStake = earningsPool.claimableStake; transcoderRewardCut = earningsPool.transcoderRewardCut; transcoderFeeShare = earningsPool.transcoderFeeShare; transcoderRewardPool = earningsPool.transcoderRewardPool; transcoderFeePool = earningsPool.transcoderFeePool; hasTranscoderRewardFeePool = earningsPool.hasTranscoderRewardFeePool; cumulativeRewardFactor = earningsPool.cumulativeRewardFactor; cumulativeFeeFactor = earningsPool.cumulativeFeeFactor; } /** * @notice Return delegator info * @param _delegator Address of delegator * @return total amount bonded by '_delegator' * @return amount of fees collected by '_delegator' * @return address '_delegator' has bonded to * @return total amount delegated to '_delegator' * @return round in which bond for '_delegator' became effective * @return round for which '_delegator' has last claimed earnings * @return ID for the next unbonding lock created for '_delegator' */ function getDelegator( address _delegator ) public view returns (uint256 bondedAmount, uint256 fees, address delegateAddress, uint256 delegatedAmount, uint256 startRound, uint256 lastClaimRound, uint256 nextUnbondingLockId) { Delegator storage del = delegators[_delegator]; bondedAmount = del.bondedAmount; fees = del.fees; delegateAddress = del.delegateAddress; delegatedAmount = del.delegatedAmount; startRound = del.startRound; lastClaimRound = del.lastClaimRound; nextUnbondingLockId = del.nextUnbondingLockId; } /** * @notice Return delegator's unbonding lock info * @param _delegator Address of delegator * @param _unbondingLockId ID of unbonding lock * @return amount of stake locked up by unbonding lock * @return round in which 'amount' becomes available for withdrawal */ function getDelegatorUnbondingLock( address _delegator, uint256 _unbondingLockId ) public view returns (uint256 amount, uint256 withdrawRound) { UnbondingLock storage lock = delegators[_delegator].unbondingLocks[_unbondingLockId]; return (lock.amount, lock.withdrawRound); } /** * @notice Returns max size of transcoder pool * @return transcoder pool max size */ function getTranscoderPoolMaxSize() public view returns (uint256) { return transcoderPoolV2.getMaxSize(); } /** * @notice Returns size of transcoder pool * @return transcoder pool current size */ function getTranscoderPoolSize() public view returns (uint256) { return transcoderPoolV2.getSize(); } /** * @notice Returns transcoder with most stake in pool * @return address for transcoder with highest stake in transcoder pool */ function getFirstTranscoderInPool() public view returns (address) { return transcoderPoolV2.getFirst(); } /** * @notice Returns next transcoder in pool for a given transcoder * @param _transcoder Address of a transcoder in the pool * @return address for the transcoder after '_transcoder' in transcoder pool */ function getNextTranscoderInPool(address _transcoder) public view returns (address) { return transcoderPoolV2.getNext(_transcoder); } /** * @notice Return total bonded tokens * @return total active stake for the current round */ function getTotalBonded() public view returns (uint256) { return currentRoundTotalActiveStake; } /** * @notice Return whether a transcoder is active for the current round * @param _transcoder Transcoder address * @return true if transcoder is active */ function isActiveTranscoder(address _transcoder) public view returns (bool) { Transcoder storage t = transcoders[_transcoder]; uint256 currentRound = roundsManager().currentRound(); return t.activationRound <= currentRound && currentRound < t.deactivationRound; } /** * @notice Return whether a transcoder is registered * @param _transcoder Transcoder address * @return true if transcoder is self-bonded */ function isRegisteredTranscoder(address _transcoder) public view returns (bool) { Delegator storage d = delegators[_transcoder]; return d.delegateAddress == _transcoder && d.bondedAmount > 0; } /** * @notice Return whether an unbonding lock for a delegator is valid * @param _delegator Address of delegator * @param _unbondingLockId ID of unbonding lock * @return true if unbondingLock for ID has a non-zero withdraw round */ function isValidUnbondingLock(address _delegator, uint256 _unbondingLockId) public view returns (bool) { // A unbonding lock is only valid if it has a non-zero withdraw round (the default value is zero) return delegators[_delegator].unbondingLocks[_unbondingLockId].withdrawRound > 0; } /** * @notice Return an EarningsPool.Data struct with the latest cumulative factors for a given round * @param _transcoder Storage pointer to a transcoder struct * @param _round The round to fetch the latest cumulative factors for * @return pool An EarningsPool.Data populated with the latest cumulative factors for _round */ function latestCumulativeFactorsPool(Transcoder storage _transcoder, uint256 _round) internal view returns (EarningsPool.Data memory pool) { pool.cumulativeRewardFactor = _transcoder.earningsPoolPerRound[_round].cumulativeRewardFactor; pool.cumulativeFeeFactor = _transcoder.earningsPoolPerRound[_round].cumulativeFeeFactor; uint256 lastRewardRound = _transcoder.lastRewardRound; // Only use the cumulativeRewardFactor for lastRewardRound if lastRewardRound is before _round if (pool.cumulativeRewardFactor == 0 && lastRewardRound < _round) { pool.cumulativeRewardFactor = _transcoder.earningsPoolPerRound[lastRewardRound].cumulativeRewardFactor; } uint256 lastFeeRound = _transcoder.lastFeeRound; // Only use the cumulativeFeeFactor for lastFeeRound if lastFeeRound is before _round if (pool.cumulativeFeeFactor == 0 && lastFeeRound < _round) { pool.cumulativeFeeFactor = _transcoder.earningsPoolPerRound[lastFeeRound].cumulativeFeeFactor; } return pool; } /** * @notice Return a delegator's cumulative stake and fees using the LIP-36 earnings claiming algorithm * @param _transcoder Storage pointer to a transcoder struct for a delegator's delegate * @param _startRound The round for the start cumulative factors * @param _endRound The round for the end cumulative factors * @param _stake The delegator's initial stake before including earned rewards * @param _fees The delegator's initial fees before including earned fees * @return (cStake, cFees) where cStake is the delegator's cumulative stake including earned rewards and cFees is the delegator's cumulative fees including earned fees */ function delegatorCumulativeStakeAndFees( Transcoder storage _transcoder, uint256 _startRound, uint256 _endRound, uint256 _stake, uint256 _fees ) internal view returns (uint256 cStake, uint256 cFees) { uint256 baseRewardFactor = MathUtils.percPoints(1, 1); // Fetch start cumulative factors EarningsPool.Data memory startPool; startPool.cumulativeRewardFactor = _transcoder.earningsPoolPerRound[_startRound].cumulativeRewardFactor; startPool.cumulativeFeeFactor = _transcoder.earningsPoolPerRound[_startRound].cumulativeFeeFactor; if (startPool.cumulativeRewardFactor == 0) { startPool.cumulativeRewardFactor = baseRewardFactor; } // Fetch end cumulative factors EarningsPool.Data memory endPool = latestCumulativeFactorsPool(_transcoder, _endRound); if (endPool.cumulativeRewardFactor == 0) { endPool.cumulativeRewardFactor = baseRewardFactor; } cFees = _fees.add( MathUtils.percOf( _stake, endPool.cumulativeFeeFactor.sub(startPool.cumulativeFeeFactor), startPool.cumulativeRewardFactor ) ); cStake = MathUtils.percOf( _stake, endPool.cumulativeRewardFactor, startPool.cumulativeRewardFactor ); return (cStake, cFees); } /** * @notice Return the pending stake and fees for a delegator * @param _delegator Address of a delegator * @param _endRound The last round to claim earnings for when calculating the pending stake and fees * @return (stake, fees) where stake is the delegator's pending stake and fees is the delegator's pending fees */ function pendingStakeAndFees(address _delegator, uint256 _endRound) internal view returns (uint256 stake, uint256 fees) { Delegator storage del = delegators[_delegator]; Transcoder storage t = transcoders[del.delegateAddress]; fees = del.fees; stake = del.bondedAmount; uint256 startRound = del.lastClaimRound.add(1); address delegateAddr = del.delegateAddress; bool isTranscoder = _delegator == delegateAddr; uint256 lip36Round = roundsManager().lipUpgradeRound(36); while (startRound <= _endRound && startRound <= lip36Round) { EarningsPool.Data storage earningsPool = t.earningsPoolPerRound[startRound]; // If earningsPool.hasTranscoderRewardFeePool is not set during lip36Round then the transcoder did not call // reward during lip36Round before the upgrade. In this case, if the transcoder calls reward in lip36Round // the delegator can use the LIP-36 earnings claiming algorithm to claim for lip36Round if (startRound == lip36Round && !earningsPool.hasTranscoderRewardFeePool) { break; } if (earningsPool.hasClaimableShares()) { // Calculate and add fee pool share from this round fees = fees.add(earningsPool.feePoolShare(stake, isTranscoder)); // Calculate new bonded amount with rewards from this round. Updated bonded amount used // to calculate fee pool share in next round stake = stake.add(earningsPool.rewardPoolShare(stake, isTranscoder)); } startRound = startRound.add(1); } // If the transcoder called reward during lip36Round the upgrade, then startRound = lip36Round // Otherwise, startRound = lip36Round + 1 // If the start round is greater than the end round, we've already claimed for the end round so we do not // need to execute the LIP-36 earnings claiming algorithm. This could be the case if: // - _endRound < lip36Round i.e. we are not claiming through the lip36Round // - _endRound == lip36Round AND startRound = lip36Round + 1 i.e we already claimed through the lip36Round if (startRound > _endRound) { return (stake, fees); } // The LIP-36 earnings claiming algorithm uses the cumulative factors from the delegator's lastClaimRound i.e. startRound - 1 // and from the specified _endRound ( stake, fees ) = delegatorCumulativeStakeAndFees(t, startRound.sub(1), _endRound, stake, fees); if (isTranscoder) { stake = stake.add(t.cumulativeRewards); fees = fees.add(t.cumulativeFees); } return (stake, fees); } /** * @dev Increase the total stake for a delegate and updates its 'lastActiveStakeUpdateRound' * @param _delegate The delegate to increase the stake for * @param _amount The amount to increase the stake for '_delegate' by */ function increaseTotalStake(address _delegate, uint256 _amount, address _newPosPrev, address _newPosNext) internal { if (isRegisteredTranscoder(_delegate)) { uint256 currStake = transcoderTotalStake(_delegate); uint256 newStake = currStake.add(_amount); uint256 currRound = roundsManager().currentRound(); uint256 nextRound = currRound.add(1); // If the transcoder is already in the active set update its stake and return if (transcoderPoolV2.contains(_delegate)) { transcoderPoolV2.updateKey(_delegate, newStake, _newPosPrev, _newPosNext); nextRoundTotalActiveStake = nextRoundTotalActiveStake.add(_amount); Transcoder storage t = transcoders[_delegate]; // currStake (the transcoder's delegatedAmount field) will reflect the transcoder's stake from lastActiveStakeUpdateRound // because it is updated every time lastActiveStakeUpdateRound is updated // The current active total stake is set to currStake to ensure that the value can be used in updateTranscoderWithRewards() // and updateTranscoderWithFees() when lastActiveStakeUpdateRound > currentRound if (t.lastActiveStakeUpdateRound < currRound) { t.earningsPoolPerRound[currRound].setStake(currStake); } t.earningsPoolPerRound[nextRound].setStake(newStake); t.lastActiveStakeUpdateRound = nextRound; } else { // Check if the transcoder is eligible to join the active set in the update round tryToJoinActiveSet(_delegate, newStake, nextRound, _newPosPrev, _newPosNext); } } // Increase delegate's delegated amount delegators[_delegate].delegatedAmount = delegators[_delegate].delegatedAmount.add(_amount); } /** * @dev Decrease the total stake for a delegate and updates its 'lastActiveStakeUpdateRound' * @param _delegate The transcoder to decrease the stake for * @param _amount The amount to decrease the stake for '_delegate' by */ function decreaseTotalStake(address _delegate, uint256 _amount, address _newPosPrev, address _newPosNext) internal { if (transcoderPoolV2.contains(_delegate)) { uint256 currStake = transcoderTotalStake(_delegate); uint256 newStake = currStake.sub(_amount); uint256 currRound = roundsManager().currentRound(); uint256 nextRound = currRound.add(1); transcoderPoolV2.updateKey(_delegate, newStake, _newPosPrev, _newPosNext); nextRoundTotalActiveStake = nextRoundTotalActiveStake.sub(_amount); Transcoder storage t = transcoders[_delegate]; // currStake (the transcoder's delegatedAmount field) will reflect the transcoder's stake from lastActiveStakeUpdateRound // because it is updated every time lastActiveStakeUpdateRound is updated // The current active total stake is set to currStake to ensure that the value can be used in updateTranscoderWithRewards() // and updateTranscoderWithFees() when lastActiveStakeUpdateRound > currentRound if (t.lastActiveStakeUpdateRound < currRound) { t.earningsPoolPerRound[currRound].setStake(currStake); } t.lastActiveStakeUpdateRound = nextRound; t.earningsPoolPerRound[nextRound].setStake(newStake); } // Decrease old delegate's delegated amount delegators[_delegate].delegatedAmount = delegators[_delegate].delegatedAmount.sub(_amount); } /** * @dev Tries to add a transcoder to active transcoder pool, evicts the active transcoder with the lowest stake if the pool is full * @param _transcoder The transcoder to insert into the transcoder pool * @param _totalStake The total stake for '_transcoder' * @param _activationRound The round in which the transcoder should become active */ function tryToJoinActiveSet( address _transcoder, uint256 _totalStake, uint256 _activationRound, address _newPosPrev, address _newPosNext ) internal { uint256 pendingNextRoundTotalActiveStake = nextRoundTotalActiveStake; if (transcoderPoolV2.isFull()) { address lastTranscoder = transcoderPoolV2.getLast(); uint256 lastStake = transcoderTotalStake(lastTranscoder); // If the pool is full and the transcoder has less stake than the least stake transcoder in the pool // then the transcoder is unable to join the active set for the next round if (_totalStake <= lastStake) { return; } // Evict the least stake transcoder from the active set for the next round // Not zeroing 'Transcoder.lastActiveStakeUpdateRound' saves gas (5k when transcoder is evicted and 20k when transcoder is reinserted) // There should be no side-effects as long as the value is properly updated on stake updates // Not zeroing the stake on the current round's 'EarningsPool' saves gas and should have no side effects as long as // 'EarningsPool.setStake()' is called whenever a transcoder becomes active again. transcoderPoolV2.remove(lastTranscoder); transcoders[lastTranscoder].deactivationRound = _activationRound; pendingNextRoundTotalActiveStake = pendingNextRoundTotalActiveStake.sub(lastStake); emit TranscoderDeactivated(lastTranscoder, _activationRound); } transcoderPoolV2.insert(_transcoder, _totalStake, _newPosPrev, _newPosNext); pendingNextRoundTotalActiveStake = pendingNextRoundTotalActiveStake.add(_totalStake); Transcoder storage t = transcoders[_transcoder]; t.lastActiveStakeUpdateRound = _activationRound; t.activationRound = _activationRound; t.deactivationRound = MAX_FUTURE_ROUND; t.earningsPoolPerRound[_activationRound].setStake(_totalStake); nextRoundTotalActiveStake = pendingNextRoundTotalActiveStake; emit TranscoderActivated(_transcoder, _activationRound); } /** * @dev Remove a transcoder from the pool and deactivate it */ function resignTranscoder(address _transcoder) internal { // Not zeroing 'Transcoder.lastActiveStakeUpdateRound' saves gas (5k when transcoder is evicted and 20k when transcoder is reinserted) // There should be no side-effects as long as the value is properly updated on stake updates // Not zeroing the stake on the current round's 'EarningsPool' saves gas and should have no side effects as long as // 'EarningsPool.setStake()' is called whenever a transcoder becomes active again. transcoderPoolV2.remove(_transcoder); nextRoundTotalActiveStake = nextRoundTotalActiveStake.sub(transcoderTotalStake(_transcoder)); uint256 deactivationRound = roundsManager().currentRound().add(1); transcoders[_transcoder].deactivationRound = deactivationRound; emit TranscoderDeactivated(_transcoder, deactivationRound); } /** * @dev Update a transcoder with rewards and update the transcoder pool with an optional list hint if needed. * See SortedDoublyLL.sol for details on list hints * @param _transcoder Address of transcoder * @param _rewards Amount of rewards * @param _round Round that transcoder is updated * @param _newPosPrev Address of previous transcoder in pool if the transcoder is in the pool * @param _newPosNext Address of next transcoder in pool if the transcoder is in the pool */ function updateTranscoderWithRewards( address _transcoder, uint256 _rewards, uint256 _round, address _newPosPrev, address _newPosNext ) internal { Transcoder storage t = transcoders[_transcoder]; EarningsPool.Data storage earningsPool = t.earningsPoolPerRound[_round]; EarningsPool.Data storage prevEarningsPool = t.earningsPoolPerRound[t.lastRewardRound]; t.activeCumulativeRewards = t.cumulativeRewards; uint256 transcoderCommissionRewards = MathUtils.percOf(_rewards, earningsPool.transcoderRewardCut); uint256 delegatorsRewards = _rewards.sub(transcoderCommissionRewards); // Calculate the rewards earned by the transcoder's earned rewards uint256 transcoderRewardStakeRewards = MathUtils.percOf(delegatorsRewards, t.activeCumulativeRewards, earningsPool.totalStake); // Track rewards earned by the transcoder based on its earned rewards and rewardCut t.cumulativeRewards = t.cumulativeRewards.add(transcoderRewardStakeRewards).add(transcoderCommissionRewards); // Update cumulative reward factor with new rewards // The cumulativeRewardFactor is used to calculate rewards for all delegators including the transcoder (self-delegated) // Note that delegatorsRewards includes transcoderRewardStakeRewards, but no delegator will claim that amount using // the earnings claiming algorithm and instead that amount is accounted for in the transcoder's cumulativeRewards field earningsPool.updateCumulativeRewardFactor(prevEarningsPool, delegatorsRewards); // Update transcoder's total stake with rewards increaseTotalStake(_transcoder, _rewards, _newPosPrev, _newPosNext); } /** * @dev Update a delegator with token pools shares from its lastClaimRound through a given round * @param _delegator Delegator address * @param _endRound The last round for which to update a delegator's stake with earnings pool shares * @param _lastClaimRound The round for which a delegator has last claimed earnings */ function updateDelegatorWithEarnings(address _delegator, uint256 _endRound, uint256 _lastClaimRound) internal { Delegator storage del = delegators[_delegator]; uint256 startRound = _lastClaimRound.add(1); uint256 currentBondedAmount = del.bondedAmount; uint256 currentFees = del.fees; uint256 lip36Round = roundsManager().lipUpgradeRound(36); // Only will have earnings to claim if you have a delegate // If not delegated, skip the earnings claim process if (del.delegateAddress != address(0)) { if (startRound <= lip36Round) { // Cannot claim earnings for more than maxEarningsClaimsRounds before LIP-36 // This is a number to cause transactions to fail early if // we know they will require too much gas to loop through all the necessary rounds to claim earnings // The user should instead manually invoke `claimEarnings` to split up the claiming process // across multiple transactions uint256 endLoopRound = _endRound <= lip36Round ? _endRound : lip36Round; require(endLoopRound.sub(_lastClaimRound) <= maxEarningsClaimsRounds, "too many rounds to claim through"); } ( currentBondedAmount, currentFees ) = pendingStakeAndFees(_delegator, _endRound); // Check whether the endEarningsPool is initialised // If it is not initialised set it's cumulative factors so that they can be used when a delegator // next claims earnings as the start cumulative factors (see delegatorCumulativeStakeAndFees()) Transcoder storage t = transcoders[del.delegateAddress]; EarningsPool.Data storage endEarningsPool = t.earningsPoolPerRound[_endRound]; if (endEarningsPool.cumulativeRewardFactor == 0) { endEarningsPool.cumulativeRewardFactor = t.earningsPoolPerRound[t.lastRewardRound].cumulativeRewardFactor; } if (endEarningsPool.cumulativeFeeFactor == 0) { endEarningsPool.cumulativeFeeFactor = t.earningsPoolPerRound[t.lastFeeRound].cumulativeFeeFactor; } if (del.delegateAddress == _delegator) { t.cumulativeFees = 0; t.cumulativeRewards = 0; // activeCumulativeRewards is not cleared here because the next reward() call will set it to cumulativeRewards } } emit EarningsClaimed( del.delegateAddress, _delegator, currentBondedAmount.sub(del.bondedAmount), currentFees.sub(del.fees), startRound, _endRound ); del.lastClaimRound = _endRound; // Rewards are bonded by default del.bondedAmount = currentBondedAmount; del.fees = currentFees; } /** * @dev Update the state of a delegator and its delegate by processing a rebond using an unbonding lock and update the transcoder pool with an optional * list hint if needed. See SortedDoublyLL.sol for details on list hints * @param _delegator Address of delegator * @param _unbondingLockId ID of unbonding lock to rebond with * @param _newPosPrev Address of previous transcoder in pool if the delegate is already in or joins the pool * @param _newPosNext Address of next transcoder in pool if the delegate is already in or joins the pool */ function processRebond(address _delegator, uint256 _unbondingLockId, address _newPosPrev, address _newPosNext) internal { Delegator storage del = delegators[_delegator]; UnbondingLock storage lock = del.unbondingLocks[_unbondingLockId]; require(isValidUnbondingLock(_delegator, _unbondingLockId), "invalid unbonding lock ID"); uint256 amount = lock.amount; // Increase delegator's bonded amount del.bondedAmount = del.bondedAmount.add(amount); // Delete lock delete del.unbondingLocks[_unbondingLockId]; increaseTotalStake(del.delegateAddress, amount, _newPosPrev, _newPosNext); emit Rebond(del.delegateAddress, _delegator, _unbondingLockId, amount); } /** * @dev Return LivepeerToken interface * @return Livepeer token contract registered with Controller */ function livepeerToken() internal view returns (ILivepeerToken) { return ILivepeerToken(controller.getContract(keccak256("LivepeerToken"))); } /** * @dev Return Minter interface * @return Minter contract registered with Controller */ function minter() internal view returns (IMinter) { return IMinter(controller.getContract(keccak256("Minter"))); } /** * @dev Return RoundsManager interface * @return RoundsManager contract registered with Controller */ function roundsManager() internal view returns (IRoundsManager) { return IRoundsManager(controller.getContract(keccak256("RoundsManager"))); } }
Withdraws fees to the caller/ Tell Minter to transfer fees (ETH) to the delegator
function withdrawFees() external whenSystemNotPaused currentRoundInitialized autoClaimEarnings { uint256 fees = delegators[msg.sender].fees; require(fees > 0, "no fees to withdraw"); delegators[msg.sender].fees = 0; minter().trustedWithdrawETH(msg.sender, fees); emit WithdrawFees(msg.sender); }
1,112,492
// SPDX-License-Identifier: agpl-3.0 pragma solidity ^0.8.0; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; import "@openzeppelin/contracts/utils/math/SafeMath.sol"; import "@openzeppelin/contracts/utils/Address.sol"; import "@openzeppelin/contracts/security/ReentrancyGuard.sol"; import "./IConfigurationManager.sol"; import "./IPodOption.sol"; import "./IOptionAMMPool.sol"; import "./IOptionPoolRegistry.sol"; import "./IOptionHelper.sol"; /** * @title PodOption * @author Pods Finance * @notice Represents a Proxy that can perform a set of operations on the behalf of an user */ contract OptionHelper is IOptionHelper, ReentrancyGuard { using SafeERC20 for IERC20; using SafeMath for uint256; /** * @dev store globally accessed configurations */ IConfigurationManager public immutable configurationManager; event OptionsBought( address indexed buyer, address indexed optionAddress, uint256 optionsBought, address inputToken, uint256 inputSold ); event OptionsSold( address indexed seller, address indexed optionAddress, uint256 optionsSold, address outputToken, uint256 outputReceived ); event OptionsMintedAndSold( address indexed seller, address indexed optionAddress, uint256 optionsMintedAndSold, address outputToken, uint256 outputBought ); event LiquidityAdded( address indexed staker, address indexed optionAddress, uint256 amountOptions, address token, uint256 tokenAmount ); constructor(IConfigurationManager _configurationManager) public { require( Address.isContract(address(_configurationManager)), "OptionHelper: Configuration Manager is not a contract" ); configurationManager = _configurationManager; } modifier withinDeadline(uint256 deadline) { require(deadline > block.timestamp, "OptionHelper: deadline expired"); _; } /** * @notice Mint options * @dev Mints an amount of options and return to caller * * @param option The option contract to mint * @param optionAmount Amount of options to mint */ function mint(IPodOption option, uint256 optionAmount) external override { _mint(option, optionAmount); // Transfers back the minted options IERC20(address(option)).safeTransfer(msg.sender, optionAmount); } /** * @notice Mint and sell options * @dev Mints an amount of options and sell it in pool * * @param option The option contract to mint * @param optionAmount Amount of options to mint * @param minTokenAmount Minimum amount of output tokens accepted * @param deadline The deadline in unix-timestamp that limits the transaction from happening * @param initialIVGuess The initial implied volatility guess */ function mintAndSellOptions( IPodOption option, uint256 optionAmount, uint256 minTokenAmount, uint256 deadline, uint256 initialIVGuess ) external override nonReentrant withinDeadline(deadline) { IOptionAMMPool pool = _getPool(option); _mint(option, optionAmount); // Approve pool transfer IERC20(address(option)).safeApprove(address(pool), optionAmount); // Sells options to pool uint256 tokensBought = pool.tradeExactAInput(optionAmount, minTokenAmount, msg.sender, initialIVGuess); emit OptionsMintedAndSold(msg.sender, address(option), optionAmount, pool.tokenB(), tokensBought); } /** * @notice Mint and add liquidity * @dev Mint options and provide them as liquidity to the pool * * @param option The option contract to mint * @param optionAmount Amount of options to mint * @param tokenAmount Amount of tokens to provide as liquidity */ function mintAndAddLiquidity( IPodOption option, uint256 optionAmount, uint256 tokenAmount ) external override nonReentrant { IOptionAMMPool pool = _getPool(option); IERC20 tokenB = IERC20(pool.tokenB()); _mint(option, optionAmount); if (tokenAmount > 0) { // Take stable token from caller tokenB.safeTransferFrom(msg.sender, address(this), tokenAmount); } // Approve pool transfer IERC20(address(option)).safeApprove(address(pool), optionAmount); tokenB.safeApprove(address(pool), tokenAmount); // Adds options and tokens to pool as liquidity pool.addLiquidity(optionAmount, tokenAmount, msg.sender); emit LiquidityAdded(msg.sender, address(option), optionAmount, pool.tokenB(), tokenAmount); } /** * @notice Mint and add liquidity using only collateralAmount as input * @dev Mint options and provide them as liquidity to the pool * * @param option The option contract to mint * @param collateralAmount Amount of collateral tokens to be used to both mint and mint into the stable side */ function mintAndAddLiquidityWithCollateral(IPodOption option, uint256 collateralAmount) external override nonReentrant { require(option.optionType() == IPodOption.OptionType.PUT, "OptionHelper: Invalid option type"); IOptionAMMPool pool = _getPool(option); IERC20 tokenB = IERC20(pool.tokenB()); (uint256 optionAmount, uint256 tokenBToAdd) = _calculateEvenAmounts(option, collateralAmount); _mint(option, optionAmount); tokenB.safeTransferFrom(msg.sender, address(this), tokenBToAdd); // Approve pool transfer IERC20(address(option)).safeApprove(address(pool), optionAmount); tokenB.safeApprove(address(pool), tokenBToAdd); // Adds options and tokens to pool as liquidity pool.addLiquidity(optionAmount, tokenBToAdd, msg.sender); emit LiquidityAdded(msg.sender, address(option), optionAmount, pool.tokenB(), tokenBToAdd); } /** * @notice Add liquidity * @dev Provide options as liquidity to the pool * * @param option The option contract to mint * @param optionAmount Amount of options to provide * @param tokenAmount Amount of tokens to provide as liquidity */ function addLiquidity( IPodOption option, uint256 optionAmount, uint256 tokenAmount ) external override nonReentrant { IOptionAMMPool pool = _getPool(option); IERC20 tokenB = IERC20(pool.tokenB()); if (optionAmount > 0) { // Take options from caller IERC20(address(option)).safeTransferFrom(msg.sender, address(this), optionAmount); } if (tokenAmount > 0) { // Take stable token from caller tokenB.safeTransferFrom(msg.sender, address(this), tokenAmount); } // Approve pool transfer IERC20(address(option)).safeApprove(address(pool), optionAmount); tokenB.safeApprove(address(pool), tokenAmount); // Adds options and tokens to pool as liquidity pool.addLiquidity(optionAmount, tokenAmount, msg.sender); emit LiquidityAdded(msg.sender, address(option), optionAmount, pool.tokenB(), tokenAmount); } /** * @notice Sell exact amount of options * @dev Sell an amount of options from pool * * @param option The option contract to sell * @param optionAmount Amount of options to sell * @param minTokenReceived Min amount of input tokens to receive * @param deadline The deadline in unix-timestamp that limits the transaction from happening * @param initialIVGuess The initial implied volatility guess */ function sellExactOptions( IPodOption option, uint256 optionAmount, uint256 minTokenReceived, uint256 deadline, uint256 initialIVGuess ) external override withinDeadline(deadline) nonReentrant { IOptionAMMPool pool = _getPool(option); IERC20 tokenA = IERC20(pool.tokenA()); // Take input amount from caller tokenA.safeTransferFrom(msg.sender, address(this), optionAmount); // Approve pool transfer tokenA.safeApprove(address(pool), optionAmount); // Buys options from pool uint256 tokenAmountReceived = pool.tradeExactAInput(optionAmount, minTokenReceived, msg.sender, initialIVGuess); emit OptionsSold(msg.sender, address(option), optionAmount, pool.tokenB(), tokenAmountReceived); } /** * @notice Sell estimated amount of options * @dev Sell an estimated amount of options to the pool * * @param option The option contract to sell * @param maxOptionAmount max Amount of options to sell * @param exactTokenReceived exact amount of input tokens to receive * @param deadline The deadline in unix-timestamp that limits the transaction from happening * @param initialIVGuess The initial implied volatility guess */ function sellOptionsAndReceiveExactTokens( IPodOption option, uint256 maxOptionAmount, uint256 exactTokenReceived, uint256 deadline, uint256 initialIVGuess ) external override withinDeadline(deadline) nonReentrant { IOptionAMMPool pool = _getPool(option); IERC20 tokenA = IERC20(pool.tokenA()); // Take input amount from caller tokenA.safeTransferFrom(msg.sender, address(this), maxOptionAmount); // Approve pool transfer tokenA.safeApprove(address(pool), maxOptionAmount); // Buys options from pool uint256 optionsSold = pool.tradeExactBOutput(exactTokenReceived, maxOptionAmount, msg.sender, initialIVGuess); uint256 unusedFunds = maxOptionAmount.sub(optionsSold); // Reset allowance tokenA.safeApprove(address(pool), 0); // Transfer back unused funds if (unusedFunds > 0) { tokenA.safeTransfer(msg.sender, unusedFunds); } emit OptionsSold(msg.sender, address(option), optionsSold, pool.tokenB(), exactTokenReceived); } /** * @notice Buy exact amount of options * @dev Buys an amount of options from pool * * @param option The option contract to buy * @param optionAmount Amount of options to buy * @param maxTokenAmount Max amount of input tokens sold * @param deadline The deadline in unix-timestamp that limits the transaction from happening * @param initialIVGuess The initial implied volatility guess */ function buyExactOptions( IPodOption option, uint256 optionAmount, uint256 maxTokenAmount, uint256 deadline, uint256 initialIVGuess ) external override withinDeadline(deadline) nonReentrant { IOptionAMMPool pool = _getPool(option); IERC20 tokenB = IERC20(pool.tokenB()); // Take input amount from caller tokenB.safeTransferFrom(msg.sender, address(this), maxTokenAmount); // Approve pool transfer tokenB.safeApprove(address(pool), maxTokenAmount); // Buys options from pool uint256 tokensSold = pool.tradeExactAOutput(optionAmount, maxTokenAmount, msg.sender, initialIVGuess); uint256 unusedFunds = maxTokenAmount.sub(tokensSold); // Reset allowance tokenB.safeApprove(address(pool), 0); // Transfer back unused funds if (unusedFunds > 0) { tokenB.safeTransfer(msg.sender, unusedFunds); } emit OptionsBought(msg.sender, address(option), optionAmount, pool.tokenB(), tokensSold); } /** * @notice Buy estimated amount of options * @dev Buys an estimated amount of options from pool * * @param option The option contract to buy * @param minOptionAmount Min amount of options bought * @param tokenAmount The exact amount of input tokens sold * @param deadline The deadline in unix-timestamp that limits the transaction from happening * @param initialIVGuess The initial implied volatility guess */ function buyOptionsWithExactTokens( IPodOption option, uint256 minOptionAmount, uint256 tokenAmount, uint256 deadline, uint256 initialIVGuess ) external override withinDeadline(deadline) nonReentrant { IOptionAMMPool pool = _getPool(option); IERC20 tokenB = IERC20(pool.tokenB()); // Take input amount from caller tokenB.safeTransferFrom(msg.sender, address(this), tokenAmount); // Approve pool transfer tokenB.safeApprove(address(pool), tokenAmount); // Buys options from pool uint256 optionsBought = pool.tradeExactBInput(tokenAmount, minOptionAmount, msg.sender, initialIVGuess); emit OptionsBought(msg.sender, address(option), optionsBought, pool.tokenB(), tokenAmount); } /** * @dev Mints an amount of tokens collecting the strike tokens from the caller * * @param option The option contract to mint * @param amount The amount of options to mint */ function _mint(IPodOption option, uint256 amount) internal { require(Address.isContract(address(option)), "OptionHelper: Option is not a contract"); if (option.optionType() == IPodOption.OptionType.PUT) { IERC20 strikeAsset = IERC20(option.strikeAsset()); uint256 strikeToTransfer = option.strikeToTransfer(amount); // Take strike asset from caller strikeAsset.safeTransferFrom(msg.sender, address(this), strikeToTransfer); // Approving strike asset transfer to Option strikeAsset.safeApprove(address(option), strikeToTransfer); option.mint(amount, msg.sender); } else if (option.optionType() == IPodOption.OptionType.CALL) { IERC20 underlyingAsset = IERC20(option.underlyingAsset()); // Take underlying asset from caller underlyingAsset.safeTransferFrom(msg.sender, address(this), amount); // Approving underlying asset to Option underlyingAsset.safeApprove(address(option), amount); option.mint(amount, msg.sender); } } /** * @dev Returns the AMM Pool associated with the option * * @param option The option to search for * @return IOptionAMMPool */ function _getPool(IPodOption option) internal view returns (IOptionAMMPool) { IOptionPoolRegistry registry = IOptionPoolRegistry(configurationManager.getOptionPoolRegistry()); address exchangeOptionAddress = registry.getPool(address(option)); require(exchangeOptionAddress != address(0), "OptionHelper: pool not found"); return IOptionAMMPool(exchangeOptionAddress); } /** * @dev Returns the AMM Pool associated with the option * * @param option The option to search for * @param collateralAmount Total collateral amount that will be used to mint and add liquidity * @return amountOfOptions amount of options to mint * @return amountOfTokenB amount of stable to add liquidity */ function _calculateEvenAmounts(IPodOption option, uint256 collateralAmount) internal view returns (uint256 amountOfOptions, uint256 amountOfTokenB) { // 1) Get BS Unit Price IOptionAMMPool pool = _getPool(option); uint256 ABPrice = pool.getABPrice(); uint256 strikePrice = option.strikePrice(); uint256 optionDecimals = option.underlyingAssetDecimals(); amountOfOptions = collateralAmount.mul(10**optionDecimals).div(strikePrice.add(ABPrice)); amountOfTokenB = amountOfOptions.mul(ABPrice).div(10**optionDecimals); } }
Mint options Mints an amount of options and return to caller option The option contract to mint optionAmount Amount of options to mint/ Transfers back the minted options
function mint(IPodOption option, uint256 optionAmount) external override { _mint(option, optionAmount); IERC20(address(option)).safeTransfer(msg.sender, optionAmount); }
14,096,217
// SPDX-License-Identifier: GPL-3.0-or-later pragma solidity ^0.8.4; import "./IUniswapPCVDeposit.sol"; import "../../Constants.sol"; import "../PCVDeposit.sol"; import "../../refs/UniRef.sol"; import "@uniswap/v2-periphery/contracts/interfaces/IWETH.sol"; import "@uniswap/lib/contracts/libraries/Babylonian.sol"; import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; /// @title implementation for Uniswap LP PCV Deposit. /// Note: the FEI counterpart of tokens deposited have to be pre-minted on /// this contract before deposit(), if it doesn't have the MINTER_ROLE role. /// @author Fei Protocol contract UniswapPCVDeposit is IUniswapPCVDeposit, PCVDeposit, UniRef { using Decimal for Decimal.D256; using Babylonian for uint256; /// @notice a slippage protection parameter, deposits revert when spot price is > this % from oracle uint256 public override maxBasisPointsFromPegLP; /// @notice the Uniswap router contract IUniswapV2Router02 public override router; /// @notice Uniswap PCV Deposit constructor /// @param _core Fei Core for reference /// @param _pair Uniswap Pair to deposit to /// @param _router Uniswap Router /// @param _oracle oracle for reference /// @param _backupOracle the backup oracle to reference /// @param _maxBasisPointsFromPegLP the max basis points of slippage from peg allowed on LP deposit constructor( address _core, address _pair, address _router, address _oracle, address _backupOracle, uint256 _maxBasisPointsFromPegLP ) UniRef(_core, _pair, _oracle, _backupOracle) { router = IUniswapV2Router02(_router); _approveToken(address(fei())); _approveToken(token); _approveToken(_pair); maxBasisPointsFromPegLP = _maxBasisPointsFromPegLP; emit MaxBasisPointsFromPegLPUpdate(0, _maxBasisPointsFromPegLP); } receive() external payable { _wrap(); } /// @notice deposit tokens into the PCV allocation function deposit() external override whenNotPaused { updateOracle(); // Calculate amounts to provide liquidity uint256 tokenAmount = IERC20(token).balanceOf(address(this)); uint256 feiAmount = readOracle().mul(tokenAmount).asUint256(); _addLiquidity(tokenAmount, feiAmount); _burnFeiHeld(); // burn any FEI dust from LP emit Deposit(msg.sender, tokenAmount); } /// @notice withdraw tokens from the PCV allocation /// @param amountUnderlying of tokens withdrawn /// @param to the address to send PCV to /// @dev has rounding errors on amount to withdraw, can differ from the input "amountUnderlying" function withdraw(address to, uint256 amountUnderlying) external override onlyPCVController whenNotPaused { uint256 totalUnderlying = balance(); require( amountUnderlying <= totalUnderlying, "UniswapPCVDeposit: Insufficient underlying" ); uint256 totalLiquidity = liquidityOwned(); // ratio of LP tokens needed to get out the desired amount Decimal.D256 memory ratioToWithdraw = Decimal.ratio(amountUnderlying, totalUnderlying); // amount of LP tokens to withdraw factoring in ratio uint256 liquidityToWithdraw = ratioToWithdraw.mul(totalLiquidity).asUint256(); // Withdraw liquidity from the pair and send to target uint256 amountWithdrawn = _removeLiquidity(liquidityToWithdraw); SafeERC20.safeTransfer(IERC20(token), to, amountWithdrawn); _burnFeiHeld(); // burn remaining FEI emit Withdrawal(msg.sender, to, amountWithdrawn); } /// @notice sets the new slippage parameter for depositing liquidity /// @param _maxBasisPointsFromPegLP the new distance in basis points (1/10000) from peg beyond which a liquidity provision will fail function setMaxBasisPointsFromPegLP(uint256 _maxBasisPointsFromPegLP) public override onlyGovernorOrAdmin { require( _maxBasisPointsFromPegLP <= Constants.BASIS_POINTS_GRANULARITY, "UniswapPCVDeposit: basis points from peg too high" ); uint256 oldMaxBasisPointsFromPegLP = maxBasisPointsFromPegLP; maxBasisPointsFromPegLP = _maxBasisPointsFromPegLP; emit MaxBasisPointsFromPegLPUpdate( oldMaxBasisPointsFromPegLP, _maxBasisPointsFromPegLP ); } /// @notice set the new pair contract /// @param _pair the new pair /// @dev also approves the router for the new pair token and underlying token function setPair(address _pair) public virtual override onlyGovernor { _setupPair(_pair); _approveToken(token); _approveToken(_pair); } /// @notice returns total balance of PCV in the Deposit excluding the FEI function balance() public view override returns (uint256) { (, uint256 tokenReserves) = getReserves(); return _ratioOwned().mul(tokenReserves).asUint256(); } /// @notice display the related token of the balance reported function balanceReportedIn() public view override returns (address) { return token; } /** @notice get the manipulation resistant Other(example ETH) and FEI in the Uniswap pool @return number of other token in pool @return number of FEI in pool Derivation rETH, rFEI = resistant (ideal) ETH and FEI reserves, P = price of ETH in FEI: 1. rETH * rFEI = k 2. rETH = k / rFEI 3. rETH = (k * rETH) / (rFEI * rETH) 4. rETH ^ 2 = k / P 5. rETH = sqrt(k / P) and rFEI = k / rETH by 1. Finally scale the resistant reserves by the ratio owned by the contract */ function resistantBalanceAndFei() public view override returns(uint256, uint256) { (uint256 feiInPool, uint256 otherInPool) = getReserves(); Decimal.D256 memory priceOfToken = readOracle(); uint256 k = feiInPool * otherInPool; // resistant other/fei in pool uint256 resistantOtherInPool = Decimal.one().div(priceOfToken).mul(k).asUint256().sqrt(); uint256 resistantFeiInPool = Decimal.ratio(k, resistantOtherInPool).asUint256(); Decimal.D256 memory ratioOwned = _ratioOwned(); return ( ratioOwned.mul(resistantOtherInPool).asUint256(), ratioOwned.mul(resistantFeiInPool).asUint256() ); } /// @notice amount of pair liquidity owned by this contract /// @return amount of LP tokens function liquidityOwned() public view virtual override returns (uint256) { return pair.balanceOf(address(this)); } function _removeLiquidity(uint256 liquidity) internal virtual returns (uint256) { uint256 endOfTime = type(uint256).max; // No restrictions on withdrawal price (, uint256 amountWithdrawn) = router.removeLiquidity( address(fei()), token, liquidity, 0, 0, address(this), endOfTime ); return amountWithdrawn; } function _addLiquidity(uint256 tokenAmount, uint256 feiAmount) internal virtual { if (core().isMinter(address(this))) { _mintFei(address(this), feiAmount); } uint256 endOfTime = type(uint256).max; // Deposit price gated by slippage parameter router.addLiquidity( address(fei()), token, feiAmount, tokenAmount, _getMinLiquidity(feiAmount), _getMinLiquidity(tokenAmount), address(this), endOfTime ); } /// @notice used as slippage protection when adding liquidity to the pool function _getMinLiquidity(uint256 amount) internal view returns (uint256) { return (amount * (Constants.BASIS_POINTS_GRANULARITY - maxBasisPointsFromPegLP)) / Constants.BASIS_POINTS_GRANULARITY; } /// @notice ratio of all pair liquidity owned by this contract function _ratioOwned() internal view returns (Decimal.D256 memory) { uint256 liquidity = liquidityOwned(); uint256 total = pair.totalSupply(); return Decimal.ratio(liquidity, total); } /// @notice approves a token for the router function _approveToken(address _token) internal { uint256 maxTokens = type(uint256).max; IERC20(_token).approve(address(router), maxTokens); } // Wrap all held ETH function _wrap() internal { uint256 amount = address(this).balance; IWETH(router.WETH()).deposit{value: amount}(); } } // SPDX-License-Identifier: GPL-3.0-or-later pragma solidity ^0.8.4; import "@uniswap/v2-periphery/contracts/interfaces/IUniswapV2Router02.sol"; /// @title a PCV Deposit interface /// @author Fei Protocol interface IUniswapPCVDeposit { // ----------- Events ----------- event MaxBasisPointsFromPegLPUpdate(uint256 oldMaxBasisPointsFromPegLP, uint256 newMaxBasisPointsFromPegLP); // ----------- Governor only state changing api ----------- function setMaxBasisPointsFromPegLP(uint256 amount) external; // ----------- Getters ----------- function router() external view returns (IUniswapV2Router02); function liquidityOwned() external view returns (uint256); function maxBasisPointsFromPegLP() external view returns (uint256); } // SPDX-License-Identifier: GPL-3.0-or-later pragma solidity ^0.8.0; import "@uniswap/v2-periphery/contracts/interfaces/IWETH.sol"; library Constants { /// @notice the denominator for basis points granularity (10,000) uint256 public constant BASIS_POINTS_GRANULARITY = 10_000; uint256 public constant ONE_YEAR = 365.25 days; /// @notice WETH9 address IWETH public constant WETH = IWETH(0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2); /// @notice USD stand-in address address public constant USD = 0x1111111111111111111111111111111111111111; /// @notice Wei per ETH, i.e. 10**18 uint256 public constant ETH_GRANULARITY = 1e18; /// @notice number of decimals in ETH, 18 uint256 public constant ETH_DECIMALS = 18; } // SPDX-License-Identifier: GPL-3.0-or-later pragma solidity ^0.8.4; import "../refs/CoreRef.sol"; import "./IPCVDeposit.sol"; import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; /// @title abstract contract for withdrawing ERC-20 tokens using a PCV Controller /// @author Fei Protocol abstract contract PCVDeposit is IPCVDeposit, CoreRef { using SafeERC20 for IERC20; /// @notice withdraw ERC20 from the contract /// @param token address of the ERC20 to send /// @param to address destination of the ERC20 /// @param amount quantity of ERC20 to send function withdrawERC20( address token, address to, uint256 amount ) public virtual override onlyPCVController { _withdrawERC20(token, to, amount); } function _withdrawERC20( address token, address to, uint256 amount ) internal { IERC20(token).safeTransfer(to, amount); emit WithdrawERC20(msg.sender, token, to, amount); } /// @notice withdraw ETH from the contract /// @param to address to send ETH /// @param amountOut amount of ETH to send function withdrawETH(address payable to, uint256 amountOut) external virtual override onlyPCVController { Address.sendValue(to, amountOut); emit WithdrawETH(msg.sender, to, amountOut); } function balance() public view virtual override returns(uint256); function resistantBalanceAndFei() public view virtual override returns(uint256, uint256) { return (balance(), 0); } } // SPDX-License-Identifier: GPL-3.0-or-later pragma solidity ^0.8.4; import "./ICoreRef.sol"; import "@openzeppelin/contracts/security/Pausable.sol"; /// @title A Reference to Core /// @author Fei Protocol /// @notice defines some modifiers and utilities around interacting with Core abstract contract CoreRef is ICoreRef, Pausable { ICore private immutable _core; IFei private immutable _fei; IERC20 private immutable _tribe; /// @notice a role used with a subset of governor permissions for this contract only bytes32 public override CONTRACT_ADMIN_ROLE; constructor(address coreAddress) { _core = ICore(coreAddress); _fei = ICore(coreAddress).fei(); _tribe = ICore(coreAddress).tribe(); _setContractAdminRole(ICore(coreAddress).GOVERN_ROLE()); } function _initialize(address) internal {} // no-op for backward compatibility modifier ifMinterSelf() { if (_core.isMinter(address(this))) { _; } } modifier onlyMinter() { require(_core.isMinter(msg.sender), "CoreRef: Caller is not a minter"); _; } modifier onlyBurner() { require(_core.isBurner(msg.sender), "CoreRef: Caller is not a burner"); _; } modifier onlyPCVController() { require( _core.isPCVController(msg.sender), "CoreRef: Caller is not a PCV controller" ); _; } modifier onlyGovernorOrAdmin() { require( _core.isGovernor(msg.sender) || isContractAdmin(msg.sender), "CoreRef: Caller is not a governor or contract admin" ); _; } modifier onlyGovernor() { require( _core.isGovernor(msg.sender), "CoreRef: Caller is not a governor" ); _; } modifier onlyGuardianOrGovernor() { require( _core.isGovernor(msg.sender) || _core.isGuardian(msg.sender), "CoreRef: Caller is not a guardian or governor" ); _; } modifier isGovernorOrGuardianOrAdmin() { require( _core.isGovernor(msg.sender) || _core.isGuardian(msg.sender) || isContractAdmin(msg.sender), "CoreRef: Caller is not governor or guardian or admin"); _; } // Named onlyTribeRole to prevent collision with OZ onlyRole modifier modifier onlyTribeRole(bytes32 role) { require(_core.hasRole(role, msg.sender), "UNAUTHORIZED"); _; } // Modifiers to allow any combination of roles modifier hasAnyOfTwoRoles(bytes32 role1, bytes32 role2) { require(_core.hasRole(role1, msg.sender) || _core.hasRole(role2, msg.sender), "UNAUTHORIZED"); _; } modifier hasAnyOfThreeRoles(bytes32 role1, bytes32 role2, bytes32 role3) { require(_core.hasRole(role1, msg.sender) || _core.hasRole(role2, msg.sender) || _core.hasRole(role3, msg.sender), "UNAUTHORIZED"); _; } modifier hasAnyOfFourRoles(bytes32 role1, bytes32 role2, bytes32 role3, bytes32 role4) { require(_core.hasRole(role1, msg.sender) || _core.hasRole(role2, msg.sender) || _core.hasRole(role3, msg.sender) || _core.hasRole(role4, msg.sender), "UNAUTHORIZED"); _; } modifier hasAnyOfFiveRoles(bytes32 role1, bytes32 role2, bytes32 role3, bytes32 role4, bytes32 role5) { require(_core.hasRole(role1, msg.sender) || _core.hasRole(role2, msg.sender) || _core.hasRole(role3, msg.sender) || _core.hasRole(role4, msg.sender) || _core.hasRole(role5, msg.sender), "UNAUTHORIZED"); _; } modifier onlyFei() { require(msg.sender == address(_fei), "CoreRef: Caller is not FEI"); _; } /// @notice sets a new admin role for this contract function setContractAdminRole(bytes32 newContractAdminRole) external override onlyGovernor { _setContractAdminRole(newContractAdminRole); } /// @notice returns whether a given address has the admin role for this contract function isContractAdmin(address _admin) public view override returns (bool) { return _core.hasRole(CONTRACT_ADMIN_ROLE, _admin); } /// @notice set pausable methods to paused function pause() public override onlyGuardianOrGovernor { _pause(); } /// @notice set pausable methods to unpaused function unpause() public override onlyGuardianOrGovernor { _unpause(); } /// @notice address of the Core contract referenced /// @return ICore implementation address function core() public view override returns (ICore) { return _core; } /// @notice address of the Fei contract referenced by Core /// @return IFei implementation address function fei() public view override returns (IFei) { return _fei; } /// @notice address of the Tribe contract referenced by Core /// @return IERC20 implementation address function tribe() public view override returns (IERC20) { return _tribe; } /// @notice fei balance of contract /// @return fei amount held function feiBalance() public view override returns (uint256) { return _fei.balanceOf(address(this)); } /// @notice tribe balance of contract /// @return tribe amount held function tribeBalance() public view override returns (uint256) { return _tribe.balanceOf(address(this)); } function _burnFeiHeld() internal { _fei.burn(feiBalance()); } function _mintFei(address to, uint256 amount) internal virtual { if (amount != 0) { _fei.mint(to, amount); } } function _setContractAdminRole(bytes32 newContractAdminRole) internal { bytes32 oldContractAdminRole = CONTRACT_ADMIN_ROLE; CONTRACT_ADMIN_ROLE = newContractAdminRole; emit ContractAdminRoleUpdate(oldContractAdminRole, newContractAdminRole); } } // SPDX-License-Identifier: GPL-3.0-or-later pragma solidity ^0.8.4; import "../core/ICore.sol"; /// @title CoreRef interface /// @author Fei Protocol interface ICoreRef { // ----------- Events ----------- event CoreUpdate(address indexed oldCore, address indexed newCore); event ContractAdminRoleUpdate(bytes32 indexed oldContractAdminRole, bytes32 indexed newContractAdminRole); // ----------- Governor only state changing api ----------- function setContractAdminRole(bytes32 newContractAdminRole) external; // ----------- Governor or Guardian only state changing api ----------- function pause() external; function unpause() external; // ----------- Getters ----------- function core() external view returns (ICore); function fei() external view returns (IFei); function tribe() external view returns (IERC20); function feiBalance() external view returns (uint256); function tribeBalance() external view returns (uint256); function CONTRACT_ADMIN_ROLE() external view returns (bytes32); function isContractAdmin(address admin) external view returns (bool); } // SPDX-License-Identifier: GPL-3.0-or-later pragma solidity ^0.8.4; import "./IPermissions.sol"; import "../fei/IFei.sol"; /// @title Core Interface /// @author Fei Protocol interface ICore is IPermissions { // ----------- Events ----------- event FeiUpdate(address indexed _fei); event TribeUpdate(address indexed _tribe); event GenesisGroupUpdate(address indexed _genesisGroup); event TribeAllocation(address indexed _to, uint256 _amount); event GenesisPeriodComplete(uint256 _timestamp); // ----------- Governor only state changing api ----------- function init() external; // ----------- Governor only state changing api ----------- function setFei(address token) external; function setTribe(address token) external; function allocateTribe(address to, uint256 amount) external; // ----------- Getters ----------- function fei() external view returns (IFei); function tribe() external view returns (IERC20); } // SPDX-License-Identifier: GPL-3.0-or-later pragma solidity ^0.8.4; import "@openzeppelin/contracts/access/AccessControl.sol"; import "./IPermissionsRead.sol"; /// @title Permissions interface /// @author Fei Protocol interface IPermissions is IAccessControl, IPermissionsRead { // ----------- Governor only state changing api ----------- function createRole(bytes32 role, bytes32 adminRole) external; function grantMinter(address minter) external; function grantBurner(address burner) external; function grantPCVController(address pcvController) external; function grantGovernor(address governor) external; function grantGuardian(address guardian) external; function revokeMinter(address minter) external; function revokeBurner(address burner) external; function revokePCVController(address pcvController) external; function revokeGovernor(address governor) external; function revokeGuardian(address guardian) external; // ----------- Revoker only state changing api ----------- function revokeOverride(bytes32 role, address account) external; // ----------- Getters ----------- function GUARDIAN_ROLE() external view returns (bytes32); function GOVERN_ROLE() external view returns (bytes32); function BURNER_ROLE() external view returns (bytes32); function MINTER_ROLE() external view returns (bytes32); function PCV_CONTROLLER_ROLE() external view returns (bytes32); } // SPDX-License-Identifier: GPL-3.0-or-later pragma solidity ^0.8.4; /// @title Permissions Read interface /// @author Fei Protocol interface IPermissionsRead { // ----------- Getters ----------- function isBurner(address _address) external view returns (bool); function isMinter(address _address) external view returns (bool); function isGovernor(address _address) external view returns (bool); function isGuardian(address _address) external view returns (bool); function isPCVController(address _address) external view returns (bool); } // SPDX-License-Identifier: GPL-3.0-or-later pragma solidity ^0.8.4; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; /// @title FEI stablecoin interface /// @author Fei Protocol interface IFei is IERC20 { // ----------- Events ----------- event Minting( address indexed _to, address indexed _minter, uint256 _amount ); event Burning( address indexed _to, address indexed _burner, uint256 _amount ); event IncentiveContractUpdate( address indexed _incentivized, address indexed _incentiveContract ); // ----------- State changing api ----------- function burn(uint256 amount) external; function permit( address owner, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) external; // ----------- Burner only state changing api ----------- function burnFrom(address account, uint256 amount) external; // ----------- Minter only state changing api ----------- function mint(address account, uint256 amount) external; // ----------- Governor only state changing api ----------- function setIncentiveContract(address account, address incentive) external; // ----------- Getters ----------- function incentiveContract(address account) external view returns (address); } // SPDX-License-Identifier: GPL-3.0-or-later pragma solidity ^0.8.4; import "./IPCVDepositBalances.sol"; /// @title a PCV Deposit interface /// @author Fei Protocol interface IPCVDeposit is IPCVDepositBalances { // ----------- Events ----------- event Deposit(address indexed _from, uint256 _amount); event Withdrawal( address indexed _caller, address indexed _to, uint256 _amount ); event WithdrawERC20( address indexed _caller, address indexed _token, address indexed _to, uint256 _amount ); event WithdrawETH( address indexed _caller, address indexed _to, uint256 _amount ); // ----------- State changing api ----------- function deposit() external; // ----------- PCV Controller only state changing api ----------- function withdraw(address to, uint256 amount) external; function withdrawERC20(address token, address to, uint256 amount) external; function withdrawETH(address payable to, uint256 amount) external; } // SPDX-License-Identifier: GPL-3.0-or-later pragma solidity ^0.8.4; /// @title a PCV Deposit interface for only balance getters /// @author Fei Protocol interface IPCVDepositBalances { // ----------- Getters ----------- /// @notice gets the effective balance of "balanceReportedIn" token if the deposit were fully withdrawn function balance() external view returns (uint256); /// @notice gets the token address in which this deposit returns its balance function balanceReportedIn() external view returns (address); /// @notice gets the resistant token balance and protocol owned fei of this deposit function resistantBalanceAndFei() external view returns (uint256, uint256); } // SPDX-License-Identifier: GPL-3.0-or-later pragma solidity ^0.8.4; import "./OracleRef.sol"; import "./IUniRef.sol"; /// @title A Reference to Uniswap /// @author Fei Protocol /// @notice defines some utilities around interacting with Uniswap /// @dev the uniswap pair should be FEI and another asset abstract contract UniRef is IUniRef, OracleRef { /// @notice the referenced Uniswap pair contract IUniswapV2Pair public override pair; /// @notice the address of the non-fei underlying token address public override token; /// @notice UniRef constructor /// @param _core Fei Core to reference /// @param _pair Uniswap pair to reference /// @param _oracle oracle to reference /// @param _backupOracle backup oracle to reference constructor( address _core, address _pair, address _oracle, address _backupOracle ) OracleRef(_core, _oracle, _backupOracle, 0, false) { _setupPair(_pair); _setDecimalsNormalizerFromToken(_token()); } /// @notice set the new pair contract /// @param newPair the new pair function setPair(address newPair) external override virtual onlyGovernor { _setupPair(newPair); } /// @notice pair reserves with fei listed first function getReserves() public view override returns (uint256 feiReserves, uint256 tokenReserves) { address token0 = pair.token0(); (uint256 reserve0, uint256 reserve1, ) = pair.getReserves(); (feiReserves, tokenReserves) = address(fei()) == token0 ? (reserve0, reserve1) : (reserve1, reserve0); return (feiReserves, tokenReserves); } function _setupPair(address newPair) internal { require(newPair != address(0), "UniRef: zero address"); address oldPair = address(pair); pair = IUniswapV2Pair(newPair); emit PairUpdate(oldPair, newPair); token = _token(); } function _token() internal view returns (address) { address token0 = pair.token0(); if (address(fei()) == token0) { return pair.token1(); } return token0; } } // SPDX-License-Identifier: GPL-3.0-or-later pragma solidity ^0.8.4; import "./IOracleRef.sol"; import "./CoreRef.sol"; import "@openzeppelin/contracts/utils/math/SafeCast.sol"; import "@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol"; /// @title Reference to an Oracle /// @author Fei Protocol /// @notice defines some utilities around interacting with the referenced oracle abstract contract OracleRef is IOracleRef, CoreRef { using Decimal for Decimal.D256; using SafeCast for int256; /// @notice the oracle reference by the contract IOracle public override oracle; /// @notice the backup oracle reference by the contract IOracle public override backupOracle; /// @notice number of decimals to scale oracle price by, i.e. multiplying by 10^(decimalsNormalizer) int256 public override decimalsNormalizer; bool public override doInvert; /// @notice OracleRef constructor /// @param _core Fei Core to reference /// @param _oracle oracle to reference /// @param _backupOracle backup oracle to reference /// @param _decimalsNormalizer number of decimals to normalize the oracle feed if necessary /// @param _doInvert invert the oracle price if this flag is on constructor(address _core, address _oracle, address _backupOracle, int256 _decimalsNormalizer, bool _doInvert) CoreRef(_core) { _setOracle(_oracle); if (_backupOracle != address(0) && _backupOracle != _oracle) { _setBackupOracle(_backupOracle); } _setDoInvert(_doInvert); _setDecimalsNormalizer(_decimalsNormalizer); } /// @notice sets the referenced oracle /// @param newOracle the new oracle to reference function setOracle(address newOracle) external override onlyGovernor { _setOracle(newOracle); } /// @notice sets the flag for whether to invert or not /// @param newDoInvert the new flag for whether to invert function setDoInvert(bool newDoInvert) external override onlyGovernor { _setDoInvert(newDoInvert); } /// @notice sets the new decimalsNormalizer /// @param newDecimalsNormalizer the new decimalsNormalizer function setDecimalsNormalizer(int256 newDecimalsNormalizer) external override onlyGovernor { _setDecimalsNormalizer(newDecimalsNormalizer); } /// @notice sets the referenced backup oracle /// @param newBackupOracle the new backup oracle to reference function setBackupOracle(address newBackupOracle) external override onlyGovernorOrAdmin { _setBackupOracle(newBackupOracle); } /// @notice invert a peg price /// @param price the peg price to invert /// @return the inverted peg as a Decimal /// @dev the inverted peg would be X per FEI function invert(Decimal.D256 memory price) public pure override returns (Decimal.D256 memory) { return Decimal.one().div(price); } /// @notice updates the referenced oracle function updateOracle() public override { oracle.update(); } /// @notice the peg price of the referenced oracle /// @return the peg as a Decimal /// @dev the peg is defined as FEI per X with X being ETH, dollars, etc function readOracle() public view override returns (Decimal.D256 memory) { (Decimal.D256 memory _peg, bool valid) = oracle.read(); if (!valid && address(backupOracle) != address(0)) { (_peg, valid) = backupOracle.read(); } require(valid, "OracleRef: oracle invalid"); // Scale the oracle price by token decimals delta if necessary uint256 scalingFactor; if (decimalsNormalizer < 0) { scalingFactor = 10 ** (-1 * decimalsNormalizer).toUint256(); _peg = _peg.div(scalingFactor); } else { scalingFactor = 10 ** decimalsNormalizer.toUint256(); _peg = _peg.mul(scalingFactor); } // Invert the oracle price if necessary if (doInvert) { _peg = invert(_peg); } return _peg; } function _setOracle(address newOracle) internal { require(newOracle != address(0), "OracleRef: zero address"); address oldOracle = address(oracle); oracle = IOracle(newOracle); emit OracleUpdate(oldOracle, newOracle); } // Supports zero address if no backup function _setBackupOracle(address newBackupOracle) internal { address oldBackupOracle = address(backupOracle); backupOracle = IOracle(newBackupOracle); emit BackupOracleUpdate(oldBackupOracle, newBackupOracle); } function _setDoInvert(bool newDoInvert) internal { bool oldDoInvert = doInvert; doInvert = newDoInvert; if (oldDoInvert != newDoInvert) { _setDecimalsNormalizer( -1 * decimalsNormalizer); } emit InvertUpdate(oldDoInvert, newDoInvert); } function _setDecimalsNormalizer(int256 newDecimalsNormalizer) internal { int256 oldDecimalsNormalizer = decimalsNormalizer; decimalsNormalizer = newDecimalsNormalizer; emit DecimalsNormalizerUpdate(oldDecimalsNormalizer, newDecimalsNormalizer); } function _setDecimalsNormalizerFromToken(address token) internal { int256 feiDecimals = 18; int256 _decimalsNormalizer = feiDecimals - int256(uint256(IERC20Metadata(token).decimals())); if (doInvert) { _decimalsNormalizer = -1 * _decimalsNormalizer; } _setDecimalsNormalizer(_decimalsNormalizer); } } // SPDX-License-Identifier: GPL-3.0-or-later pragma solidity ^0.8.4; import "../oracle/IOracle.sol"; /// @title OracleRef interface /// @author Fei Protocol interface IOracleRef { // ----------- Events ----------- event OracleUpdate(address indexed oldOracle, address indexed newOracle); event InvertUpdate(bool oldDoInvert, bool newDoInvert); event DecimalsNormalizerUpdate(int256 oldDecimalsNormalizer, int256 newDecimalsNormalizer); event BackupOracleUpdate(address indexed oldBackupOracle, address indexed newBackupOracle); // ----------- State changing API ----------- function updateOracle() external; // ----------- Governor only state changing API ----------- function setOracle(address newOracle) external; function setBackupOracle(address newBackupOracle) external; function setDecimalsNormalizer(int256 newDecimalsNormalizer) external; function setDoInvert(bool newDoInvert) external; // ----------- Getters ----------- function oracle() external view returns (IOracle); function backupOracle() external view returns (IOracle); function doInvert() external view returns (bool); function decimalsNormalizer() external view returns (int256); function readOracle() external view returns (Decimal.D256 memory); function invert(Decimal.D256 calldata price) external pure returns (Decimal.D256 memory); } // SPDX-License-Identifier: GPL-3.0-or-later pragma solidity ^0.8.4; import "../external/Decimal.sol"; /// @title generic oracle interface for Fei Protocol /// @author Fei Protocol interface IOracle { // ----------- Events ----------- event Update(uint256 _peg); // ----------- State changing API ----------- function update() external; // ----------- Getters ----------- function read() external view returns (Decimal.D256 memory, bool); function isOutdated() external view returns (bool); } /* Copyright 2019 dYdX Trading Inc. Copyright 2020 Empty Set Squad <[email protected]> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ pragma solidity ^0.8.4; import "@openzeppelin/contracts/utils/math/SafeMath.sol"; /** * @title Decimal * @author dYdX * * Library that defines a fixed-point number with 18 decimal places. */ library Decimal { using SafeMath for uint256; // ============ Constants ============ uint256 private constant BASE = 10**18; // ============ Structs ============ struct D256 { uint256 value; } // ============ Static Functions ============ function zero() internal pure returns (D256 memory) { return D256({ value: 0 }); } function one() internal pure returns (D256 memory) { return D256({ value: BASE }); } function from( uint256 a ) internal pure returns (D256 memory) { return D256({ value: a.mul(BASE) }); } function ratio( uint256 a, uint256 b ) internal pure returns (D256 memory) { return D256({ value: getPartial(a, BASE, b) }); } // ============ Self Functions ============ function add( D256 memory self, uint256 b ) internal pure returns (D256 memory) { return D256({ value: self.value.add(b.mul(BASE)) }); } function sub( D256 memory self, uint256 b ) internal pure returns (D256 memory) { return D256({ value: self.value.sub(b.mul(BASE)) }); } function sub( D256 memory self, uint256 b, string memory reason ) internal pure returns (D256 memory) { return D256({ value: self.value.sub(b.mul(BASE), reason) }); } function mul( D256 memory self, uint256 b ) internal pure returns (D256 memory) { return D256({ value: self.value.mul(b) }); } function div( D256 memory self, uint256 b ) internal pure returns (D256 memory) { return D256({ value: self.value.div(b) }); } function pow( D256 memory self, uint256 b ) internal pure returns (D256 memory) { if (b == 0) { return from(1); } D256 memory temp = D256({ value: self.value }); for (uint256 i = 1; i < b; i++) { temp = mul(temp, self); } return temp; } function add( D256 memory self, D256 memory b ) internal pure returns (D256 memory) { return D256({ value: self.value.add(b.value) }); } function sub( D256 memory self, D256 memory b ) internal pure returns (D256 memory) { return D256({ value: self.value.sub(b.value) }); } function sub( D256 memory self, D256 memory b, string memory reason ) internal pure returns (D256 memory) { return D256({ value: self.value.sub(b.value, reason) }); } function mul( D256 memory self, D256 memory b ) internal pure returns (D256 memory) { return D256({ value: getPartial(self.value, b.value, BASE) }); } function div( D256 memory self, D256 memory b ) internal pure returns (D256 memory) { return D256({ value: getPartial(self.value, BASE, b.value) }); } function equals(D256 memory self, D256 memory b) internal pure returns (bool) { return self.value == b.value; } function greaterThan(D256 memory self, D256 memory b) internal pure returns (bool) { return compareTo(self, b) == 2; } function lessThan(D256 memory self, D256 memory b) internal pure returns (bool) { return compareTo(self, b) == 0; } function greaterThanOrEqualTo(D256 memory self, D256 memory b) internal pure returns (bool) { return compareTo(self, b) > 0; } function lessThanOrEqualTo(D256 memory self, D256 memory b) internal pure returns (bool) { return compareTo(self, b) < 2; } function isZero(D256 memory self) internal pure returns (bool) { return self.value == 0; } function asUint256(D256 memory self) internal pure returns (uint256) { return self.value.div(BASE); } // ============ Core Methods ============ function getPartial( uint256 target, uint256 numerator, uint256 denominator ) private pure returns (uint256) { return target.mul(numerator).div(denominator); } function compareTo( D256 memory a, D256 memory b ) private pure returns (uint256) { if (a.value == b.value) { return 1; } return a.value > b.value ? 2 : 0; } } // SPDX-License-Identifier: GPL-3.0-or-later pragma solidity ^0.8.4; import "@uniswap/v2-core/contracts/interfaces/IUniswapV2Pair.sol"; /// @title UniRef interface /// @author Fei Protocol interface IUniRef { // ----------- Events ----------- event PairUpdate(address indexed oldPair, address indexed newPair); // ----------- Governor only state changing api ----------- function setPair(address newPair) external; // ----------- Getters ----------- function pair() external view returns (IUniswapV2Pair); function token() external view returns (address); function getReserves() external view returns (uint256 feiReserves, uint256 tokenReserves); } pragma solidity >=0.5.0; interface IWETH { function deposit() external payable; function transfer(address to, uint value) external returns (bool); function withdraw(uint) external; } // SPDX-License-Identifier: GPL-3.0-or-later pragma solidity >=0.4.0; // computes square roots using the babylonian method // https://en.wikipedia.org/wiki/Methods_of_computing_square_roots#Babylonian_method library Babylonian { function sqrt(uint y) internal pure returns (uint z) { if (y > 3) { z = y; uint x = y / 2 + 1; while (x < z) { z = x; x = (y / x + x) / 2; } } else if (y != 0) { z = 1; } // else z = 0 } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC20/utils/SafeERC20.sol) 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 // 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); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/Address.sol) pragma solidity ^0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); (bool success, bytes memory returndata) = target.delegatecall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } pragma solidity >=0.6.2; import './IUniswapV2Router01.sol'; interface IUniswapV2Router02 is IUniswapV2Router01 { function removeLiquidityETHSupportingFeeOnTransferTokens( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline ) external returns (uint amountETH); function removeLiquidityETHWithPermitSupportingFeeOnTransferTokens( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external returns (uint amountETH); function swapExactTokensForTokensSupportingFeeOnTransferTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external; function swapExactETHForTokensSupportingFeeOnTransferTokens( uint amountOutMin, address[] calldata path, address to, uint deadline ) external payable; function swapExactTokensForETHSupportingFeeOnTransferTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external; } pragma solidity >=0.6.2; interface IUniswapV2Router01 { function factory() external pure returns (address); function WETH() external pure returns (address); function addLiquidity( address tokenA, address tokenB, uint amountADesired, uint amountBDesired, uint amountAMin, uint amountBMin, address to, uint deadline ) external returns (uint amountA, uint amountB, uint liquidity); function addLiquidityETH( address token, uint amountTokenDesired, uint amountTokenMin, uint amountETHMin, address to, uint deadline ) external payable returns (uint amountToken, uint amountETH, uint liquidity); function removeLiquidity( address tokenA, address tokenB, uint liquidity, uint amountAMin, uint amountBMin, address to, uint deadline ) external returns (uint amountA, uint amountB); function removeLiquidityETH( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline ) external returns (uint amountToken, uint amountETH); function removeLiquidityWithPermit( address tokenA, address tokenB, uint liquidity, uint amountAMin, uint amountBMin, address to, uint deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external returns (uint amountA, uint amountB); function removeLiquidityETHWithPermit( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external returns (uint amountToken, uint amountETH); function swapExactTokensForTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external returns (uint[] memory amounts); function swapTokensForExactTokens( uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline ) external returns (uint[] memory amounts); function swapExactETHForTokens(uint amountOutMin, address[] calldata path, address to, uint deadline) external payable returns (uint[] memory amounts); function swapTokensForExactETH(uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline) external returns (uint[] memory amounts); function swapExactTokensForETH(uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline) external returns (uint[] memory amounts); function swapETHForExactTokens(uint amountOut, address[] calldata path, address to, uint deadline) external payable returns (uint[] memory amounts); function quote(uint amountA, uint reserveA, uint reserveB) external pure returns (uint amountB); function getAmountOut(uint amountIn, uint reserveIn, uint reserveOut) external pure returns (uint amountOut); function getAmountIn(uint amountOut, uint reserveIn, uint reserveOut) external pure returns (uint amountIn); function getAmountsOut(uint amountIn, address[] calldata path) external view returns (uint[] memory amounts); function getAmountsIn(uint amountOut, address[] calldata path) external view returns (uint[] memory amounts); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (security/Pausable.sol) pragma solidity ^0.8.0; import "../utils/Context.sol"; /** * @dev Contract module which allows children to implement an emergency stop * mechanism that can be triggered by an authorized account. * * This module is used through inheritance. It will make available the * modifiers `whenNotPaused` and `whenPaused`, which can be applied to * the functions of your contract. Note that they will not be pausable by * simply including this module, only once the modifiers are put in place. */ abstract contract Pausable is Context { /** * @dev Emitted when the pause is triggered by `account`. */ event Paused(address account); /** * @dev Emitted when the pause is lifted by `account`. */ event Unpaused(address account); bool private _paused; /** * @dev Initializes the contract in unpaused state. */ constructor() { _paused = false; } /** * @dev Returns true if the contract is paused, and false otherwise. */ function paused() public view virtual returns (bool) { return _paused; } /** * @dev Modifier to make a function callable only when the contract is not paused. * * Requirements: * * - The contract must not be paused. */ modifier whenNotPaused() { require(!paused(), "Pausable: paused"); _; } /** * @dev Modifier to make a function callable only when the contract is paused. * * Requirements: * * - The contract must be paused. */ modifier whenPaused() { require(paused(), "Pausable: not paused"); _; } /** * @dev Triggers stopped state. * * Requirements: * * - The contract must not be paused. */ function _pause() internal virtual whenNotPaused { _paused = true; emit Paused(_msgSender()); } /** * @dev Returns to normal state. * * Requirements: * * - The contract must be paused. */ function _unpause() internal virtual whenPaused { _paused = false; emit Unpaused(_msgSender()); } } // SPDX-License-Identifier: MIT // 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 (access/AccessControl.sol) pragma solidity ^0.8.0; import "./IAccessControl.sol"; import "../utils/Context.sol"; import "../utils/Strings.sol"; import "../utils/introspection/ERC165.sol"; /** * @dev Contract module that allows children to implement role-based access * control mechanisms. This is a lightweight version that doesn't allow enumerating role * members except through off-chain means by accessing the contract event logs. Some * applications may benefit from on-chain enumerability, for those cases see * {AccessControlEnumerable}. * * Roles are referred to by their `bytes32` identifier. These should be exposed * in the external API and be unique. The best way to achieve this is by * using `public constant` hash digests: * * ``` * bytes32 public constant MY_ROLE = keccak256("MY_ROLE"); * ``` * * Roles can be used to represent a set of permissions. To restrict access to a * function call, use {hasRole}: * * ``` * function foo() public { * require(hasRole(MY_ROLE, msg.sender)); * ... * } * ``` * * Roles can be granted and revoked dynamically via the {grantRole} and * {revokeRole} functions. Each role has an associated admin role, and only * accounts that have a role's admin role can call {grantRole} and {revokeRole}. * * By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means * that only accounts with this role will be able to grant or revoke other * roles. More complex role relationships can be created by using * {_setRoleAdmin}. * * WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to * grant and revoke this role. Extra precautions should be taken to secure * accounts that have been granted it. */ abstract contract AccessControl is Context, IAccessControl, ERC165 { struct RoleData { mapping(address => bool) members; bytes32 adminRole; } mapping(bytes32 => RoleData) private _roles; bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00; /** * @dev Modifier that checks that an account has a specific role. Reverts * with a standardized message including the required role. * * The format of the revert reason is given by the following regular expression: * * /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/ * * _Available since v4.1._ */ modifier onlyRole(bytes32 role) { _checkRole(role, _msgSender()); _; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IAccessControl).interfaceId || super.supportsInterface(interfaceId); } /** * @dev Returns `true` if `account` has been granted `role`. */ function hasRole(bytes32 role, address account) public view override returns (bool) { return _roles[role].members[account]; } /** * @dev Revert with a standard message if `account` is missing `role`. * * The format of the revert reason is given by the following regular expression: * * /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/ */ function _checkRole(bytes32 role, address account) internal view { if (!hasRole(role, account)) { revert( string( abi.encodePacked( "AccessControl: account ", Strings.toHexString(uint160(account), 20), " is missing role ", Strings.toHexString(uint256(role), 32) ) ) ); } } /** * @dev Returns the admin role that controls `role`. See {grantRole} and * {revokeRole}. * * To change a role's admin, use {_setRoleAdmin}. */ function getRoleAdmin(bytes32 role) public view override returns (bytes32) { return _roles[role].adminRole; } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function grantRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) { _grantRole(role, account); } /** * @dev Revokes `role` from `account`. * * If `account` had been granted `role`, emits a {RoleRevoked} event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function revokeRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) { _revokeRole(role, account); } /** * @dev Revokes `role` from the calling account. * * Roles are often managed via {grantRole} and {revokeRole}: this function's * purpose is to provide a mechanism for accounts to lose their privileges * if they are compromised (such as when a trusted device is misplaced). * * If the calling account had been revoked `role`, emits a {RoleRevoked} * event. * * Requirements: * * - the caller must be `account`. */ function renounceRole(bytes32 role, address account) public virtual override { require(account == _msgSender(), "AccessControl: can only renounce roles for self"); _revokeRole(role, account); } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. Note that unlike {grantRole}, this function doesn't perform any * checks on the calling account. * * [WARNING] * ==== * This function should only be called from the constructor when setting * up the initial roles for the system. * * Using this function in any other way is effectively circumventing the admin * system imposed by {AccessControl}. * ==== * * NOTE: This function is deprecated in favor of {_grantRole}. */ function _setupRole(bytes32 role, address account) internal virtual { _grantRole(role, account); } /** * @dev Sets `adminRole` as ``role``'s admin role. * * Emits a {RoleAdminChanged} event. */ function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual { bytes32 previousAdminRole = getRoleAdmin(role); _roles[role].adminRole = adminRole; emit RoleAdminChanged(role, previousAdminRole, adminRole); } /** * @dev Grants `role` to `account`. * * Internal function without access restriction. */ function _grantRole(bytes32 role, address account) internal virtual { if (!hasRole(role, account)) { _roles[role].members[account] = true; emit RoleGranted(role, account, _msgSender()); } } /** * @dev Revokes `role` from `account`. * * Internal function without access restriction. */ function _revokeRole(bytes32 role, address account) internal virtual { if (hasRole(role, account)) { _roles[role].members[account] = false; emit RoleRevoked(role, account, _msgSender()); } } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.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/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 (utils/math/SafeCast.sol) pragma solidity ^0.8.0; /** * @dev Wrappers over Solidity's uintXX/intXX casting operators with added overflow * checks. * * Downcasting from uint256/int256 in Solidity does not revert on overflow. This can * easily result in undesired exploitation or bugs, since developers usually * assume that overflows raise errors. `SafeCast` restores this intuition by * reverting the transaction when such an operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. * * Can be combined with {SafeMath} and {SignedSafeMath} to extend it to smaller types, by performing * all math on `uint256` and `int256` and then downcasting. */ library SafeCast { /** * @dev Returns the downcasted uint224 from uint256, reverting on * overflow (when the input is greater than largest uint224). * * Counterpart to Solidity's `uint224` operator. * * Requirements: * * - input must fit into 224 bits */ function toUint224(uint256 value) internal pure returns (uint224) { require(value <= type(uint224).max, "SafeCast: value doesn't fit in 224 bits"); return uint224(value); } /** * @dev Returns the downcasted uint128 from uint256, reverting on * overflow (when the input is greater than largest uint128). * * Counterpart to Solidity's `uint128` operator. * * Requirements: * * - input must fit into 128 bits */ function toUint128(uint256 value) internal pure returns (uint128) { require(value <= type(uint128).max, "SafeCast: value doesn't fit in 128 bits"); return uint128(value); } /** * @dev Returns the downcasted uint96 from uint256, reverting on * overflow (when the input is greater than largest uint96). * * Counterpart to Solidity's `uint96` operator. * * Requirements: * * - input must fit into 96 bits */ function toUint96(uint256 value) internal pure returns (uint96) { require(value <= type(uint96).max, "SafeCast: value doesn't fit in 96 bits"); return uint96(value); } /** * @dev Returns the downcasted uint64 from uint256, reverting on * overflow (when the input is greater than largest uint64). * * Counterpart to Solidity's `uint64` operator. * * Requirements: * * - input must fit into 64 bits */ function toUint64(uint256 value) internal pure returns (uint64) { require(value <= type(uint64).max, "SafeCast: value doesn't fit in 64 bits"); return uint64(value); } /** * @dev Returns the downcasted uint32 from uint256, reverting on * overflow (when the input is greater than largest uint32). * * Counterpart to Solidity's `uint32` operator. * * Requirements: * * - input must fit into 32 bits */ function toUint32(uint256 value) internal pure returns (uint32) { require(value <= type(uint32).max, "SafeCast: value doesn't fit in 32 bits"); return uint32(value); } /** * @dev Returns the downcasted uint16 from uint256, reverting on * overflow (when the input is greater than largest uint16). * * Counterpart to Solidity's `uint16` operator. * * Requirements: * * - input must fit into 16 bits */ function toUint16(uint256 value) internal pure returns (uint16) { require(value <= type(uint16).max, "SafeCast: value doesn't fit in 16 bits"); return uint16(value); } /** * @dev Returns the downcasted uint8 from uint256, reverting on * overflow (when the input is greater than largest uint8). * * Counterpart to Solidity's `uint8` operator. * * Requirements: * * - input must fit into 8 bits. */ function toUint8(uint256 value) internal pure returns (uint8) { require(value <= type(uint8).max, "SafeCast: value doesn't fit in 8 bits"); return uint8(value); } /** * @dev Converts a signed int256 into an unsigned uint256. * * Requirements: * * - input must be greater than or equal to 0. */ function toUint256(int256 value) internal pure returns (uint256) { require(value >= 0, "SafeCast: value must be positive"); return uint256(value); } /** * @dev Returns the downcasted int128 from int256, reverting on * overflow (when the input is less than smallest int128 or * greater than largest int128). * * Counterpart to Solidity's `int128` operator. * * Requirements: * * - input must fit into 128 bits * * _Available since v3.1._ */ function toInt128(int256 value) internal pure returns (int128) { require(value >= type(int128).min && value <= type(int128).max, "SafeCast: value doesn't fit in 128 bits"); return int128(value); } /** * @dev Returns the downcasted int64 from int256, reverting on * overflow (when the input is less than smallest int64 or * greater than largest int64). * * Counterpart to Solidity's `int64` operator. * * Requirements: * * - input must fit into 64 bits * * _Available since v3.1._ */ function toInt64(int256 value) internal pure returns (int64) { require(value >= type(int64).min && value <= type(int64).max, "SafeCast: value doesn't fit in 64 bits"); return int64(value); } /** * @dev Returns the downcasted int32 from int256, reverting on * overflow (when the input is less than smallest int32 or * greater than largest int32). * * Counterpart to Solidity's `int32` operator. * * Requirements: * * - input must fit into 32 bits * * _Available since v3.1._ */ function toInt32(int256 value) internal pure returns (int32) { require(value >= type(int32).min && value <= type(int32).max, "SafeCast: value doesn't fit in 32 bits"); return int32(value); } /** * @dev Returns the downcasted int16 from int256, reverting on * overflow (when the input is less than smallest int16 or * greater than largest int16). * * Counterpart to Solidity's `int16` operator. * * Requirements: * * - input must fit into 16 bits * * _Available since v3.1._ */ function toInt16(int256 value) internal pure returns (int16) { require(value >= type(int16).min && value <= type(int16).max, "SafeCast: value doesn't fit in 16 bits"); return int16(value); } /** * @dev Returns the downcasted int8 from int256, reverting on * overflow (when the input is less than smallest int8 or * greater than largest int8). * * Counterpart to Solidity's `int8` operator. * * Requirements: * * - input must fit into 8 bits. * * _Available since v3.1._ */ function toInt8(int256 value) internal pure returns (int8) { require(value >= type(int8).min && value <= type(int8).max, "SafeCast: value doesn't fit in 8 bits"); return int8(value); } /** * @dev Converts an unsigned uint256 into a signed int256. * * Requirements: * * - input must be less than or equal to maxInt256. */ function toInt256(uint256 value) internal pure returns (int256) { // Note: Unsafe cast below is okay because `type(int256).max` is guaranteed to be positive require(value <= uint256(type(int256).max), "SafeCast: value doesn't fit in an int256"); return int256(value); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC20/extensions/IERC20Metadata.sol) pragma solidity ^0.8.0; import "../IERC20.sol"; /** * @dev Interface for the optional metadata functions from the ERC20 standard. * * _Available since v4.1._ */ interface IERC20Metadata is IERC20 { /** * @dev Returns the name of the token. */ function name() external view returns (string memory); /** * @dev Returns the symbol of the token. */ function symbol() external view returns (string memory); /** * @dev Returns the decimals places of the token. */ function decimals() external view returns (uint8); } // SPDX-License-Identifier: MIT // 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; } } } pragma solidity >=0.5.0; interface IUniswapV2Pair { event Approval(address indexed owner, address indexed spender, uint value); event Transfer(address indexed from, address indexed to, uint value); function name() external pure returns (string memory); function symbol() external pure returns (string memory); function decimals() external pure returns (uint8); function totalSupply() external view returns (uint); function balanceOf(address owner) external view returns (uint); function allowance(address owner, address spender) external view returns (uint); function approve(address spender, uint value) external returns (bool); function transfer(address to, uint value) external returns (bool); function transferFrom(address from, address to, uint value) external returns (bool); function DOMAIN_SEPARATOR() external view returns (bytes32); function PERMIT_TYPEHASH() external pure returns (bytes32); function nonces(address owner) external view returns (uint); function permit(address owner, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) external; event Mint(address indexed sender, uint amount0, uint amount1); event Burn(address indexed sender, uint amount0, uint amount1, address indexed to); event Swap( address indexed sender, uint amount0In, uint amount1In, uint amount0Out, uint amount1Out, address indexed to ); event Sync(uint112 reserve0, uint112 reserve1); function MINIMUM_LIQUIDITY() external pure returns (uint); function factory() external view returns (address); function token0() external view returns (address); function token1() external view returns (address); function getReserves() external view returns (uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast); function price0CumulativeLast() external view returns (uint); function price1CumulativeLast() external view returns (uint); function kLast() external view returns (uint); function mint(address to) external returns (uint liquidity); function burn(address to) external returns (uint amount0, uint amount1); function swap(uint amount0Out, uint amount1Out, address to, bytes calldata data) external; function skim(address to) external; function sync() external; function initialize(address, address) external; }
set the new pair contract _pair the new pair also approves the router for the new pair token and underlying token
function setPair(address _pair) public virtual override onlyGovernor { _setupPair(_pair); _approveToken(token); _approveToken(_pair); }
10,229,783
./full_match/5/0x5137ABFf24ad5b7f8079F7f9BfCDB5645e490526/sources/project_/contracts/util/Issuable.sol
Returns true if the caller is one of the current issuer./
function isIssuer() public view returns (bool) { for (uint i = 0; i < _issuers.length; i++) { if (_issuers[i] == msg.sender) { return true; } } return false; }
11,594,536
./full_match/56/0xfC652Ea2E8A373C16f3d8c5BD25E9898b9699ECB/sources/contracts/IFAllocationMaster.sol
get closest PRECEDING user checkpoint get total checkpoint count for user First check most recent checkpoint return closest checkpoint Next check earliest checkpoint If specified timestamp number is earlier than user's first checkpoint, return null checkpoint
function getClosestUserCheckpoint( uint24 trackId, address user, uint80 timestamp ) private view returns (UserCheckpoint memory cp) { uint32 nCheckpoints = userCheckpointCounts[trackId][user]; if ( userCheckpoints[trackId][user][nCheckpoints - 1].timestamp <= timestamp ) { return userCheckpoints[trackId][user][nCheckpoints - 1]; return UserCheckpoint({ timestamp: 0, staked: 0, stakeWeight: 0, numFinishedSales: 0 }); uint32 upper = nCheckpoints - 1; while (upper > lower) { UserCheckpoint memory tempCp = userCheckpoints[trackId][user][ center ]; if (tempCp.timestamp == timestamp) { return tempCp; lower = center; upper = center - 1; } } } }
3,247,466
// SPDX-License-Identifier: Apache-2.0 /* Copyright 2021 ZeroEx Intl. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ pragma solidity ^0.6.5; pragma experimental ABIEncoderV2; import "@0x/contracts-erc20/contracts/src/v06/IEtherTokenV06.sol"; import "@0x/contracts-utils/contracts/src/v06/errors/LibRichErrorsV06.sol"; import "@0x/contracts-utils/contracts/src/v06/LibSafeMathV06.sol"; import "../../fixins/FixinProtocolFees.sol"; import "../../errors/LibNativeOrdersRichErrors.sol"; import "../../vendor/v3/IStaking.sol"; /// @dev Mixin for protocol fee utility functions. abstract contract NativeOrdersProtocolFees is FixinProtocolFees { using LibSafeMathV06 for uint256; using LibRichErrorsV06 for bytes; constructor( IEtherTokenV06 weth, IStaking staking, FeeCollectorController feeCollectorController, uint32 protocolFeeMultiplier ) internal FixinProtocolFees(weth, staking, feeCollectorController, protocolFeeMultiplier) { // solhint-disable no-empty-blocks } /// @dev Transfers protocol fees from the `FeeCollector` pools into /// the staking contract. /// @param poolIds Staking pool IDs function transferProtocolFeesForPools(bytes32[] calldata poolIds) external { for (uint256 i = 0; i < poolIds.length; ++i) { _transferFeesForPool(poolIds[i]); } } /// @dev Get the protocol fee multiplier. This should be multiplied by the /// gas price to arrive at the required protocol fee to fill a native order. /// @return multiplier The protocol fee multiplier. function getProtocolFeeMultiplier() external view returns (uint32 multiplier) { return PROTOCOL_FEE_MULTIPLIER; } }
Transfers protocol fees from the `FeeCollector` pools into the staking contract. poolIds Staking pool IDs
function transferProtocolFeesForPools(bytes32[] calldata poolIds) external { for (uint256 i = 0; i < poolIds.length; ++i) { _transferFeesForPool(poolIds[i]); } }
12,969,122
./full_match/1/0x9837Ce9825D52672Ca02533B5A160212bf901963/sources/contracts/libraries/Throttle.sol
Reverts if usage amount exceeds available amount supply {qRTok} Total RToken supply beforehand amount {qRTok} Amount of RToken to use. Should be negative for the issuance throttle during redemption and for the redemption throttle during issuance. untestable: amtRate will always be greater > 0 due to previous validations Calculate hourly limit Calculate available amount before supply change Calculate available amount after supply change untestable: the final else statement, amount will never be 0
function useAvailable( Throttle storage throttle, uint256 supply, int256 amount ) internal { if (throttle.params.amtRate == 0 && throttle.params.pctRate == 0) return; uint256 available = currentlyAvailable(throttle, limit); if (amount > 0) { require(uint256(amount) <= available, "supply change throttled"); available -= uint256(amount); available += uint256(-amount); } throttle.lastTimestamp = uint48(block.timestamp); }
16,407,699
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Library for managing * https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive * types. * * Sets have the following properties: * * - Elements are added, removed, and checked for existence in constant time * (O(1)). * - Elements are enumerated in O(n). No guarantees are made on the ordering. * * ``` * contract Example { * // Add the library methods * using EnumerableSet for EnumerableSet.AddressSet; * * // Declare a set state variable * EnumerableSet.AddressSet private mySet; * } * ``` * * As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`) * and `uint256` (`UintSet`) are supported. */ library EnumerableSet { // To implement this library for multiple types with as little code // repetition as possible, we write it in terms of a generic Set type with // bytes32 values. // The Set implementation uses private functions, and user-facing // implementations (such as AddressSet) are just wrappers around the // underlying Set. // This means that we can only create new EnumerableSets for types that fit // in bytes32. struct Set { // Storage of set values bytes32[] _values; // Position of the value in the `values` array, plus 1 because index 0 // means a value is not in the set. mapping(bytes32 => uint256) _indexes; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function _add(Set storage set, bytes32 value) private returns (bool) { if (!_contains(set, value)) { set._values.push(value); // The value is stored at length-1, but we add 1 to all indexes // and use 0 as a sentinel value set._indexes[value] = set._values.length; return true; } else { return false; } } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function _remove(Set storage set, bytes32 value) private returns (bool) { // We read and store the value's index to prevent multiple reads from the same storage slot uint256 valueIndex = set._indexes[value]; if (valueIndex != 0) { // Equivalent to contains(set, value) // To delete an element from the _values array in O(1), we swap the element to delete with the last one in // the array, and then remove the last element (sometimes called as 'swap and pop'). // This modifies the order of the array, as noted in {at}. uint256 toDeleteIndex = valueIndex - 1; uint256 lastIndex = set._values.length - 1; if (lastIndex != toDeleteIndex) { bytes32 lastvalue = set._values[lastIndex]; // Move the last value to the index where the value to delete is set._values[toDeleteIndex] = lastvalue; // Update the index for the moved value set._indexes[lastvalue] = valueIndex; // Replace lastvalue's index to valueIndex } // Delete the slot where the moved value was stored set._values.pop(); // Delete the index for the deleted slot delete set._indexes[value]; return true; } else { return false; } } /** * @dev Returns true if the value is in the set. O(1). */ function _contains(Set storage set, bytes32 value) private view returns (bool) { return set._indexes[value] != 0; } /** * @dev Returns the number of values on the set. O(1). */ function _length(Set storage set) private view returns (uint256) { return set._values.length; } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function _at(Set storage set, uint256 index) private view returns (bytes32) { return set._values[index]; } // Bytes32Set struct Bytes32Set { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _add(set._inner, value); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _remove(set._inner, value); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) { return _contains(set._inner, value); } /** * @dev Returns the number of values in the set. O(1). */ function length(Bytes32Set storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) { return _at(set._inner, index); } // AddressSet struct AddressSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(AddressSet storage set, address value) internal returns (bool) { return _add(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(AddressSet storage set, address value) internal returns (bool) { return _remove(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(AddressSet storage set, address value) internal view returns (bool) { return _contains(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Returns the number of values in the set. O(1). */ function length(AddressSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(AddressSet storage set, uint256 index) internal view returns (address) { return address(uint160(uint256(_at(set._inner, index)))); } // UintSet struct UintSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(UintSet storage set, uint256 value) internal returns (bool) { return _add(set._inner, bytes32(value)); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(UintSet storage set, uint256 value) internal returns (bool) { return _remove(set._inner, bytes32(value)); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(UintSet storage set, uint256 value) internal view returns (bool) { return _contains(set._inner, bytes32(value)); } /** * @dev Returns the number of values on the set. O(1). */ function length(UintSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(UintSet storage set, uint256 index) internal view returns (uint256) { return uint256(_at(set._inner, index)); } } //SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import '@openzeppelin/contracts/utils/structs/EnumerableSet.sol'; import './IEarlyBirdRegistry.sol'; /// @title EarlyBirdRegistry /// @author Simon Fremaux (@dievardump) contract EarlyBirdRegistry is IEarlyBirdRegistry { using EnumerableSet for EnumerableSet.AddressSet; event ProjectCreated( address indexed creator, uint256 indexed projectId, uint256 endRegistration, // when the registration ends uint256 maxRegistration, // how many people can register bool open // if the project accepts Open Registration ); event Registration(uint256 indexed projectId, address[] list); struct Project { bool open; address creator; uint256 endRegistration; uint256 maxRegistration; } // this is a counter that increments automatically when registering an Early Bird Project uint256 lastProjectId; // list of all projects mapping(uint256 => Project) public projects; // list of registered address for a project mapping(uint256 => EnumerableSet.AddressSet) internal _registered; modifier onlyProject(uint256 projectId) { require(exists(projectId), 'Unknown project id.'); _; } constructor() {} /// @notice allows anyone to register a new project that accepts Early Birds registrations /// @param open if the early bird registration is open or only creator can register addresses /// @param endRegistration unix epoch timestamp of registration closing /// @param maxRegistration the max registration count /// @return projectId the project Id (useful if called by a contract) function registerProject( bool open, uint256 endRegistration, uint256 maxRegistration ) external override returns (uint256 projectId) { projectId = lastProjectId + 1; lastProjectId = projectId; projects[projectId] = Project({ open: open, creator: msg.sender, endRegistration: endRegistration, maxRegistration: maxRegistration }); emit ProjectCreated( msg.sender, projectId, endRegistration, maxRegistration, open ); } /// @notice tells if a project exists /// @param projectId project id to check /// @return true if the project exists function exists(uint256 projectId) public view override returns (bool) { return projectId > 0 && projectId <= lastProjectId; } /// @notice Helper to paginate all address registered for a project /// Using pagination just in case it ever happens that there are much EarlyBirds /// @param projectId the project id /// @param offset index where to start /// @param limit how many to grab /// @return list of registered addresses function listRegistrations( uint256 projectId, uint256 offset, uint256 limit ) external view override onlyProject(projectId) returns (address[] memory list) { EnumerableSet.AddressSet storage registered = _registered[projectId]; uint256 count = registered.length(); require(offset < count, 'Offset too high'); if (count < offset + limit) { limit = count - offset; } list = new address[](limit); for (uint256 i; i < limit; i++) { list[i] = registered.at(offset + i); } } /// @notice Helper to know how many address registered to a project /// @param projectId the project id /// @return how many people registered function registeredCount(uint256 projectId) external view override onlyProject(projectId) returns (uint256) { return _registered[projectId].length(); } /// @notice Small helpers that returns in how many seconds a project registration ends /// @param projectId to check /// @return the time in second before end; 0 if ended function registrationEndsIn(uint256 projectId) public view returns (uint256) { if (projects[projectId].endRegistration <= block.timestamp) { return 0; } return projects[projectId].endRegistration - block.timestamp; } /// @notice Helper to check if an address is registered for a project id /// @param check the address to check /// @param projectId the project id /// @return if the address was registered as an early bird function isRegistered(address check, uint256 projectId) external view override onlyProject(projectId) returns (bool) { return _registered[projectId].contains(check); } /// @notice Allows the creator of a project to change registration open state /// this can be usefull to first register a specific list of addresses /// before making the registration public /// @param projectId to modify /// @param open if the project is open to anyone or only creator can change function setRegistrationOpen(uint256 projectId, bool open) external { require( msg.sender == projects[projectId].creator, 'Not project creator.' ); projects[projectId].open = open; } /// @notice Allows a user to register for an EarlyBird spot on a project /// @dev the project needs to be "open" for people to register directly to it /// @param projectId the project id to register to function registerTo(uint256 projectId) external onlyProject(projectId) { Project memory project = projects[projectId]; require(project.open == true, 'Project not open.'); EnumerableSet.AddressSet storage registered = _registered[projectId]; require( // before end registration time block.timestamp <= project.endRegistration && // and there is still available spots registered.length() + 1 <= project.maxRegistration, 'Registration closed.' ); require(!registered.contains(msg.sender), 'Already registered'); // add user to list registered.add(msg.sender); address[] memory list = new address[](1); list[0] = msg.sender; emit Registration(projectId, list); } /// @notice Allows a project creator to add early birds in Batch /// @dev msg.sender must be the projectId creator /// @param projectId to add to /// @param birds all addresses to add function registerBatchTo(uint256 projectId, address[] memory birds) external override { Project memory project = projects[projectId]; require(msg.sender == project.creator, 'Not project creator.'); uint256 count = birds.length; EnumerableSet.AddressSet storage registered = _registered[projectId]; // before end registration time require( block.timestamp <= project.endRegistration, 'Registration closed.' ); // and there is still enough available spots require( registered.length() + count <= project.maxRegistration, 'Not enough spots.' ); for (uint256 i; i < count; i++) { registered.add(birds[i]); } emit Registration(projectId, birds); } } //SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /// @title IEarlyBirdRegistry /// @author Simon Fremaux (@dievardump) interface IEarlyBirdRegistry { /// @notice allows anyone to register a new project that accepts Early Birds registrations /// @param open if the early bird registration is open or only creator can register addresses /// @param endRegistration unix epoch timestamp of registration closing /// @param maxRegistration the max registration count /// @return projectId the project Id (useful if called by a contract) function registerProject( bool open, uint256 endRegistration, uint256 maxRegistration ) external returns (uint256 projectId); /// @notice tells if a project exists /// @param projectId project id to check /// @return if the project exists function exists(uint256 projectId) external view returns (bool); /// @notice Helper to paginate all address registered for a project /// @param projectId the project id /// @param offset index where to start /// @param limit how many to grab /// @return list of registered addresses function listRegistrations( uint256 projectId, uint256 offset, uint256 limit ) external view returns (address[] memory list); /// @notice Helper to know how many address registered to a project /// @param projectId the project id /// @return how many people registered function registeredCount(uint256 projectId) external view returns (uint256); /// @notice Helper to check if an address is registered for a project id /// @param check the address to check /// @param projectId the project id /// @return if the address was registered as an early bird function isRegistered(address check, uint256 projectId) external view returns (bool); /// @notice Allows a project creator to add early birds in Batch /// @dev msg.sender must be the projectId creator /// @param projectId to add to /// @param birds all addresses to add function registerBatchTo(uint256 projectId, address[] memory birds) external; }
Allows a project creator to add early birds in Batch msg.sender must be the projectId creator projectId to add to birds all addresses to add before end registration time and there is still enough available spots
function registerBatchTo(uint256 projectId, address[] memory birds) external override { Project memory project = projects[projectId]; require(msg.sender == project.creator, 'Not project creator.'); uint256 count = birds.length; EnumerableSet.AddressSet storage registered = _registered[projectId]; require( block.timestamp <= project.endRegistration, 'Registration closed.' ); require( registered.length() + count <= project.maxRegistration, 'Not enough spots.' ); for (uint256 i; i < count; i++) { registered.add(birds[i]); } emit Registration(projectId, birds); }
6,147,981
./full_match/4/0x6BE60E29FBb7559A5aF18D1e8F840767dd315359/sources/usingtellor/contracts/UsingTellor.sol
Allows the user to get the latest value for the requestId specified _requestId is the requestId to look up the value for return ifRetrieve bool true if it is able to retreive a value, the value, and the value's timestamp return value the value retrieved return _timestampRetrieved the value's timestamp/
function getCurrentValue(uint256 _requestId) public view returns ( bool ifRetrieve, uint256 value, uint256 _timestampRetrieved ) { uint256 _count = tellor.getNewValueCountbyRequestId(_requestId); uint256 _time = tellor.getTimestampbyRequestIDandIndex( _requestId, _count - 1 ); uint256 _value = tellor.retrieveData(_requestId, _time); if (_value > 0) return (true, _value, _time); return (false, 0, _time); }
817,552
./partial_match/1/0x0ace20a35eE382Bda90D1D93CEE65f5970FC01c8/sources/Chip.sol
Returns the symbol of the token, usually a shorter version of the name./
function symbol() public view returns (string memory) { return _symbol; }
4,257,943
/** *Submitted for verification at Etherscan.io on 2021-08-28 */ // SPDX-License-Identifier: MIT pragma solidity ^0.8.7; // ---------------------------------------------------------------------------- /// @author Gradi Kayamba /// @title Bozindo Currency - BOZY // ---------------------------------------------------------------------------- // ---------------------------------------------------------------------------- /// @title Interface : Token Standard #20. https://github.com/ethereum/EIPs/issues/20 // ---------------------------------------------------------------------------- interface ERC20Interface { /** * @dev Triggers on any successful call to transfer() and transferFrom(). * @param _from : The address sending the tokens. * @param _to : The address receiving the tokens. * @param _amount : The quantity of tokens to be sent. */ event Transfer(address indexed _from, address indexed _to, uint256 _amount); /** * @dev Triggers on any successful call to approve() and allowance(). * @param _owner : The address allowing token to be spent. * @param _spender : The address allowed to spend tokens. * @param _amount : The quantity allowed to be spent. */ event Approval(address indexed _owner, address indexed _spender, uint256 _amount); /** * @notice Transfers `_amount` tokens to `_to`. * @param _to : The address receiving tokens. * @param _amount : The quantity of tokens to send. */ function transfer(address _to, uint256 _amount) external returns (bool success); /** * @notice Transfers `_amount` tokens from `_from` to `_to`. * @param _from : The address sending tokens. * @param _to : The address receiving tokens. * @param _amount : The quantity of tokens to be sent. */ function transferFrom(address _from, address _to, uint256 _amount) external returns (bool success); /** * @notice Sets `_amount` to be spent by `_spender` on your behalf. * @param _spender : The address allowed to spend tokens. * @param _amount : The quantity allowed to be spent. */ function approve(address _spender, uint256 _amount) external returns (bool success); /** * @notice Returns the amount which `_spender` is still allowed to withdraw from `_owner`. * @param _owner : The address allowing token to be spent. * @param _spender : The address allowed to spend tokens. */ function allowance(address _owner, address _spender) external view returns (uint256 remaining); /** * @notice Returns the amount of tokens owned by account `_owner`. * @param _owner : The address from which the balance will be retrieved. * @return holdings 000 */ function balanceOf(address _owner) external view returns (uint256 holdings); /** * @notice Returns the amount of tokens in existence. * @return remaining 000 */ function totalSupply() external view returns (uint256); } // ---------------------------------------------------------------------------- /// @title Context : Information about sender, and value of the transaction. // ---------------------------------------------------------------------------- abstract contract Context { /// @dev Returns information about the sender of the transaction. function _msgSender() internal view virtual returns (address payable) { return payable(msg.sender); } /// @dev Returns information about the value of the transaction. function _msgValue() internal view virtual returns (uint256) { return msg.value; } } // ---------------------------------------------------------------------------- /// @title Ownable : Information about the founder of the contract and none-zero address modifier. // ---------------------------------------------------------------------------- abstract contract Ownable is Context { // Define public constant variables. address payable public founder; mapping(address => uint256) balances; // Set values on construction. constructor() { founder = payable(_msgSender()); } /** * @dev Triggers on any successful call to transferOwnership(). * @param _oldOwner : The address tranfering the ownership. * @param _newOwner : The address gaining ownership. */ event TransferOwnership(address _oldOwner, address _newOwner); /// @dev Makes a function callable only by the founder. modifier onlyFounder() { require(_msgSender() == founder, "Your are not the Founder."); _; } /// @dev Makes a function callable only when the _owner is not a zero-address. modifier noneZero(address _owner){ require(_owner != address(0), "Zero address not allowed."); _; } /** * @notice Transfers ownership of the contract to `_newOwner`. * @notice Callable by the founder only. * @notice Callable only by a none-zero address. */ function transferOwnership(address payable _newOwner) onlyFounder noneZero(_newOwner) public returns (bool success) { // Check founder's balance. uint256 founderBalance = balances[founder]; // Check new owner's balance. uint256 newOwnerBalance = balances[_newOwner]; // Set founder balance to 0. balances[founder] = 0; // Add founder's old balance to the new owner's balance. balances[_newOwner] = newOwnerBalance + founderBalance; // Transfer ownership from `founder` to the `_newOwner`. founder = _newOwner; // Emit event emit TransferOwnership(founder, _newOwner); // Returns true on success. return true; } } // ---------------------------------------------------------------------------- /// @title Whitelisted : The ability to block evil users' transactions and to burn their tokens. // ---------------------------------------------------------------------------- abstract contract Whitelisted is Ownable { // Define public constant variables. mapping (address => bool) public isWhitelisted; /** * @dev Triggers on any successful call to burnWhiteTokens(). * @param _evilOwner : The address to burn tokens from. * @param _dirtyTokens : The quantity of tokens burned. */ event BurnWhiteTokens(address _evilOwner, uint256 _dirtyTokens); /** * @dev Triggers on any successful call to addToWhitelist(). * @param _evilOwner : The address to add to whitelist. */ event AddToWhitelist(address _evilOwner); /** * @dev Triggers on any successful call to removedFromWhitelist(). * @param _owner : The address to remove from whitelist. */ event RemovedFromWhitelist(address _owner); /// @dev Makes a function callable only when `_owner` is not whitelisted. modifier whenNotWhitelisted(address _owner) { require(isWhitelisted[_owner] == false, "Whitelisted status detected; please check whitelisted status."); _; } /// @dev Makes a function callable only when `_owner` is whitelisted. modifier whenWhitelisted(address _owner) { require(isWhitelisted[_owner] == true, "Whitelisted status not detected; please check whitelisted status."); _; } /** * @notice Adds `_evilOwner` to whitelist. * @notice Callable only by the founder. * @notice Callable only when `_evilOwner` is not whitelisted. * @param _evilOwner : The address to whitelist. * @return success */ function addToWhitelist(address _evilOwner) onlyFounder whenNotWhitelisted(_evilOwner) public returns (bool success) { // Set whitelisted status isWhitelisted[_evilOwner] = true; // Emit event emit AddToWhitelist(_evilOwner); // Returns true on success. return true; } /** * @notice Removes `_owner` from whitelist. * @notice Callable only by the founder. * @notice Callable only when `_owner` is whitelisted. * @param _owner : The address to remove from whitelist. * @return success */ function removedFromWhitelist(address _owner) onlyFounder whenWhitelisted(_owner) public returns (bool success) { // Unset whitelisted status isWhitelisted[_owner] = false; // Emit event emit RemovedFromWhitelist(_owner); // Returns true on success. return true; } /** * @notice Burns tokens of `_evilOwner`. * @notice Callable only by the founder. * @notice Callable only when `_evilOwner` is whitelisted. * @param _evilOwner : The address to burn funds from. * @return success */ function burnWhiteTokens(address _evilOwner) onlyFounder whenWhitelisted(_evilOwner) public returns (bool success) { // Check evil owner's balance - NOTE - Always check the balance first. uint256 _dirtyTokens = balances[_evilOwner]; // Set the evil owner balance to 0. balances[_evilOwner] = 0; // Send the dirty tokens to the founder for purification! balances[founder] += _dirtyTokens; // Emit event emit BurnWhiteTokens(_evilOwner, _dirtyTokens); // Returns true on success. return true; } } // ---------------------------------------------------------------------------- /// @title Pausable: The ability to pause or unpause trasactions of all tokens. // ---------------------------------------------------------------------------- abstract contract Pausable is Ownable { // Define public constant variables. bool public paused = false; /// @dev Triggers on any successful call to pause(). event Pause(); /// @dev Triggers on any successful call to unpause(). event Unpause(); /// @dev Makes a function callable only when the contract is not paused. modifier whenNotPaused() { require(paused == false, "All transactions have been paused."); _; } /// @dev Makes a function callable only when the contract is paused. modifier whenPaused() { require(paused); _; } /** * @notice Pauses transactions. * @notice Callable only by the founder. * @notice Callable only when the contract is not paused. * @return success */ function pause() public onlyFounder whenNotPaused returns (bool success) { // Set pause paused = true; // See {event Pause} emit Pause(); // Returns true on success. return true; } /** * @dev Unpauses transactions. * @notice Callable only by the founder. * @notice Callable only when the contract is paused. * @return success */ function unpause() public onlyFounder whenPaused returns (bool success) { // Unset pause paused = false; // See {event Unpause} emit Unpause(); // Returns true on success. return true; } } // ---------------------------------------------------------------------------- /// @title Bozy : ERC Token. // ---------------------------------------------------------------------------- contract Bozy is ERC20Interface, Context, Ownable, Whitelisted, Pausable { // Define public constant variables. uint8 public decimals; // Number of decimals string public name; // Token name string public symbol; // Token symbol uint256 public tokenPrice; uint256 public override totalSupply; mapping(address => mapping(address => uint256)) allowed; // Set immutable values. constructor() { name = "Bozindo.com Currency"; decimals = 18; symbol = "BOZY"; totalSupply = 30000000000E18; balances[founder] = totalSupply; tokenPrice = 0.00001 ether; } /** * @dev Triggers on any successful call to mint(). * @param _from : The address minting tokens. * @param _to : The address tokens will be minted to. * @param _amount : The quantity of tokes to be minted. */ event Mint(address indexed _from, address indexed _to, uint256 _amount); /** * @dev Triggers on any successful call to burn(). * @param _from : The address burning tokens. * @param _to : The address tokens will be burned from. * @param _amount : The quantity of tokes to be burned. */ event Burn(address indexed _from, address indexed _to, uint256 _amount); /** * @notice Changes token name to `_newName`. * @notice Callable by the founder only. * @notice Callable only by a none-zero address. */ function changeTokenName(string memory _newName) onlyFounder public returns (bool success) { // Change token name from `name` to the `_newName`. name = _newName; // Returns true on success. return true; } /** * @notice Changes token symbol to `_newSymbol`. * @notice Callable by the founder only. * @notice Callable only by a none-zero address. */ function changeTokenSymbol(string memory _newSymbol) onlyFounder public returns (bool success) { // Change token symbol from `symbol` to the `_newSymbol`. symbol = _newSymbol; // Returns true on success. return true; } /** * @notice Changes token price to `_newPrice` in wei. * @notice Callable by the founder only. * @notice Callable only by a none-zero address. */ function changeTokenPrice(uint256 _newPrice) onlyFounder public returns (bool success) { // Change token price from `tokenPrice` to the `_newPrice` in wei. tokenPrice = _newPrice; // Returns true on success. return true; } // See {_transfer} and {ERC20Interface - transfer} function transfer(address _to, uint256 _amount) public virtual override returns (bool success) { // Inherit from {_transfer}. _transfer(_msgSender(), _to, _amount); // Returns true on success. return true; } // See {_transfer}, {_approve} and {ERC20Interface - transferFrom} // @notice Execution cost recommended: 87,000 gas - 90,000 gas function transferFrom( address _from, address _to, uint256 _amount ) public virtual override returns (bool success) { // Inherits from _transfer. _transfer(_from, _to, _amount); // Check sender's allowance. // NOTE - Always check balances before transaction. uint256 currentAllowance = allowed[_from][_msgSender()]; // Inherits from _approve. _approve(_from, _msgSender(), currentAllowance - _amount, currentAllowance); // Returns true on success. return true; } // See also {_approve} and {ERC20Interface - approve} function approve(address _spender, uint256 _amount) public virtual override returns (bool success) { // Inherits from _approve. _approve(_msgSender(), _spender, _amount, balances[_msgSender()]); // Returns true on success. return true; } /** * Increases total allowance to `_amount`. * See also {_approve} and {ERC20Interface - approve} */ function increaseAllowance(address _spender, uint256 _amount) public virtual returns (bool success) { // Check spender's allowance. // NOTE - Always check balances before transaction. uint256 currentAllowance = allowed[_msgSender()][_spender]; // Inherits from _approve. _approve(_msgSender(), _spender, currentAllowance + _amount, balances[_msgSender()]); // Returns true on success. return true; } /** * Decreases total allowance by `_amount`. * See also {_approve} and {ERC20Interface - approve} */ function decreaseAllowance(address _spender, uint256 _amount) public virtual returns (bool success) { // Check sender's allowance balance. // NOTE - Always check balances before transaction. uint256 currentAllowance = allowed[_msgSender()][_spender]; // Inherits from _approve. _approve(_msgSender(), _spender, currentAllowance - _amount, currentAllowance); // Returns true on success. return true; } /** * @notice See {ERC20Interface - transfer}. * @notice MUST trigger Transfer event. */ function _transfer( address _from, address _to, uint256 _amount) noneZero(_from) noneZero(_to) whenNotWhitelisted(_from) whenNotWhitelisted(_to) whenNotPaused internal virtual { // Check sender's balance. // NOTE - Always check balances before transaction. uint256 senderBalance = balances[_from]; /// @dev Requires the sender `senderBalance` balance be at least the `_amount`. require(senderBalance >= _amount, "The transfer amount exceeds balance."); // Increase recipient balance. balances[_to] += _amount; // Decrease sender balance. balances[_from] -= _amount; // See {event ERC20Interface-Transfer} emit Transfer(_from, _to, _amount); } /** * @notice See {ERC20Interface - approve} * @notice MUST trigger a Approval event. */ function _approve( address _owner, address _spender, uint256 _amount, uint256 _initialBalance) noneZero(_spender) noneZero(_owner) internal virtual { /// @dev Requires the owner `_initialBalance` balance be at least the `_amount`. require(_initialBalance >= _amount, "Not enough balance."); /// @dev Requires the `_amount` be at least 0 (zero). require(_amount >= 0, "The value is less than or zero!"); // Set spender allowance to the `_amount`. allowed[_owner][_spender] = _amount; // See {event ERC20Interface-Approval} emit Approval(_owner, _spender, _amount); } /** * @notice Increases an address balance and add to the total supply. * @notice Callable only by the founder. * @notice Callable only by a none-zero address. * @param _owner : The address to mint or add tokens to. * @param _amount : The quantity of tokens to mint or create. * @notice MUST trigger Mint event. * @return success */ function mint(address _owner, uint256 _amount) onlyFounder public virtual returns (bool success) { // Increase total supply. totalSupply += _amount; // Increase owner's balance. balances[_owner] += _amount; // See {event Mint} emit Mint(address(0), _owner, _amount); // Returns true on success. return true; } /** * @notice Decreases an address balance, and add to the total supply. * @notice Callable only by the founder. * @notice Callable only by a none-zero address. * @param _owner : The address to burn or substract tokens from. * @param _amount : The quantity of tokens to burn or destroy. * @notice MUST trigger Burn event. */ function burn(address _owner, uint256 _amount) onlyFounder public virtual returns (bool success) { // Check owner's balance. // NOTE - Always check balance first before transaction. uint256 accountBalance = balances[_owner]; /// @dev Requires the owner's balance `accountBalance` be at least `_amount`. require(accountBalance >= _amount, "Burn amount exceeds balance"); // Decrease owner total supply. balances[_owner] -= _amount; // Decrease `totalSupply` by `_amount`. totalSupply -= _amount; // See {event Burn} emit Burn(address(0), _owner, _amount); // Returns true on success. return true; } // Kills contract function selfDestruct() public onlyFounder returns (bool success) { // Decrease founder total supply to 0. balances[founder] = 0; // Decrease `totalSupply` to 0. totalSupply = 0; // Returns true on success. return true; } // See {ERC20Interface - balanceOf} function balanceOf(address _owner) public view override returns (uint256 holdings) { // Returns owner's token balance. return balances[_owner]; } // See {ERC20Interface - allowance} function allowance(address _owner, address _spender) public view virtual override returns (uint256 remaining) { // Returns spender's allowance balance. return allowed[_owner][_spender]; } } // ---------------------------------------------------------------------------- /// @title BozyICO : ERC Token ICO - 0.00001 ETH/BOZY with max-cap of 60,000 ETH // ---------------------------------------------------------------------------- contract BozyICO is Bozy { // Define public constant variables address payable public deposit; uint256 public raisedAmount; uint256 public hardCap = 6000 ether; uint256 public goal = 2000 ether; uint256 public saleStart = block.timestamp + 30 days; uint256 public saleEnd = saleStart + 90 days; uint256 public TokenTransferStart = saleEnd + 10 days; uint256 public maxContribution = 10 ether; uint256 public minContribution = 0.001 ether; uint256 public icoTokenSold; //uint256 public hardCap = 60 ether; // test //uint256 public goal = 20 ether; // test //uint256 public saleStart = block.timestamp + 30 seconds; // test //uint256 public saleEnd = saleStart + 90 seconds; // test //uint256 public TokenTransferStart = saleEnd + 60 seconds; // test /** * @param beforeStart : Returns 0 before ICO starts. * @param running : Returns 1 when ICO is running. * @param afterEnd : Returns 2 when ICO has ended. * @param halted : Returns 3 when ICO is paused. */ enum State {beforeStart, running, afterEnd, halted} State icoState; /** * @dev Triggers on any successful call to contribute(). * @param _contributor : The address donating to the ICO. * @param _amount: The quantity in ETH of the contribution. * @param _tokens : The quantity of tokens sent to the contributor. */ event Contribute(address _contributor, uint256 _amount, uint256 _tokens); /// @dev All three of these values are immutable: set on construction. constructor(address payable _deposit) { deposit = _deposit; icoState = State.beforeStart; } /// @dev Sends ETH. receive() payable external { contribute(); } /// @notice Changes the deposit address. function changeDepositAddress(address payable _newDeposit) public onlyFounder { // Change deposit address to a new one. deposit = _newDeposit; } /** * @notice Contributes to the ICO. * @notice MUST trigger Contribute event. * @notice Execution cost recommended: 37493 gas */ function contribute() payable public whenNotPaused returns (bool success) { // Set ICO state to the current state. icoState = getICOState(); /// @dev Requires the ICO to be running. require(icoState == State.running, "ICO is not running. Check ICO state."); /// @dev Requires the value be greater than min. contribution and less than max. contribution. require(_msgValue() >= minContribution && _msgValue() <= maxContribution, "Contribution out of range."); /// @dev Requires the raised amount `raisedAmount` is at least less than the `hardCap`. require(raisedAmount <= hardCap, "HardCap has been reached."); // Increase raised amount of ETH. raisedAmount += _msgValue(); // Set token amount. uint256 _tokens = (_msgValue() / tokenPrice) * (10 ** decimals); // Increase ICO token sold amount. icoTokenSold += _tokens; // Increase Contributor token holdings. balances[_msgSender()] += _tokens; // Decrease founder token holdings. balances[founder] -= _tokens; // Transfer ETH to deposit account. payable(deposit).transfer(_msgValue()); // See {event Contribute} emit Contribute(_msgSender(), _msgValue(), _tokens); // Returns true on success. return true; } /// @dev See {Bozy - transfer} /// @notice Execution cost recommended: 62164 gas function transfer(address _to, uint256 _tokens) public override returns (bool success) { /// @dev Requires the current time is greater than TokenTransferStart. require(block.timestamp >= TokenTransferStart, "Transfer starts 10 days after ICO has ended."); // Get the contract from ERC20. super.transfer(_to, _tokens); // Returns true on success. return true; } /// @dev See {Bozy - transferFrom} /// @notice Execution cost recommended: 97000 gas function transferFrom( address _from, address _to, uint256 _tokens ) public override returns (bool success) { /// @dev Requires the current time is greater than TokenTransferStart. require(block.timestamp >= TokenTransferStart, "Transfer starts 10 days after ICO has ended."); // Get the contract one level higher in the inheritance hierarchy. Bozy.transferFrom(_from, _to, _tokens); // Returns true on success. return true; } /// @notice Returns current ico states. Check {enum State} function getICOState() public view returns (State) { if(paused == true) { return State.halted; // returns 3 } else if(block.timestamp < saleStart) { return State.beforeStart; // returns 0 } else if(block.timestamp >= saleStart && block.timestamp <= saleEnd) { return State.running; // returns 1 } else { return State.afterEnd; // returns 2 } } }
See {ERC20Interface - approve} MUST trigger a Approval event./ Set spender allowance to the `_amount`. See {event ERC20Interface-Approval}
function _approve( address _owner, address _spender, uint256 _amount, uint256 _initialBalance) noneZero(_spender) noneZero(_owner) internal virtual { require(_initialBalance >= _amount, "Not enough balance."); require(_amount >= 0, "The value is less than or zero!"); allowed[_owner][_spender] = _amount; emit Approval(_owner, _spender, _amount); }
15,392,880
./full_match/137/0x97854678E04Ae9c03A109C1184A8Cbf684F6c819/sources/FractalERC1155SignatureMint.sol
Mints tokens according to the provided mint request. _req The payload / mint request. _signature The signature produced by an account signing the mint request./ Set royalties, if applicable. Set URI
function mintWithSignature(MintRequest calldata _req, bytes calldata _signature) external payable virtual override returns (address signer) { require(_req.quantity > 0, "Minting zero tokens."); uint256 tokenIdToMint; uint256 nextIdToMint = nextTokenIdToMint(); if (_req.tokenId == type(uint256).max) { tokenIdToMint = nextIdToMint; nextTokenIdToMint_ += 1; require(_req.tokenId < nextIdToMint, "invalid id"); tokenIdToMint = _req.tokenId; } require(tokenIdToMint < maxSupply, "cannot exceed max supply"); address receiver = _req.to; if (_req.royaltyRecipient != address(0)) { _setupRoyaltyInfoForToken(tokenIdToMint, _req.royaltyRecipient, _req.royaltyBps); } if (_req.tokenId == type(uint256).max) { _setTokenURI(tokenIdToMint, _req.uri); } emit TokensMintedWithSignature(signer, receiver, tokenIdToMint, _req); }
3,761,307
pragma solidity ^0.4.23; contract ERC223Interface { uint public totalSupply; uint8 public decimals; function balanceOf(address who) constant returns (uint); function transfer(address to, uint value); function transfer(address to, uint value, bytes data); event Transfer(address indexed from, address indexed to, uint value, bytes data); } contract ERC223ReceivingContract { /** * @dev Standard ERC223 function that will handle incoming token transfers. * * @param _from Token sender address. * @param _value Amount of tokens. * @param _data Transaction metadata. */ function tokenFallback(address _from, uint _value, bytes _data); } /** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */ contract Ownable { address public owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ function Ownable() public { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) public onlyOwner { require(newOwner != address(0)); emit OwnershipTransferred(owner, newOwner); owner = newOwner; } } /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { /** * @dev Multiplies two numbers, throws on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256 c) { if (a == 0) { return 0; } c = a * b; assert(c / a == b); return c; } /** * @dev Integer division of two numbers, truncating the quotient. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 // uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return a / b; } /** * @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } /** * @dev Adds two numbers, throws on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256 c) { c = a + b; assert(c >= a); return c; } } /** * @title AirDropContract * Simply do the airdrop. */ contract AirDropForERC223 is Ownable { using SafeMath for uint256; // the amount that owner wants to send each time uint public airDropAmount; // the mapping to judge whether each address has already received airDropped mapping ( address => bool ) public invalidAirDrop; // the array of addresses which received airDrop address[] public arrayAirDropReceivers; // flag to stop airdrop bool public stop = false; ERC223Interface public erc20; uint256 public startTime; uint256 public endTime; // event event LogAirDrop(address indexed receiver, uint amount); event LogStop(); event LogStart(); event LogWithdrawal(address indexed receiver, uint amount); event LogInfoUpdate(uint256 startTime, uint256 endTime, uint256 airDropAmount); /** * @dev Constructor to set _airDropAmount and _tokenAddresss. * @param _airDropAmount The amount of token that is sent for doing airDrop. * @param _tokenAddress The address of token. */ constructor(uint256 _startTime, uint256 _endTime, uint _airDropAmount, address _tokenAddress) public { require(_startTime >= now && _endTime >= _startTime && _airDropAmount > 0 && _tokenAddress != address(0) ); startTime = _startTime; endTime = _endTime; erc20 = ERC223Interface(_tokenAddress); uint tokenDecimals = erc20.decimals(); airDropAmount = _airDropAmount.mul(10 ** tokenDecimals); } /** * @dev Standard ERC223 function that will handle incoming token transfers. * * @param _from Token sender address. * @param _value Amount of tokens. * @param _data Transaction metadata. */ function tokenFallback(address _from, uint _value, bytes _data) {} /** * @dev Confirm that airDrop is available. * @return A bool to confirm that airDrop is available. */ function isValidAirDropForAll() public view returns (bool) { bool validNotStop = !stop; bool validAmount = getRemainingToken() >= airDropAmount; bool validPeriod = now >= startTime && now <= endTime; return validNotStop && validAmount && validPeriod; } /** * @dev Confirm that airDrop is available for msg.sender. * @return A bool to confirm that airDrop is available for msg.sender. */ function isValidAirDropForIndividual() public view returns (bool) { bool validNotStop = !stop; bool validAmount = getRemainingToken() >= airDropAmount; bool validPeriod = now >= startTime && now <= endTime; bool validReceiveAirDropForIndividual = !invalidAirDrop[msg.sender]; return validNotStop && validAmount && validPeriod && validReceiveAirDropForIndividual; } /** * @dev Do the airDrop to msg.sender */ function receiveAirDrop() public { require(isValidAirDropForIndividual()); // set invalidAirDrop of msg.sender to true invalidAirDrop[msg.sender] = true; // set msg.sender to the array of the airDropReceiver arrayAirDropReceivers.push(msg.sender); // execute transfer erc20.transfer(msg.sender, airDropAmount); emit LogAirDrop(msg.sender, airDropAmount); } /** * @dev Change the state of stop flag */ function toggle() public onlyOwner { stop = !stop; if (stop) { emit LogStop(); } else { emit LogStart(); } } /** * @dev Withdraw the amount of token that is remaining in this contract. * @param _address The address of EOA that can receive token from this contract. */ function withdraw(address _address) public onlyOwner { require(stop || now > endTime); require(_address != address(0)); uint tokenBalanceOfContract = getRemainingToken(); erc20.transfer(_address, tokenBalanceOfContract); emit LogWithdrawal(_address, tokenBalanceOfContract); } /** * @dev Update the information regarding to period and amount. * @param _startTime The start time this airdrop starts. * @param _endTime The end time this sirdrop ends. * @param _airDropAmount The airDrop Amount that user can get via airdrop. */ function updateInfo(uint256 _startTime, uint256 _endTime, uint256 _airDropAmount) public onlyOwner { require(stop || now > endTime); require( _startTime >= now && _endTime >= _startTime && _airDropAmount > 0 ); startTime = _startTime; endTime = _endTime; uint tokenDecimals = erc20.decimals(); airDropAmount = _airDropAmount.mul(10 ** tokenDecimals); emit LogInfoUpdate(startTime, endTime, airDropAmount); } /** * @dev Get the total number of addresses which received airDrop. * @return Uint256 the total number of addresses which received airDrop. */ function getTotalNumberOfAddressesReceivedAirDrop() public view returns (uint256) { return arrayAirDropReceivers.length; } /** * @dev Get the remaining amount of token user can receive. * @return Uint256 the amount of token that user can reveive. */ function getRemainingToken() public view returns (uint256) { return erc20.balanceOf(this); } /** * @dev Return the total amount of token user received. * @return Uint256 total amount of token user received. */ function getTotalAirDroppedAmount() public view returns (uint256) { return airDropAmount.mul(arrayAirDropReceivers.length); } }
Withdraw the amount of token that is remaining in this contract. _address The address of EOA that can receive token from this contract./
function withdraw(address _address) public onlyOwner { require(stop || now > endTime); require(_address != address(0)); uint tokenBalanceOfContract = getRemainingToken(); erc20.transfer(_address, tokenBalanceOfContract); emit LogWithdrawal(_address, tokenBalanceOfContract); }
1,546,649
// SPDX-License-Identifier: AGPL-3.0-only pragma solidity 0.7.5; import "@openzeppelin/contracts-upgradeable/math/SafeMathUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/utils/ReentrancyGuardUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/utils/CountersUpgradeable.sol"; import "./presets/OwnablePausableUpgradeable.sol"; import "./interfaces/IRewardEthToken.sol"; import "./interfaces/IPool.sol"; import "./interfaces/IOracles.sol"; import "./interfaces/IMerkleDistributor.sol"; /** * @title Oracles * * @dev Oracles contract stores accounts responsible for submitting off-chain data. * The threshold of inputs from different oracles is required to submit the data. */ contract Oracles is IOracles, ReentrancyGuardUpgradeable, OwnablePausableUpgradeable { using SafeMathUpgradeable for uint256; using CountersUpgradeable for CountersUpgradeable.Counter; bytes32 public constant ORACLE_ROLE = keccak256("ORACLE_ROLE"); // @dev Defines how often oracles submit data (in blocks). uint256 public override syncPeriod; // @dev Maps candidate ID to the number of votes it has. mapping(bytes32 => uint256) public override candidates; // @dev [Deprecated] List of supported rETH2 Uniswap pairs. address[] private rewardEthUniswapPairs; // @dev Maps vote ID to whether it was submitted or not. mapping(bytes32 => bool) private submittedVotes; // @dev Address of the RewardEthToken contract. IRewardEthToken private rewardEthToken; // @dev Nonce is used to protect from submitting the same vote several times. CountersUpgradeable.Counter private nonce; // @dev Address of the Pool contract. IPool private pool; // @dev Address of the MerkleDistributor contract. IMerkleDistributor private merkleDistributor; /** * @dev Modifier for checking whether the caller is an oracle. */ modifier onlyOracle() { require(hasRole(ORACLE_ROLE, msg.sender), "Oracles: access denied"); _; } /** * @dev See {IOracles-upgrade}. */ function upgrade(address _merkleDistributor, uint256 _syncPeriod) external override onlyAdmin whenPaused { require(address(merkleDistributor) == address(0), "Oracles: already upgraded"); merkleDistributor = IMerkleDistributor(_merkleDistributor); syncPeriod = _syncPeriod; } /** * @dev See {IOracles-hasVote}. */ function hasVote(address oracle, bytes32 candidateId) external override view returns (bool) { return submittedVotes[keccak256(abi.encode(oracle, candidateId))]; } /** * @dev See {IOracles-currentNonce}. */ function currentNonce() external override view returns (uint256) { return nonce.current(); } /** * @dev See {IOracles-isOracle}. */ function isOracle(address _account) external override view returns (bool) { return hasRole(ORACLE_ROLE, _account); } /** * @dev See {IOracles-addOracle}. */ function addOracle(address _account) external override { grantRole(ORACLE_ROLE, _account); } /** * @dev See {IOracles-removeOracle}. */ function removeOracle(address _account) external override { revokeRole(ORACLE_ROLE, _account); } /** * @dev See {IOracles-setSyncPeriod}. */ function setSyncPeriod(uint256 _syncPeriod) external override onlyAdmin { require(!isRewardsVoting(), "Oracles: cannot update during voting"); syncPeriod = _syncPeriod; emit SyncPeriodUpdated(_syncPeriod, msg.sender); } /** * @dev See {IOracles-isRewardsVoting}. */ function isRewardsVoting() public override view returns (bool) { return rewardEthToken.lastUpdateBlockNumber().add(syncPeriod) < block.number; } /** * @dev See {IOracles-isMerkleRootVoting}. */ function isMerkleRootVoting() public override view returns (bool) { uint256 lastRewardBlockNumber = rewardEthToken.lastUpdateBlockNumber(); return merkleDistributor.lastUpdateBlockNumber() < lastRewardBlockNumber && lastRewardBlockNumber < block.number; } /** * @dev See {IOracles-voteForRewards}. */ function voteForRewards( uint256 _nonce, uint256 _totalRewards, uint256 _activatedValidators ) external override onlyOracle whenNotPaused { require(_nonce == nonce.current(), "Oracles: invalid nonce"); bytes32 candidateId = keccak256(abi.encode(_nonce, _totalRewards, _activatedValidators)); bytes32 voteId = keccak256(abi.encode(msg.sender, candidateId)); require(!submittedVotes[voteId], "Oracles: already voted"); require(isRewardsVoting(), "Oracles: too early vote"); // mark vote as submitted, update candidate votes number submittedVotes[voteId] = true; uint256 candidateNewVotes = candidates[candidateId].add(1); candidates[candidateId] = candidateNewVotes; emit RewardsVoteSubmitted(msg.sender, _nonce, _totalRewards, _activatedValidators); // update only if enough votes accumulated uint256 oraclesCount = getRoleMemberCount(ORACLE_ROLE); if (candidateNewVotes.mul(3) > oraclesCount.mul(2)) { // update total rewards rewardEthToken.updateTotalRewards(_totalRewards); // update activated validators if (_activatedValidators != pool.activatedValidators()) { pool.setActivatedValidators(_activatedValidators); } // clean up votes delete submittedVotes[voteId]; for (uint256 i = 0; i < oraclesCount; i++) { address oracle = getRoleMember(ORACLE_ROLE, i); if (oracle == msg.sender) continue; delete submittedVotes[keccak256(abi.encode(oracle, candidateId))]; } // clean up candidate nonce.increment(); delete candidates[candidateId]; } } /** * @dev See {IOracles-voteForMerkleRoot}. */ function voteForMerkleRoot( uint256 _nonce, bytes32 _merkleRoot, string calldata _merkleProofs ) external override onlyOracle whenNotPaused { require(_nonce == nonce.current(), "Oracles: invalid nonce"); bytes32 candidateId = keccak256(abi.encode(_nonce, _merkleRoot, _merkleProofs)); bytes32 voteId = keccak256(abi.encode(msg.sender, candidateId)); require(!submittedVotes[voteId], "Oracles: already voted"); require(isMerkleRootVoting(), "Oracles: too early vote"); // mark vote as submitted, update candidate votes number submittedVotes[voteId] = true; uint256 candidateNewVotes = candidates[candidateId].add(1); candidates[candidateId] = candidateNewVotes; emit MerkleRootVoteSubmitted(msg.sender, _nonce, _merkleRoot, _merkleProofs); // update only if enough votes accumulated uint256 oraclesCount = getRoleMemberCount(ORACLE_ROLE); if (candidateNewVotes.mul(3) > oraclesCount.mul(2)) { // update merkle root merkleDistributor.setMerkleRoot(_merkleRoot, _merkleProofs); // clean up votes delete submittedVotes[voteId]; for (uint256 i = 0; i < oraclesCount; i++) { address oracle = getRoleMember(ORACLE_ROLE, i); if (oracle == msg.sender) continue; delete submittedVotes[keccak256(abi.encode(oracle, candidateId))]; } // clean up candidate nonce.increment(); delete candidates[candidateId]; } } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMathUpgradeable { /** * @dev Returns the addition of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b > a) return (false, 0); return (true, a - b); } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a / b); } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a % b); } /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a, "SafeMath: subtraction overflow"); return a - b; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) return 0; uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers, reverting on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: division by zero"); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: modulo by zero"); return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); return a - b; } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryDiv}. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a % b; } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "../proxy/Initializable.sol"; /** * @dev Contract module that helps prevent reentrant calls to a function. * * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier * available, which can be applied to functions to make sure there are no nested * (reentrant) calls to them. * * Note that because there is a single `nonReentrant` guard, functions marked as * `nonReentrant` may not call one another. This can be worked around by making * those functions `private`, and then adding `external` `nonReentrant` entry * points to them. * * TIP: If you would like to learn more about reentrancy and alternative ways * to protect against it, check out our blog post * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul]. */ abstract contract ReentrancyGuardUpgradeable is Initializable { // Booleans are more expensive than uint256 or any type that takes up a full // word because each write operation emits an extra SLOAD to first read the // slot's contents, replace the bits taken up by the boolean, and then write // back. This is the compiler's defense against contract upgrades and // pointer aliasing, and it cannot be disabled. // The values being non-zero value makes deployment a bit more expensive, // but in exchange the refund on every call to nonReentrant will be lower in // amount. Since refunds are capped to a percentage of the total // transaction's gas, it is best to keep them low in cases like this one, to // increase the likelihood of the full refund coming into effect. uint256 private constant _NOT_ENTERED = 1; uint256 private constant _ENTERED = 2; uint256 private _status; function __ReentrancyGuard_init() internal initializer { __ReentrancyGuard_init_unchained(); } function __ReentrancyGuard_init_unchained() internal initializer { _status = _NOT_ENTERED; } /** * @dev Prevents a contract from calling itself, directly or indirectly. * Calling a `nonReentrant` function from another `nonReentrant` * function is not supported. It is possible to prevent this from happening * by making the `nonReentrant` function external, and make it call a * `private` function that does the actual work. */ modifier nonReentrant() { // On the first call to nonReentrant, _notEntered will be true require(_status != _ENTERED, "ReentrancyGuard: reentrant call"); // Any calls to nonReentrant after this point will fail _status = _ENTERED; _; // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) _status = _NOT_ENTERED; } uint256[49] private __gap; } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "../math/SafeMathUpgradeable.sol"; /** * @title Counters * @author Matt Condon (@shrugs) * @dev Provides counters that can only be incremented or decremented by one. This can be used e.g. to track the number * of elements in a mapping, issuing ERC721 ids, or counting request ids. * * Include with `using Counters for Counters.Counter;` * Since it is not possible to overflow a 256 bit integer with increments of one, `increment` can skip the {SafeMath} * overflow check, thereby saving gas. This does assume however correct usage, in that the underlying `_value` is never * directly accessed. */ library CountersUpgradeable { using SafeMathUpgradeable for uint256; struct Counter { // This variable should never be directly accessed by users of the library: interactions must be restricted to // the library's function. As of Solidity v0.5.2, this cannot be enforced, though there is a proposal to add // this feature: see https://github.com/ethereum/solidity/issues/4637 uint256 _value; // default: 0 } function current(Counter storage counter) internal view returns (uint256) { return counter._value; } function increment(Counter storage counter) internal { // The {SafeMath} overflow check can be skipped here, see the comment at the top counter._value += 1; } function decrement(Counter storage counter) internal { counter._value = counter._value.sub(1); } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity 0.7.5; import "@openzeppelin/contracts-upgradeable/access/AccessControlUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/utils/PausableUpgradeable.sol"; import "../interfaces/IOwnablePausable.sol"; /** * @title OwnablePausableUpgradeable * * @dev Bundles Access Control, Pausable and Upgradeable contracts in one. * */ abstract contract OwnablePausableUpgradeable is IOwnablePausable, PausableUpgradeable, AccessControlUpgradeable { bytes32 public constant PAUSER_ROLE = keccak256("PAUSER_ROLE"); /** * @dev Modifier for checking whether the caller is an admin. */ modifier onlyAdmin() { require(hasRole(DEFAULT_ADMIN_ROLE, msg.sender), "OwnablePausable: access denied"); _; } /** * @dev Modifier for checking whether the caller is a pauser. */ modifier onlyPauser() { require(hasRole(PAUSER_ROLE, msg.sender), "OwnablePausable: access denied"); _; } // solhint-disable-next-line func-name-mixedcase function __OwnablePausableUpgradeable_init(address _admin) internal initializer { __Context_init_unchained(); __AccessControl_init_unchained(); __Pausable_init_unchained(); __OwnablePausableUpgradeable_init_unchained(_admin); } /** * @dev Grants `DEFAULT_ADMIN_ROLE`, `PAUSER_ROLE` to the admin account. */ // solhint-disable-next-line func-name-mixedcase function __OwnablePausableUpgradeable_init_unchained(address _admin) internal initializer { _setupRole(DEFAULT_ADMIN_ROLE, _admin); _setupRole(PAUSER_ROLE, _admin); } /** * @dev See {IOwnablePausable-isAdmin}. */ function isAdmin(address _account) external override view returns (bool) { return hasRole(DEFAULT_ADMIN_ROLE, _account); } /** * @dev See {IOwnablePausable-addAdmin}. */ function addAdmin(address _account) external override { grantRole(DEFAULT_ADMIN_ROLE, _account); } /** * @dev See {IOwnablePausable-removeAdmin}. */ function removeAdmin(address _account) external override { revokeRole(DEFAULT_ADMIN_ROLE, _account); } /** * @dev See {IOwnablePausable-isPauser}. */ function isPauser(address _account) external override view returns (bool) { return hasRole(PAUSER_ROLE, _account); } /** * @dev See {IOwnablePausable-addPauser}. */ function addPauser(address _account) external override { grantRole(PAUSER_ROLE, _account); } /** * @dev See {IOwnablePausable-removePauser}. */ function removePauser(address _account) external override { revokeRole(PAUSER_ROLE, _account); } /** * @dev See {IOwnablePausable-pause}. */ function pause() external override onlyPauser { _pause(); } /** * @dev See {IOwnablePausable-unpause}. */ function unpause() external override onlyPauser { _unpause(); } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity 0.7.5; import "@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol"; /** * @dev Interface of the RewardEthToken contract. */ interface IRewardEthToken is IERC20Upgradeable { /** * @dev Event for tracking updated maintainer. * @param maintainer - address of the new maintainer, where the fee will be paid. */ event MaintainerUpdated(address maintainer); /** * @dev Event for tracking updated maintainer fee. * @param maintainerFee - new maintainer fee. */ event MaintainerFeeUpdated(uint256 maintainerFee); /** * @dev Event for tracking whether rewards distribution through merkle distributor is enabled/disabled. * @param account - address of the account. * @param isDisabled - whether rewards distribution is disabled. */ event RewardsToggled(address indexed account, bool isDisabled); /** * @dev Structure for storing information about user reward checkpoint. * @param rewardPerToken - user reward per token. * @param reward - user reward checkpoint. */ struct Checkpoint { uint128 reward; uint128 rewardPerToken; } /** * @dev Event for tracking rewards update by oracles. * @param periodRewards - rewards since the last update. * @param totalRewards - total amount of rewards. * @param rewardPerToken - calculated reward per token for account reward calculation. */ event RewardsUpdated( uint256 periodRewards, uint256 totalRewards, uint256 rewardPerToken ); /** * @dev Function for upgrading the RewardEthToken contract. * If deploying contract for the first time, the upgrade function should be replaced with `initialize` and * contain initializations from the previous versions. * @param _merkleDistributor - address of the MerkleDistributor contract. * @param _lastUpdateBlockNumber - block number of the last rewards update. */ function upgrade(address _merkleDistributor, uint256 _lastUpdateBlockNumber) external; /** * @dev Function for getting the address of the merkle distributor. */ function merkleDistributor() external view returns (address); /** * @dev Function for getting the address of the maintainer, where the fee will be paid. */ function maintainer() external view returns (address); /** * @dev Function for changing the maintainer's address. * @param _newMaintainer - new maintainer's address. */ function setMaintainer(address _newMaintainer) external; /** * @dev Function for getting maintainer fee. The percentage fee users pay from their reward for using the pool service. */ function maintainerFee() external view returns (uint256); /** * @dev Function for changing the maintainer's fee. * @param _newMaintainerFee - new maintainer's fee. Must be less than 10000 (100.00%). */ function setMaintainerFee(uint256 _newMaintainerFee) external; /** * @dev Function for retrieving the total rewards amount. */ function totalRewards() external view returns (uint128); /** * @dev Function for retrieving the last total rewards update block number. */ function lastUpdateBlockNumber() external view returns (uint256); /** * @dev Function for retrieving current reward per token used for account reward calculation. */ function rewardPerToken() external view returns (uint128); /** * @dev Function for setting whether rewards are disabled for the account. * Can only be called by the `StakedEthToken` contract. * @param account - address of the account to disable rewards for. * @param isDisabled - whether the rewards will be disabled. */ function setRewardsDisabled(address account, bool isDisabled) external; /** * @dev Function for retrieving account's current checkpoint. * @param account - address of the account to retrieve the checkpoint for. */ function checkpoints(address account) external view returns (uint128, uint128); /** * @dev Function for checking whether account's reward will be distributed through the merkle distributor. * @param account - address of the account. */ function rewardsDisabled(address account) external view returns (bool); /** * @dev Function for updating account's reward checkpoint. * @param account - address of the account to update the reward checkpoint for. */ function updateRewardCheckpoint(address account) external returns (bool); /** * @dev Function for updating reward checkpoints for two accounts simultaneously (for gas savings). * @param account1 - address of the first account to update the reward checkpoint for. * @param account2 - address of the second account to update the reward checkpoint for. */ function updateRewardCheckpoints(address account1, address account2) external returns (bool, bool); /** * @dev Function for updating validators total rewards. * Can only be called by Oracles contract. * @param newTotalRewards - new total rewards. */ function updateTotalRewards(uint256 newTotalRewards) external; /** * @dev Function for claiming rETH2 from the merkle distribution. * Can only be called by MerkleDistributor contract. * @param account - address of the account the tokens will be assigned to. * @param amount - amount of tokens to assign to the account. */ function claim(address account, uint256 amount) external; } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity 0.7.5; pragma abicoder v2; import "./IDepositContract.sol"; /** * @dev Interface of the Pool contract. */ interface IPool { /** * @dev Event for tracking new pool withdrawal credentials. * @param withdrawalCredentials - new withdrawal credentials for the pool validators. */ event WithdrawalCredentialsUpdated(bytes32 withdrawalCredentials); /** * @dev Event for tracking registered validators. * @param publicKey - validator public key. * @param operator - address of the validator operator. */ event ValidatorRegistered(bytes publicKey, address operator); /** * @dev Event for tracking scheduled deposit activation. * @param sender - address of the deposit sender. * @param validatorIndex - index of the activated validator. * @param value - deposit amount to be activated. */ event ActivationScheduled(address indexed sender, uint256 validatorIndex, uint256 value); /** * @dev Event for tracking activated deposits. * @param account - account the deposit was activated for. * @param validatorIndex - index of the activated validator. * @param value - amount activated. * @param sender - address of the transaction sender. */ event Activated(address indexed account, uint256 validatorIndex, uint256 value, address indexed sender); /** * @dev Event for tracking activated validators updates. * @param activatedValidators - new total amount of activated validators. * @param sender - address of the transaction sender. */ event ActivatedValidatorsUpdated(uint256 activatedValidators, address sender); /** * @dev Event for tracking updates to the minimal deposit amount considered for the activation period. * @param minActivatingDeposit - new minimal deposit amount considered for the activation. * @param sender - address of the transaction sender. */ event MinActivatingDepositUpdated(uint256 minActivatingDeposit, address sender); /** * @dev Event for tracking pending validators limit. * When it's exceeded, the deposits will be set for the activation. * @param pendingValidatorsLimit - pending validators percent limit. * @param sender - address of the transaction sender. */ event PendingValidatorsLimitUpdated(uint256 pendingValidatorsLimit, address sender); /** * @dev Structure for passing information about new Validator. * @param publicKey - BLS public key of the validator, generated by the operator. * @param signature - BLS signature of the validator, generated by the operator. * @param depositDataRoot - hash tree root of the deposit data, generated by the operator. */ struct Validator { bytes publicKey; bytes signature; bytes32 depositDataRoot; } /** * @dev Function for upgrading the Pools contract. * @param _oracles - address of the Oracles contract. * @param _activatedValidators - initial amount of activated validators. * @param _pendingValidators - initial amount of pending validators. * @param _minActivatingDeposit - minimal deposit in Wei to be considered for the activation period. * @param _pendingValidatorsLimit - pending validators percent limit. If it's not exceeded tokens can be minted immediately. */ function upgrade( address _oracles, uint256 _activatedValidators, uint256 _pendingValidators, uint256 _minActivatingDeposit, uint256 _pendingValidatorsLimit ) external; /** * @dev Function for getting the total amount of pending validators. */ function pendingValidators() external view returns (uint256); /** * @dev Function for retrieving the total amount of activated validators. */ function activatedValidators() external view returns (uint256); /** * @dev Function for getting the withdrawal credentials used to * initiate pool validators withdrawal from the beacon chain. */ function withdrawalCredentials() external view returns (bytes32); /** * @dev Function for getting the minimal deposit amount considered for the activation. */ function minActivatingDeposit() external view returns (uint256); /** * @dev Function for getting the pending validators percent limit. * When it's exceeded, the deposits will be set for the activation. */ function pendingValidatorsLimit() external view returns (uint256); /** * @dev Function for getting the amount of activating deposits. * @param account - address of the account to get the amount for. * @param validatorIndex - index of the activated validator. */ function activations(address account, uint256 validatorIndex) external view returns (uint256); /** * @dev Function for setting minimal deposit amount considered for the activation period. * @param _minActivatingDeposit - new minimal deposit amount considered for the activation. */ function setMinActivatingDeposit(uint256 _minActivatingDeposit) external; /** * @dev Function for changing withdrawal credentials. * @param _withdrawalCredentials - new withdrawal credentials for the pool validators. */ function setWithdrawalCredentials(bytes32 _withdrawalCredentials) external; /** * @dev Function for changing the total amount of activated validators. * @param _activatedValidators - new total amount of activated validators. */ function setActivatedValidators(uint256 _activatedValidators) external; /** * @dev Function for changing pending validators limit. * @param _pendingValidatorsLimit - new pending validators limit. When it's exceeded, the deposits will be set for the activation. */ function setPendingValidatorsLimit(uint256 _pendingValidatorsLimit) external; /** * @dev Function for checking whether validator index can be activated. * @param _validatorIndex - index of the validator to check. */ function canActivate(uint256 _validatorIndex) external view returns (bool); /** * @dev Function for retrieving the validator registration contract address. */ function validatorRegistration() external view returns (IDepositContract); /** * @dev Function for adding deposits to the pool. */ function addDeposit() external payable; /** * @dev Function for minting account's tokens for the specific validator index. * @param _account - account address to activate the tokens for. * @param _validatorIndex - index of the activated validator. */ function activate(address _account, uint256 _validatorIndex) external; /** * @dev Function for minting account's tokens for the specific validator indexes. * @param _account - account address to activate the tokens for. * @param _validatorIndexes - list of activated validator indexes. */ function activateMultiple(address _account, uint256[] calldata _validatorIndexes) external; /** * @dev Function for registering new pool validator. * @param _validator - validator to register. */ function registerValidator(Validator calldata _validator) external; } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity 0.7.5; /** * @dev Interface of the Oracles contract. */ interface IOracles { /** * @dev Event for tracking oracle rewards votes. * @param oracle - address of the account which submitted vote. * @param nonce - current nonce. * @param totalRewards - submitted value of total rewards. * @param activatedValidators - submitted amount of activated validators. */ event RewardsVoteSubmitted( address indexed oracle, uint256 nonce, uint256 totalRewards, uint256 activatedValidators ); /** * @dev Event for tracking oracle merkle root votes. * @param oracle - address of the account which submitted vote. * @param nonce - current nonce. * @param merkleRoot - new merkle root. * @param merkleProofs - link to the merkle proofs. */ event MerkleRootVoteSubmitted( address indexed oracle, uint256 nonce, bytes32 indexed merkleRoot, string merkleProofs ); /** * @dev Event for tracking changes of oracles' sync periods. * @param syncPeriod - new sync period in blocks. * @param sender - address of the transaction sender. */ event SyncPeriodUpdated(uint256 syncPeriod, address indexed sender); /** * @dev Function for retrieving number of votes of the submission candidate. * @param _candidateId - ID of the candidate to retrieve number of votes for. */ function candidates(bytes32 _candidateId) external view returns (uint256); /** * @dev Function for retrieving oracles sync period (in blocks). */ function syncPeriod() external view returns (uint256); /** * @dev Function for upgrading the Oracles contract. * If deploying contract for the first time, the upgrade function should be replaced with `initialize` * and contain initializations from all the previous versions. * @param _merkleDistributor - address of the MerkleDistributor contract. * @param _syncPeriod - number of blocks to wait before the next sync. */ function upgrade(address _merkleDistributor, uint256 _syncPeriod) external; /** * @dev Function for checking whether an account has an oracle role. * @param _account - account to check. */ function isOracle(address _account) external view returns (bool); /** * @dev Function for checking whether an oracle has voted. * @param oracle - oracle address to check. * @param candidateId - hash of nonce and vote parameters. */ function hasVote(address oracle, bytes32 candidateId) external view returns (bool); /** * @dev Function for checking whether the oracles are currently voting for new total rewards. */ function isRewardsVoting() external view returns (bool); /** * @dev Function for checking whether the oracles are currently voting for new merkle root. */ function isMerkleRootVoting() external view returns (bool); /** * @dev Function for retrieving current nonce. */ function currentNonce() external view returns (uint256); /** * @dev Function for adding an oracle role to the account. * Can only be called by an account with an admin role. * @param _account - account to assign an oracle role to. */ function addOracle(address _account) external; /** * @dev Function for removing an oracle role from the account. * Can only be called by an account with an admin role. * @param _account - account to remove an oracle role from. */ function removeOracle(address _account) external; /** * @dev Function for updating oracles sync period. The number of blocks after they will submit the off-chain data. * Can only be called by an account with an admin role. * @param _syncPeriod - new sync period. */ function setSyncPeriod(uint256 _syncPeriod) external; /** * @dev Function for submitting oracle vote for total rewards. The last vote required for quorum will update the values. * Can only be called by an account with an oracle role. * @param _nonce - current nonce. * @param _totalRewards - voted total rewards. * @param _activatedValidators - voted amount of activated validators. */ function voteForRewards(uint256 _nonce, uint256 _totalRewards, uint256 _activatedValidators) external; /** * @dev Function for submitting oracle vote for merkle root. The last vote required for quorum will update the values. * Can only be called by an account with an oracle role. * @param _nonce - current nonce. * @param _merkleRoot - hash of the new merkle root. * @param _merkleProofs - link to the merkle proofs. */ function voteForMerkleRoot(uint256 _nonce, bytes32 _merkleRoot, string calldata _merkleProofs) external; } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity 0.7.5; import "@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol"; import "./IOracles.sol"; /** * @dev Interface of the MerkleDistributor contract. * Allows anyone to claim a token if they exist in a merkle root. */ interface IMerkleDistributor { /** * @dev Event for tracking merkle root updates. * @param sender - address of the new transaction sender. * @param merkleRoot - new merkle root hash. * @param merkleProofs - link to the merkle proofs. */ event MerkleRootUpdated( address indexed sender, bytes32 indexed merkleRoot, string merkleProofs ); /** * @dev Event for tracking SWISE token distributions. * @param sender - address of the new transaction sender. * @param token - address of the token. * @param beneficiary - address of the beneficiary, the SWISE allocation is added to. * @param amount - amount of tokens distributed. * @param startBlock - start block of the tokens distribution. * @param endBlock - end block of the tokens distribution. */ event DistributionAdded( address indexed sender, address indexed token, address indexed beneficiary, uint256 amount, uint256 startBlock, uint256 endBlock ); /** * @dev Event for tracking tokens' claims. * @param account - the address of the user that has claimed the tokens. * @param index - the index of the user that has claimed the tokens. * @param tokens - list of token addresses the user got amounts in. * @param amounts - list of user token amounts. */ event Claimed(address indexed account, uint256 index, address[] tokens, uint256[] amounts); /** * @dev Function for getting the current merkle root. */ function merkleRoot() external view returns (bytes32); /** * @dev Function for getting the RewardEthToken contract address. */ function rewardEthToken() external view returns (address); /** * @dev Function for getting the Oracles contract address. */ function oracles() external view returns (IOracles); /** * @dev Function for retrieving the last total merkle root update block number. */ function lastUpdateBlockNumber() external view returns (uint256); /** * @dev Constructor for initializing the MerkleDistributor contract. * @param _admin - address of the contract admin. * @param _rewardEthToken - address of the RewardEthToken contract. * @param _oracles - address of the Oracles contract. */ function initialize(address _admin, address _rewardEthToken, address _oracles) external; /** * @dev Function for checking the claimed bit map. * @param _merkleRoot - the merkle root hash. * @param _wordIndex - the word index of te bit map. */ function claimedBitMap(bytes32 _merkleRoot, uint256 _wordIndex) external view returns (uint256); /** * @dev Function for changing the merkle root. Can only be called by `Oracles` contract. * @param newMerkleRoot - new merkle root hash. * @param merkleProofs - URL to the merkle proofs. */ function setMerkleRoot(bytes32 newMerkleRoot, string calldata merkleProofs) external; /** * @dev Function for adding tokens distribution. * @param token - address of the token. * @param beneficiary - address of the beneficiary. * @param amount - amount of tokens to distribute. * @param durationInBlocks - duration in blocks when the token distribution should be stopped. */ function distribute( address token, address beneficiary, uint256 amount, uint256 durationInBlocks ) external; /** * @dev Function for checking whether the tokens were already claimed. * @param index - the index of the user that is part of the merkle root. */ function isClaimed(uint256 index) external view returns (bool); /** * @dev Function for claiming the given amount of tokens to the account address. * Reverts if the inputs are invalid or the oracles are currently updating the merkle root. * @param index - the index of the user that is part of the merkle root. * @param account - the address of the user that is part of the merkle root. * @param tokens - list of the token addresses. * @param amounts - list of token amounts. * @param merkleProof - an array of hashes to verify whether the user is part of the merkle root. */ function claim( uint256 index, address account, address[] calldata tokens, uint256[] calldata amounts, bytes32[] calldata merkleProof ) external; } // SPDX-License-Identifier: MIT // solhint-disable-next-line compiler-version pragma solidity >=0.4.24 <0.8.0; import "../utils/AddressUpgradeable.sol"; /** * @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed * behind a proxy. Since a proxied contract can't have a constructor, it's common to move constructor logic to an * external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer * function so it can only be called once. The {initializer} modifier provided by this contract will have this effect. * * TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as * possible by providing the encoded function call as the `_data` argument to {UpgradeableProxy-constructor}. * * CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure * that all initializers are idempotent. This is not verified automatically as constructors are by Solidity. */ abstract contract Initializable { /** * @dev Indicates that the contract has been initialized. */ bool private _initialized; /** * @dev Indicates that the contract is in the process of being initialized. */ bool private _initializing; /** * @dev Modifier to protect an initializer function from being invoked twice. */ modifier initializer() { require(_initializing || _isConstructor() || !_initialized, "Initializable: contract is already initialized"); bool isTopLevelCall = !_initializing; if (isTopLevelCall) { _initializing = true; _initialized = true; } _; if (isTopLevelCall) { _initializing = false; } } /// @dev Returns true if and only if the function is running in the constructor function _isConstructor() private view returns (bool) { return !AddressUpgradeable.isContract(address(this)); } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.2 <0.8.0; /** * @dev Collection of functions related to the address type */ library AddressUpgradeable { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: value }(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "../utils/EnumerableSetUpgradeable.sol"; import "../utils/AddressUpgradeable.sol"; import "../utils/ContextUpgradeable.sol"; import "../proxy/Initializable.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 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; } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "./ContextUpgradeable.sol"; import "../proxy/Initializable.sol"; /** * @dev Contract module which allows children to implement an emergency stop * mechanism that can be triggered by an authorized account. * * This module is used through inheritance. It will make available the * modifiers `whenNotPaused` and `whenPaused`, which can be applied to * the functions of your contract. Note that they will not be pausable by * simply including this module, only once the modifiers are put in place. */ abstract contract PausableUpgradeable is Initializable, ContextUpgradeable { /** * @dev Emitted when the pause is triggered by `account`. */ event Paused(address account); /** * @dev Emitted when the pause is lifted by `account`. */ event Unpaused(address account); bool private _paused; /** * @dev Initializes the contract in unpaused state. */ function __Pausable_init() internal initializer { __Context_init_unchained(); __Pausable_init_unchained(); } function __Pausable_init_unchained() internal initializer { _paused = false; } /** * @dev Returns true if the contract is paused, and false otherwise. */ function paused() public view virtual returns (bool) { return _paused; } /** * @dev Modifier to make a function callable only when the contract is not paused. * * Requirements: * * - The contract must not be paused. */ modifier whenNotPaused() { require(!paused(), "Pausable: paused"); _; } /** * @dev Modifier to make a function callable only when the contract is paused. * * Requirements: * * - The contract must be paused. */ modifier whenPaused() { require(paused(), "Pausable: not paused"); _; } /** * @dev Triggers stopped state. * * Requirements: * * - The contract must not be paused. */ function _pause() internal virtual whenNotPaused { _paused = true; emit Paused(_msgSender()); } /** * @dev Returns to normal state. * * Requirements: * * - The contract must be paused. */ function _unpause() internal virtual whenPaused { _paused = false; emit Unpaused(_msgSender()); } uint256[49] private __gap; } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity 0.7.5; /** * @dev Interface of the OwnablePausableUpgradeable and OwnablePausable contracts. */ interface IOwnablePausable { /** * @dev Function for checking whether an account has an admin role. * @param _account - account to check. */ function isAdmin(address _account) external view returns (bool); /** * @dev Function for assigning an admin role to the account. * Can only be called by an account with an admin role. * @param _account - account to assign an admin role to. */ function addAdmin(address _account) external; /** * @dev Function for removing an admin role from the account. * Can only be called by an account with an admin role. * @param _account - account to remove an admin role from. */ function removeAdmin(address _account) external; /** * @dev Function for checking whether an account has a pauser role. * @param _account - account to check. */ function isPauser(address _account) external view returns (bool); /** * @dev Function for adding a pauser role to the account. * Can only be called by an account with an admin role. * @param _account - account to assign a pauser role to. */ function addPauser(address _account) external; /** * @dev Function for removing a pauser role from the account. * Can only be called by an account with an admin role. * @param _account - account to remove a pauser role from. */ function removePauser(address _account) external; /** * @dev Function for pausing the contract. */ function pause() external; /** * @dev Function for unpausing the contract. */ function unpause() external; } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Library for managing * https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive * types. * * Sets have the following properties: * * - Elements are added, removed, and checked for existence in constant time * (O(1)). * - Elements are enumerated in O(n). No guarantees are made on the ordering. * * ``` * contract Example { * // Add the library methods * using EnumerableSet for EnumerableSet.AddressSet; * * // Declare a set state variable * EnumerableSet.AddressSet private mySet; * } * ``` * * As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`) * and `uint256` (`UintSet`) are supported. */ library EnumerableSetUpgradeable { // To implement this library for multiple types with as little code // repetition as possible, we write it in terms of a generic Set type with // bytes32 values. // The Set implementation uses private functions, and user-facing // implementations (such as AddressSet) are just wrappers around the // underlying Set. // This means that we can only create new EnumerableSets for types that fit // in bytes32. struct Set { // Storage of set values bytes32[] _values; // Position of the value in the `values` array, plus 1 because index 0 // means a value is not in the set. mapping (bytes32 => uint256) _indexes; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function _add(Set storage set, bytes32 value) private returns (bool) { if (!_contains(set, value)) { set._values.push(value); // The value is stored at length-1, but we add 1 to all indexes // and use 0 as a sentinel value set._indexes[value] = set._values.length; return true; } else { return false; } } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function _remove(Set storage set, bytes32 value) private returns (bool) { // We read and store the value's index to prevent multiple reads from the same storage slot uint256 valueIndex = set._indexes[value]; if (valueIndex != 0) { // Equivalent to contains(set, value) // To delete an element from the _values array in O(1), we swap the element to delete with the last one in // the array, and then remove the last element (sometimes called as 'swap and pop'). // This modifies the order of the array, as noted in {at}. uint256 toDeleteIndex = valueIndex - 1; uint256 lastIndex = set._values.length - 1; // When the value to delete is the last one, the swap operation is unnecessary. However, since this occurs // so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement. bytes32 lastvalue = set._values[lastIndex]; // Move the last value to the index where the value to delete is set._values[toDeleteIndex] = lastvalue; // Update the index for the moved value set._indexes[lastvalue] = toDeleteIndex + 1; // All indexes are 1-based // Delete the slot where the moved value was stored set._values.pop(); // Delete the index for the deleted slot delete set._indexes[value]; return true; } else { return false; } } /** * @dev Returns true if the value is in the set. O(1). */ function _contains(Set storage set, bytes32 value) private view returns (bool) { return set._indexes[value] != 0; } /** * @dev Returns the number of values on the set. O(1). */ function _length(Set storage set) private view returns (uint256) { return set._values.length; } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function _at(Set storage set, uint256 index) private view returns (bytes32) { require(set._values.length > index, "EnumerableSet: index out of bounds"); return set._values[index]; } // Bytes32Set struct Bytes32Set { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _add(set._inner, value); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _remove(set._inner, value); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) { return _contains(set._inner, value); } /** * @dev Returns the number of values in the set. O(1). */ function length(Bytes32Set storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) { return _at(set._inner, index); } // AddressSet struct AddressSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(AddressSet storage set, address value) internal returns (bool) { return _add(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(AddressSet storage set, address value) internal returns (bool) { return _remove(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(AddressSet storage set, address value) internal view returns (bool) { return _contains(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Returns the number of values in the set. O(1). */ function length(AddressSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(AddressSet storage set, uint256 index) internal view returns (address) { return address(uint160(uint256(_at(set._inner, index)))); } // UintSet struct UintSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(UintSet storage set, uint256 value) internal returns (bool) { return _add(set._inner, bytes32(value)); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(UintSet storage set, uint256 value) internal returns (bool) { return _remove(set._inner, bytes32(value)); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(UintSet storage set, uint256 value) internal view returns (bool) { return _contains(set._inner, bytes32(value)); } /** * @dev Returns the number of values on the set. O(1). */ function length(UintSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(UintSet storage set, uint256 index) internal view returns (uint256) { return uint256(_at(set._inner, index)); } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "../proxy/Initializable.sol"; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract ContextUpgradeable is Initializable { function __Context_init() internal initializer { __Context_init_unchained(); } function __Context_init_unchained() internal initializer { } function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } uint256[50] private __gap; } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20Upgradeable { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity 0.7.5; // This interface is designed to be compatible with the Vyper version. /// @notice This is the Ethereum 2.0 deposit contract interface. /// For more information see the Phase 0 specification under https://github.com/ethereum/eth2.0-specs /// https://github.com/ethereum/eth2.0-specs/blob/dev/solidity_deposit_contract/deposit_contract.sol interface IDepositContract { /// @notice A processed deposit event. event DepositEvent( bytes pubkey, bytes withdrawal_credentials, bytes amount, bytes signature, bytes index ); /// @notice Submit a Phase 0 DepositData object. /// @param pubkey A BLS12-381 public key. /// @param withdrawal_credentials Commitment to a public key for withdrawals. /// @param signature A BLS12-381 signature. /// @param deposit_data_root The SHA-256 hash of the SSZ-encoded DepositData object. /// Used as a protection against malformed input. function deposit( bytes calldata pubkey, bytes calldata withdrawal_credentials, bytes calldata signature, bytes32 deposit_data_root ) external payable; /// @notice Query the current deposit root hash. /// @return The deposit root hash. function get_deposit_root() external view returns (bytes32); /// @notice Query the current deposit count. /// @return The deposit count encoded as a little endian 64-bit number. function get_deposit_count() external view returns (bytes memory); }
See {IOracles-voteForRewards}./ mark vote as submitted, update candidate votes number update only if enough votes accumulated update total rewards update activated validators
function voteForRewards( uint256 _nonce, uint256 _totalRewards, uint256 _activatedValidators ) external override onlyOracle whenNotPaused { require(_nonce == nonce.current(), "Oracles: invalid nonce"); bytes32 candidateId = keccak256(abi.encode(_nonce, _totalRewards, _activatedValidators)); bytes32 voteId = keccak256(abi.encode(msg.sender, candidateId)); require(!submittedVotes[voteId], "Oracles: already voted"); require(isRewardsVoting(), "Oracles: too early vote"); submittedVotes[voteId] = true; uint256 candidateNewVotes = candidates[candidateId].add(1); candidates[candidateId] = candidateNewVotes; emit RewardsVoteSubmitted(msg.sender, _nonce, _totalRewards, _activatedValidators); uint256 oraclesCount = getRoleMemberCount(ORACLE_ROLE); if (candidateNewVotes.mul(3) > oraclesCount.mul(2)) { rewardEthToken.updateTotalRewards(_totalRewards); if (_activatedValidators != pool.activatedValidators()) { pool.setActivatedValidators(_activatedValidators); } for (uint256 i = 0; i < oraclesCount; i++) { address oracle = getRoleMember(ORACLE_ROLE, i); if (oracle == msg.sender) continue; delete submittedVotes[keccak256(abi.encode(oracle, candidateId))]; } delete candidates[candidateId]; } }
14,633,148
// SPDX-License-Identifier: MIT pragma solidity ^0.8.4; import "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol"; import "@openzeppelin/contracts-upgradeable/token/ERC20/ERC20Upgradeable.sol"; // The ATTRToken is the Attrace utility token. // More info: https://attrace.com // // We keep the contract upgradeable during development to make sure we can evolve and implement gas optimizations later on. // // Upgrade strategy towards DAO: // - Pre-DAO: the token is managed and improved by the Attrace project. // - When DAO is achieved: the token will become owned by the DAO contracts, or if the DAO decides to lock the token, then it can do so by transferring ownership to a contract which can't be upgraded. contract ATTRToken is ERC20Upgradeable { // Accounts which can transfer out in the pre-listing period mapping(address => bool) private _preListingAddrWL; // Timestamp when rules are disabled, once this time is reached, this is irreversible uint64 private _wlDisabledAt; // Who can modify _preListingAddrWL and _wlDisabledAt (team doing the listing). address private _wlController; // Account time lock & vesting rules mapping(address => TransferRule) public transferRules; // Emitted whenever a transfer rule is configured event TransferRuleConfigured(address addr, TransferRule rule); function initialize(address preListWlController) public initializer { __ERC20_init("Attrace", "ATTR"); _mint(msg.sender, 10 ** 27); // 1000000000000000000000000000 aces, 1,000,000,000 ATTR _wlController = address(preListWlController); _wlDisabledAt = 1624399200; // June 23 2021 } // Hook into openzeppelin's ERC20Upgradeable flow to support golive requirements function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual override { super._beforeTokenTransfer(from, to, amount); // When not yet released, verify that the sender is white-listed. if(_wlDisabledAt > block.timestamp) { require(_preListingAddrWL[from] == true, "not yet tradeable"); } // If we reach this, the token is already released and we verify the transfer rules which enforce locking and vesting. if(transferRules[from].tokens > 0) { uint lockedTokens = calcBalanceLocked(from); uint balanceUnlocked = super.balanceOf(from) - lockedTokens; require(amount <= balanceUnlocked, "transfer rule violation"); } // If we reach this, the transfer is successful. // Check if we should lock/vest the recipient of the tokens. if(transferRules[from].outboundVestingMonths > 0 || transferRules[from].outboundTimeLockMonths > 0) { // We don't support multiple rules, so recipient should not have vesting rules yet. require(transferRules[to].tokens == 0, "unsupported"); transferRules[to].timeLockMonths = transferRules[from].outboundTimeLockMonths; transferRules[to].vestingMonths = transferRules[from].outboundVestingMonths; transferRules[to].tokens = uint96(amount); transferRules[to].activationTime = uint40(block.timestamp); } } // To support listing some addresses can be allowed transfers pre-listing. function setPreReleaseAddressStatus(address addr, bool status) public { require(_wlController == msg.sender); _preListingAddrWL[addr] = status; } // Once pre-release rules are disabled, rules remain disabled // While not expected to be used, in case of need (to support optimal listing), the team can control the time the token becomes tradeable. function setNoRulesTime(uint64 disableTime) public { require(_wlController == msg.sender); // Only controller can require(_wlDisabledAt > uint64(block.timestamp)); // Can not be set anymore when rules are already disabled require(disableTime > uint64(block.timestamp)); // Has to be in the future _wlDisabledAt = disableTime; } // ---- LOCKING & VESTING RULES // The contract embeds transfer rules for project go-live and vesting. // Vesting rule describes the vesting rule a set of tokens is under since a relative time. // This is gas-optimized and doesn't require the user to do any form of release() calls. // When the periods expire, tokens will become tradeable. struct TransferRule { // The number of 30-day periods timelock this rule enforces. // This timelock starts from the rule activation time. uint16 timeLockMonths; // 2 // The number of 30-day periods vesting this rule enforces. // This period starts after the timelock period has expired. // The number of tokens released in every cycle equals rule.tokens/vestingMonths. uint16 vestingMonths; // 2 // The number of tokens managed by the rule // Eg: when ecosystem adoption sends N ATTR to an exchange, then this will have 1000 tokens. uint96 tokens; // 12 // Time when the rule went into effect // When the rule is 0, then the _wlDisabledAt time is used (time of listing). // Eg: when ecosystem adoption wallet does a transfer to an exchange, the rule will receive block.timestamp. uint40 activationTime; // 5 // Rules to apply to outbound transfers. // Eg: ecosystem adoption wallet can do transfers, but all received assets will be under locked rules. // When the recipient already has a vesting rule, the transfer will fail. // rule.activationTime and rule.tokens will be set by the transfer caller. uint16 outboundTimeLockMonths; // 2 uint16 outboundVestingMonths; // 2 } // Calculate how many tokens are still locked for a holder function calcBalanceLocked(address from) private view returns (uint) { // When no activation time is defined, the moment of listing is used. uint activationTime = (transferRules[from].activationTime == 0 ? _wlDisabledAt : transferRules[from].activationTime); // First check the time lock uint secondsLocked; if(transferRules[from].timeLockMonths > 0) { secondsLocked = (transferRules[from].timeLockMonths * (30 days)); if(activationTime+secondsLocked >= block.timestamp) { // All tokens are still locked return transferRules[from].tokens; } } // If no time lock, then calculate how much is unlocked according to the vesting rules. if(transferRules[from].vestingMonths > 0) { uint vestingStart = activationTime + secondsLocked; uint unlockedSlices = 0; for(uint i = 0; i < transferRules[from].vestingMonths; i++) { if(block.timestamp >= (vestingStart + (i * 30 days))) { unlockedSlices++; } } // If all months are vested, return 0 to ensure all tokens are sent back if(transferRules[from].vestingMonths == unlockedSlices) { return 0; } // Send back the amount of locked tokens return (transferRules[from].tokens - ((transferRules[from].tokens / transferRules[from].vestingMonths) * unlockedSlices)); } // No tokens are locked return 0; } // The contract enforces all vesting and locking rules as desribed on https://attrace.com/community/attr-token/#distribution // We don't lock tokens into another contract, we keep them allocated to the respective account, but with a locking rule on top of it. // When the last vesting rule expires, checking the vesting rules is ignored automatically and overall gas off the transfers lowers with an SLOAD cost. function setTransferRule(address addr, TransferRule calldata rule) public { require(_wlDisabledAt > uint64(block.timestamp)); // Can only be set before listing require(_wlController == msg.sender); // Only the whitelist controller can set rules before listing // Validate the rule require( // Either a rule has a token vesting/lock (rule.tokens > 0 && (rule.vestingMonths > 0 || rule.timeLockMonths > 0)) // And/or it has an outbound rule || (rule.outboundTimeLockMonths > 0 || rule.outboundVestingMonths > 0), "invalid rule"); // Store the rule // Rules are allowed to have an empty activationTime, then listing moment will be used as activation time. transferRules[addr] = rule; // Emit event that a rule was set emit TransferRuleConfigured(addr, rule); } function getLockedTokens(address addr) public view returns (uint256) { return calcBalanceLocked(addr); } // Batch route to set many rules at once function batchSetTransferRules(address[] calldata addresses, TransferRule[] calldata rules) public { require(_wlDisabledAt > uint64(block.timestamp)); // Can only be set before listing require(_wlController == msg.sender); // Only the whitelist controller can set rules before listing require(addresses.length != 0); require(addresses.length == rules.length); for(uint i = 0; i < addresses.length; i++) { setTransferRule(addresses[i], rules[i]); } } } // SPDX-License-Identifier: MIT // 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; } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./IERC20Upgradeable.sol"; import "./extensions/IERC20MetadataUpgradeable.sol"; import "../../utils/ContextUpgradeable.sol"; import "../../proxy/utils/Initializable.sol"; /** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20PresetMinterPauser}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin guidelines: functions revert instead * of returning `false` on failure. This behavior is nonetheless conventional * and does not conflict with the expectations of ERC20 applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */ contract ERC20Upgradeable is Initializable, ContextUpgradeable, IERC20Upgradeable, IERC20MetadataUpgradeable { mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; /** * @dev Sets the values for {name} and {symbol}. * * The defaut value of {decimals} is 18. To select a different value for * {decimals} you should overload it. * * All two of these values are immutable: they can only be set once during * construction. */ function __ERC20_init(string memory name_, string memory symbol_) internal initializer { __Context_init_unchained(); __ERC20_init_unchained(name_, symbol_); } function __ERC20_init_unchained(string memory name_, string memory symbol_) internal initializer { _name = name_; _symbol = symbol_; } /** * @dev Returns the name of the token. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless this function is * overridden; * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view virtual override returns (uint8) { return 18; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view virtual override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}. * * Requirements: * * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) { _transfer(sender, recipient, amount); uint256 currentAllowance = _allowances[sender][_msgSender()]; require(currentAllowance >= amount, "ERC20: transfer amount exceeds allowance"); _approve(sender, _msgSender(), currentAllowance - amount); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender] + addedValue); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { uint256 currentAllowance = _allowances[_msgSender()][spender]; require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero"); _approve(_msgSender(), spender, currentAllowance - subtractedValue); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer(address sender, address recipient, uint256 amount) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); uint256 senderBalance = _balances[sender]; require(senderBalance >= amount, "ERC20: transfer amount exceeds balance"); _balances[sender] = senderBalance - amount; _balances[recipient] += amount; emit Transfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements: * * - `to` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply += amount; _balances[account] += amount; emit Transfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); uint256 accountBalance = _balances[account]; require(accountBalance >= amount, "ERC20: burn amount exceeds balance"); _balances[account] = accountBalance - amount; _totalSupply -= amount; emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens. * * This internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve(address owner, address spender, uint256 amount) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be to transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { } uint256[45] private __gap; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20Upgradeable { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../IERC20Upgradeable.sol"; /** * @dev Interface for the optional metadata functions from the ERC20 standard. * * _Available since v4.1._ */ interface IERC20MetadataUpgradeable is IERC20Upgradeable { /** * @dev Returns the name of the token. */ function name() external view returns (string memory); /** * @dev Returns the symbol of the token. */ function symbol() external view returns (string memory); /** * @dev Returns the decimals places of the token. */ function decimals() external view returns (uint8); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../proxy/utils/Initializable.sol"; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract ContextUpgradeable is Initializable { function __Context_init() internal initializer { __Context_init_unchained(); } function __Context_init_unchained() internal initializer { } function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } uint256[50] private __gap; }
To support listing some addresses can be allowed transfers pre-listing.
function setPreReleaseAddressStatus(address addr, bool status) public { require(_wlController == msg.sender); _preListingAddrWL[addr] = status; }
14,486,903
pragma solidity ^0.5.0; // Copyright 2019 OpenST Ltd. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. import "./EIP20Interface.sol"; import "./GatewayInterface.sol"; import "./BrandedToken.sol"; /** * @title GatewayComposer contract. * * @notice GatewayComposer is a composition contract which can be used to * optimise the UX flow of the user where the user intends to perform * a single combined action. */ contract GatewayComposer { /* Struct */ struct StakeRequest { uint256 stakeVT; address gateway; address beneficiary; uint256 gasPrice; uint256 gasLimit; uint256 nonce; } /* Storage */ address public owner; /** EIP20Token value token which is staked on the value chain. */ EIP20Interface public valueToken; /** * A BrandedToken is an EIP20Token which allows a mainstream application * to create a value-backed token designed specifically for its * application's context. */ BrandedToken public brandedToken; mapping (bytes32 => StakeRequest) public stakeRequests; /** Mutex lock status. */ bool private mutexAcquired; /* Modifiers */ /** Checks that msg.sender is owner address. */ modifier onlyOwner() { require( owner == msg.sender, "Only owner can call the function." ); _; } /** * Checks that mutex is acquired or not. If mutex is not acquired, * mutexAcquired is set to true. At the end of function execution, * mutexAcquired is set to false. */ modifier mutex() { require( !mutexAcquired, "Mutex is already acquired." ); mutexAcquired = true; _; mutexAcquired = false; } /* Special Functions */ /** * @notice Contract constructor. * * @dev Function requires: * - owner address should not be zero * - ValueToken address should not be zero * - BrandedToken address should not be zero * - ValueToken address should not be equal to owner address * - BrandedToken address should not be equal to owner address * - ValueToken address should be equal to BrandedToken.valueToken() * * @param _owner Address of the staker on the value chain. * @param _valueToken EIP20Token which is staked. * @param _brandedToken It's a value backed minted EIP20Token. */ constructor( address _owner, EIP20Interface _valueToken, BrandedToken _brandedToken ) public { require( _owner != address(0), "Owner address is zero." ); require( address(_valueToken) != address(0), "ValueToken address is zero." ); require( address(_brandedToken) != address(0), "BrandedToken address is zero." ); require( _owner != address(_valueToken), "ValueToken address is same as owner address." ); require( _owner != address(_brandedToken), "BrandedToken address is same as owner address." ); require( address(_valueToken) == address(_brandedToken.valueToken()), "ValueToken should match BrandedToken.valueToken." ); owner = _owner; valueToken = _valueToken; brandedToken = _brandedToken; } /* External Functions */ /** * @notice Transfers value tokens from msg.sender to itself after staker * approves GatewayComposer, approves BrandedToken for value tokens * and calls BrandedToken.requestStake function. * * @dev Function requires: * - stakeVT can't be 0 * - mintBT amount and converted stakeVT amount should be equal * - gateway address can't be zero * - Gateway address should not be equal to owner address * - beneficiary address can't be zero * - successful execution of ValueToken transfer * - successful execution of ValueToken approve * * stakeVT can't be 0 because gateway.stake also doesn't allow 0 stake * amount. This condition also helps in validation of in progress * stake requests. See acceptStakeRequest for details. * * mintBT is not stored in StakeRequest struct as there was * significant gas cost difference between storage vs dynamic * evaluation from BrandedToken convert function. * * @param _stakeVT ValueToken amount which is staked. * @param _mintBT Amount of BrandedToken amount which will be minted. * @param _gateway Gateway contract address. * @param _beneficiary The address in the auxiliary chain where the utility * tokens will be minted. * @param _gasPrice Gas price that staker is ready to pay to get the stake * and mint process done. * @param _gasLimit Gas limit that staker is ready to pay. * @param _nonce Nonce of the staker address. It can be obtained from * Gateway.getNonce() method. * * @return stakeRequestHash_ Hash unique for each stake request. */ function requestStake( uint256 _stakeVT, uint256 _mintBT, address _gateway, address _beneficiary, uint256 _gasPrice, uint256 _gasLimit, uint256 _nonce ) external onlyOwner mutex returns (bytes32 stakeRequestHash_) { require( _stakeVT > uint256(0), "Stake amount is zero." ); require( _mintBT == brandedToken.convertToBrandedTokens(_stakeVT), "_mintBT should match converted _stakeVT." ); require( _gateway != address(0), "Gateway address is zero." ); require( owner != _gateway, "Gateway address is same as owner address." ); require( _beneficiary != address(0), "Beneficiary address is zero." ); require( valueToken.transferFrom(msg.sender, address(this), _stakeVT), "ValueToken transferFrom returned false." ); require( valueToken.approve(address(brandedToken), _stakeVT), "ValueToken approve returned false." ); stakeRequestHash_ = brandedToken.requestStake(_stakeVT, _mintBT); // mintBT is not stored because that uses significantly more gas than recalculation stakeRequests[stakeRequestHash_] = StakeRequest({ stakeVT: _stakeVT, gateway: _gateway, beneficiary: _beneficiary, gasPrice: _gasPrice, gasLimit: _gasLimit, nonce: _nonce }); } /** * @notice Approves Gateway for the minted BTs, calls Gateway.stake after * BrandedToken.acceptStakeRequest execution is successful. * * @dev Function requires: * - stake request hash is valid * - successful execution of ValueToken transferFrom * - successful execution of ValueToken approve * - BrandedToken.acceptStakeRequest execution is successful * - successful execution of BrandedToken approve * * As per requirement bounty token currency is same as valueToken. * Bounty flow: * - facilitator approves GatewayComposer for base tokens as bounty * - GatewayComposer approves Gateway for the bounty * * @param _stakeRequestHash Unique hash for each stake request. * @param _r R of the signature. * @param _s S of the signature. * @param _v V of the signature. * @param _hashLock Hash lock provided by the facilitator. * * @return messageHash_ Message hash unique for each stake request. */ function acceptStakeRequest( bytes32 _stakeRequestHash, bytes32 _r, bytes32 _s, uint8 _v, bytes32 _hashLock ) external returns (bytes32 messageHash_) { StakeRequest memory stakeRequest = stakeRequests[_stakeRequestHash]; delete stakeRequests[_stakeRequestHash]; require( stakeRequest.stakeVT > uint256(0), "Stake request not found." ); uint256 bounty = GatewayInterface(stakeRequest.gateway).bounty(); require( valueToken.transferFrom(msg.sender, address(this), bounty), "ValueToken transferFrom returned false." ); require( valueToken.approve(stakeRequest.gateway, bounty), "ValueToken approve returned false." ); require( brandedToken.acceptStakeRequest( _stakeRequestHash, _r, _s, _v ), "BrandedToken acceptStakeRequest returned false." ); // mintBT is recalculated because that uses significantly less gas than storage uint256 mintBT = brandedToken.convertToBrandedTokens( stakeRequest.stakeVT ); require( brandedToken.approve(stakeRequest.gateway, mintBT), "BrandedToken approve returned false." ); messageHash_ = GatewayInterface(stakeRequest.gateway).stake( mintBT, stakeRequest.beneficiary, stakeRequest.gasPrice, stakeRequest.gasLimit, stakeRequest.nonce, _hashLock ); } /** * @notice Revokes stake request by calling BrandedToken.revokeStakeRequest() * and deleting information. * * @dev Function requires: * - stake request hash is valid * - BrandedToken.revokeStakeRequest() should return true * - ValueToken.transfer() should return true * * The method is called after calling requestStake. In this flow * locked ValueToken is transferred to owner. Transfer is done for * convenience. This way extra step of calling transferToken is * avoided. * * @param _stakeRequestHash Stake request hash. * * @return success_ True on successful execution. */ function revokeStakeRequest( bytes32 _stakeRequestHash ) external onlyOwner returns (bool success_) { StakeRequest memory stakeRequest = stakeRequests[_stakeRequestHash]; delete stakeRequests[_stakeRequestHash]; require( stakeRequest.stakeVT > uint256(0), "Stake request not found." ); require( brandedToken.revokeStakeRequest(_stakeRequestHash), "BrandedToken revokeStakeRequest returned false." ); require( valueToken.transfer(owner, stakeRequest.stakeVT), "ValueToken transfer returned false." ); success_ = true; } /** * @notice Transfers EIP20 token to destination address. * * @dev Function requires: * - msg.sender should be owner * - EIP20 token address should not be zero * - token.transfer() execution should be successful * * @param _token EIP20 token address. * @param _to Address to which tokens are transferred. * @param _value Amount of tokens to be transferred. * * @return success_ True on successful execution. */ function transferToken( EIP20Interface _token, address _to, uint256 _value ) external onlyOwner returns (bool success_) { require( address(_token) != address(0), "EIP20 token address is zero." ); require( _token.transfer(_to, _value), "EIP20Token transfer returned false." ); success_ = true; } /** * @notice Approves EIP20 token to spender address. * * @dev Function requires: * - msg.sender should be owner * - EIP20 token address should not be zero * - token.approve() execution should be successful * * @param _token EIP20 token address. * @param _spender Address authorized to spend from the function caller's * address. * @param _value Amount up to which spender is authorized to spend. * * @return success_ True on successful execution. */ function approveToken( EIP20Interface _token, address _spender, uint256 _value ) external onlyOwner returns (bool success_) { require( address(_token) != address(0), "EIP20 token address is zero." ); require( _token.approve(_spender, _value), "EIP20token approve returned false." ); success_ = true; } /** * @notice Remove storage & code from blockchain. * * @dev Function requires: * - ValueToken balance should be 0 * - BrandedToken balance should be 0 * - There should not be any in progress stake requests * * BrandedToken contract has mapping stakeRequestHashes which stores * staker vs stakeRequestHash data. In progress stake requests are * validated by doing lookup into the stakeRequestHashes mapping. */ function destroy() external onlyOwner { require( valueToken.balanceOf(address(this)) == 0, "ValueToken balance should be 0." ); require( brandedToken.balanceOf(address(this)) == 0, "BrandedToken balance should be 0." ); require( brandedToken.stakeRequestHashes(address(this)) == bytes32(0), "In progress stake requests are present." ); selfdestruct(msg.sender); } /** * @notice Transfers value tokens to itself to pay the revert penalty, * approves Gateway to transfer the value tokens for the penalty, * and calls Gateway.revertStake. * * @dev Function requires: * - msg.sender is owner * - Gateway address can't be zero * - Gateway address should not be equal to owner address * - successful execution of ValueToken transferFrom * - successful execution of ValueToken approve * * As per requirement, penalty is paid in valueToken. * Penalty flow: * - staker approves GatewayComposer for value tokens as penalty * - GatewayComposer approves Gateway for the penalty * * @param _gateway Gateway contract address. * @param _penalty Amount to pay to revert stake. * @param _messageHash Message hash unique for each stake request. * * @return success_ True on successful execution. */ function revertStake( address _gateway, uint256 _penalty, bytes32 _messageHash ) external onlyOwner returns (bool success_) { require( _gateway != address(0), "Gateway address is zero." ); require( owner != _gateway, "Gateway address is same as owner address." ); require( valueToken.transferFrom(msg.sender, address(this), _penalty), "ValueToken transferFrom returned false." ); require( valueToken.approve(_gateway, _penalty), "ValueToken approve returned false." ); GatewayInterface(_gateway).revertStake(_messageHash); return true; } }
Transfers EIP20 token to destination address. Function requires: - msg.sender should be owner - EIP20 token address should not be zero - token.transfer() execution should be successful _token EIP20 token address. _to Address to which tokens are transferred. _value Amount of tokens to be transferred. return success_ True on successful execution./
function transferToken( EIP20Interface _token, address _to, uint256 _value ) external onlyOwner returns (bool success_) { require( address(_token) != address(0), "EIP20 token address is zero." ); require( _token.transfer(_to, _value), "EIP20Token transfer returned false." ); success_ = true; }
1,089,401
pragma solidity 0.5.4; /** * @title interface of ERC 20 token * */ interface IERC20 { function transfer(address to, uint256 value) external returns (bool); function approve(address spender, uint256 value) external returns (bool); function transferFrom(address from, address to, uint256 value) external returns (bool); function totalSupply() external view returns (uint256); function balanceOf(address who) external view returns (uint256); function allowance(address owner, address spender) external view returns (uint256); event Transfer(address indexed from, address indexed to, uint256 value); event Approval(address indexed owner, address indexed spender, uint256 value); } /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure. * To use this library you can add a `using SafeERC20 for ERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using SafeMath for uint256; function safeTransfer(IERC20 token, address to, uint256 value) internal { require(token.transfer(to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal { require(token.transferFrom(from, to, value)); } function safeApprove(IERC20 token, address spender, uint256 value) internal { require((value == 0) || (token.allowance(msg.sender, spender) == 0)); require(token.approve(spender, value)); } function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).add(value); require(token.approve(spender, newAllowance)); } function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).sub(value); require(token.approve(spender, newAllowance)); } } /** * @title SafeMath * @dev Unsigned math operations with safety checks that revert on error */ library SafeMath { /** * @dev Multiplies two unsigned integers, reverts on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b); return c; } /** * @dev Integer division of two unsigned integers truncating the quotient, reverts on division by zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0); uint256 c = a / b; return c; } /** * @dev Subtracts two unsigned integers, reverts on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a); uint256 c = a - b; return c; } /** * @dev Adds two unsigned integers, reverts on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a); return c; } /** * @dev Divides two unsigned integers and returns the remainder (unsigned integer modulo), * reverts when dividing by zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b != 0); return a % b; } } /** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */ contract Ownable { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ constructor () internal { _owner = msg.sender; emit OwnershipTransferred(address(0), _owner); } /** * @return the address of the owner. */ function owner() public view returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(isOwner()); _; } /** * @return true if `msg.sender` is the owner of the contract. */ function isOwner() public view returns (bool) { return msg.sender == _owner; } /** * @dev Allows the current owner to relinquish control of the contract. * @notice Warning!!!! only be used when owner address is compromised */ function renounceOwnership() public onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) public onlyOwner { _transferOwnership(newOwner); } /** * @dev Transfers control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function _transferOwnership(address newOwner) internal { require(newOwner != address(0)); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } /** * @title Vesting token for specific period */ contract TokenVesting is Ownable{ using SafeMath for uint256; using SafeERC20 for IERC20; struct VestedToken{ uint256 cliff; uint256 start; uint256 duration; uint256 releasedToken; uint256 totalToken; bool revoked; } mapping (address => VestedToken) public vestedUser; // default Vesting parameter values uint256 private _cliff = 2592000; // 30 days period uint256 private _duration = 93312000; // for 3 years bool private _revoked = false; IERC20 public LCXToken; event TokenReleased(address indexed account, uint256 amount); event VestingRevoked(address indexed account); /** * @dev Its a modifier in which we authenticate the caller is owner or LCXToken Smart Contract */ modifier onlyLCXTokenAndOwner() { require(msg.sender==owner() || msg.sender == address(LCXToken)); _; } /** * @dev First we have to set token address before doing any thing * @param token LCX Smart contract Address */ function setTokenAddress(IERC20 token) public onlyOwner returns(bool){ LCXToken = token; return true; } /** * @dev this will set the beneficiary with default vesting * parameters ie, every month for 3 years * @param account address of the beneficiary for vesting * @param amount totalToken to be vested */ function setDefaultVesting(address account, uint256 amount) public onlyLCXTokenAndOwner returns(bool){ _setDefaultVesting(account, amount); return true; } /** *@dev Internal function to set default vesting parameters */ function _setDefaultVesting(address account, uint256 amount) internal { require(account!=address(0)); VestedToken storage vested = vestedUser[account]; vested.cliff = _cliff; vested.start = block.timestamp; vested.duration = _duration; vested.totalToken = amount; vested.releasedToken = 0; vested.revoked = _revoked; } /** * @dev this will set the beneficiary with vesting * parameters provided * @param account address of the beneficiary for vesting * @param amount totalToken to be vested * @param cliff In seconds of one period in vesting * @param duration In seconds of total vesting * @param startAt UNIX timestamp in seconds from where vesting will start */ function setVesting(address account, uint256 amount, uint256 cliff, uint256 duration, uint256 startAt ) public onlyLCXTokenAndOwner returns(bool){ _setVesting(account, amount, cliff, duration, startAt); return true; } /** * @dev Internal function to set default vesting parameters * @param account address of the beneficiary for vesting * @param amount totalToken to be vested * @param cliff In seconds of one period in vestin * @param duration In seconds of total vesting duration * @param startAt UNIX timestamp in seconds from where vesting will start * */ function _setVesting(address account, uint256 amount, uint256 cliff, uint256 duration, uint256 startAt) internal { require(account!=address(0)); require(cliff<=duration); VestedToken storage vested = vestedUser[account]; vested.cliff = cliff; vested.start = startAt; vested.duration = duration; vested.totalToken = amount; vested.releasedToken = 0; vested.revoked = false; } /** * @notice Transfers vested tokens to beneficiary. * anyone can release their token */ function releaseMyToken() public returns(bool) { releaseToken(msg.sender); return true; } /** * @notice Transfers vested tokens to the given account. * @param account address of the vested user */ function releaseToken(address account) public { require(account != address(0)); VestedToken storage vested = vestedUser[account]; uint256 unreleasedToken = _releasableAmount(account); // total releasable token currently require(unreleasedToken>0); vested.releasedToken = vested.releasedToken.add(unreleasedToken); LCXToken.safeTransfer(account,unreleasedToken); emit TokenReleased(account, unreleasedToken); } /** * @dev Calculates the amount that has already vested but hasn't been released yet. * @param account address of user */ function _releasableAmount(address account) internal view returns (uint256) { return _vestedAmount(account).sub(vestedUser[account].releasedToken); } /** * @dev Calculates the amount that has already vested. * @param account address of the user */ function _vestedAmount(address account) internal view returns (uint256) { VestedToken storage vested = vestedUser[account]; uint256 totalToken = vested.totalToken; if(block.timestamp < vested.start.add(vested.cliff)){ return 0; }else if(block.timestamp >= vested.start.add(vested.duration) || vested.revoked){ return totalToken; }else{ uint256 numberOfPeriods = (block.timestamp.sub(vested.start)).div(vested.cliff); return totalToken.mul(numberOfPeriods.mul(vested.cliff)).div(vested.duration); } } /** * @notice Allows the owner to revoke the vesting. Tokens already vested * remain in the contract, the rest are returned to the owner. * @param account address in which the vesting is revoked */ function revoke(address account) public onlyOwner { VestedToken storage vested = vestedUser[account]; require(!vested.revoked); uint256 balance = vested.totalToken; uint256 unreleased = _releasableAmount(account); uint256 refund = balance.sub(unreleased); vested.revoked = true; vested.totalToken = unreleased; LCXToken.safeTransfer(owner(), refund); emit VestingRevoked(account); } } contract lcxToken is IERC20, Ownable{ using SafeMath for uint256; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowed; uint256 private _totalSupply; TokenVesting public vestingContractAddress; /** * @dev name, symbol and decimals of LCX Token */ string public constant name = 'LCX'; string public constant symbol = 'LCX'; uint256 public constant decimals = 18; /** * @dev Initializes the totalSupply of the token with decimal point 18 */ constructor(uint256 totalSupply) public{ _totalSupply = totalSupply.mul(10**decimals); _balances[msg.sender] = _totalSupply; emit Transfer(address(0), msg.sender, _totalSupply); } /** * @dev Total number of tokens in existence */ function totalSupply() public view returns (uint256) { return _totalSupply; } /** * @dev Gets the balance of the specified address. * @param owner The address to query the balance of. * @return An uint256 representing the amount owned by the passed address. */ function balanceOf(address owner) public view returns (uint256) { return _balances[owner]; } /** * @dev Function to check the amount of tokens that an owner allowed to a spender. * @param owner address The address which owns the funds. * @param spender address The address which will spend the funds. * @return A uint256 specifying the amount of tokens still available for the spender. */ function allowance(address owner, address spender) public view returns (uint256) { return _allowed[owner][spender]; } /** * @dev Transfer token for a specified address * @param to The address to transfer to. * @param value The amount to be transferred. */ function transfer(address to, uint256 value) public returns (bool) { _transfer(msg.sender, to, value); return true; } /** * @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) { _approve(msg.sender, spender, value); return true; } /** * @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) { _transfer(from, to, value); _approve(from, msg.sender, _allowed[from][msg.sender].sub(value)); return true; } /** * @param spender The address which will spend the funds. * @param addedValue The amount of tokens to increase the allowance by. */ function increaseAllowance(address spender, uint256 addedValue) public returns (bool) { _approve(msg.sender, spender, _allowed[msg.sender][spender].add(addedValue)); return true; } /** * @param spender The address which will spend the funds. * @param subtractedValue The amount of tokens to decrease the allowance by. */ function decreaseAllowance(address spender, uint256 subtractedValue) public returns (bool) { _approve(msg.sender, spender, _allowed[msg.sender][spender].sub(subtractedValue)); return true; } /** * @dev Burns a specific amount of tokens. * @param value The amount of token to be burned. */ function burn(uint256 value) public { _burn(msg.sender, value); } /** * @dev Burns a specific amount of tokens from the target address and decrements allowance * @param from address The account whose tokens will be burned. * @param value uint256 The amount of token to be burned. */ function burnFrom(address from, uint256 value) public { _burnFrom(from, value); } /** * @dev Transfer token for a specified addresses * @param from The address to transfer from. * @param to The address to transfer to. * @param value The amount to be transferred. */ function _transfer(address from, address to, uint256 value) internal { require(to != address(0)); _balances[from] = _balances[from].sub(value); _balances[to] = _balances[to].add(value); emit Transfer(from, to, value); } /** * @param account The account whose tokens will be burnt. * @param value The amount that will be burnt. */ function _burn(address account, uint256 value) internal { require(account != address(0)); _totalSupply = _totalSupply.sub(value); _balances[account] = _balances[account].sub(value); emit Transfer(account, address(0), value); } /** * @param owner The address that owns the tokens. * @param spender The address that will spend the tokens. * @param value The number of tokens that can be spent. */ function _approve(address owner, address spender, uint256 value) internal { require(spender != address(0)); require(owner != address(0)); _allowed[owner][spender] = value; emit Approval(owner, spender, value); } /** * @param account The account whose tokens will be burnt. * @param value The amount that will be burnt. */ function _burnFrom(address account, uint256 value) internal { _burn(account, value); _approve(account, msg.sender, _allowed[account][msg.sender].sub(value)); } /** * @dev Set Vesting Token Smart contract Address before starting vesting * @param tokenVestingAddress Smart conract Address of the Vesting Smart contract */ function setTokenVestingAddress(TokenVesting tokenVestingAddress) public onlyOwner returns(bool){ vestingContractAddress = tokenVestingAddress; return true; } /** * @dev Vesting users token by default parameters * @param account address of the user * @param amount the amount to be vested */ function setDefaultVestingToken(address account, uint256 amount) public onlyOwner returns(bool){ vestingContractAddress.setDefaultVesting(account, amount); _transfer(msg.sender,address(vestingContractAddress), amount); return true; } /** * @dev Vesting users token by given parameters * @param account address of the beneficiary for vesting * @param amount totalToken to be vested * @param cliff In seconds of one period in vestin * @param duration In seconds of total vesting duration * @param startAt UNIX timestamp in seconds from where vesting will start */ function setVestingToken(address account, uint256 amount, uint256 cliff, uint256 duration, uint256 startAt) public onlyOwner returns(bool){ vestingContractAddress.setVesting(account, amount, cliff, duration, startAt); _transfer(msg.sender ,address(vestingContractAddress), amount); return true; } /** * @dev Batch Transfer Transactions * @param accounts array of addresses * @param values array of values to be transfer */ function batchTransfer(address[] memory accounts, uint256[] memory values ) public onlyOwner returns(bool){ require(accounts.length == values.length); for(uint256 i=0;i< accounts.length;i++){ _transfer(msg.sender, accounts[i], values[i]); } return true; } }
Allows the owner to revoke the vesting. Tokens already vested remain in the contract, the rest are returned to the owner. account address in which the vesting is revoked/
function revoke(address account) public onlyOwner { VestedToken storage vested = vestedUser[account]; require(!vested.revoked); uint256 balance = vested.totalToken; uint256 unreleased = _releasableAmount(account); uint256 refund = balance.sub(unreleased); vested.revoked = true; vested.totalToken = unreleased; LCXToken.safeTransfer(owner(), refund); emit VestingRevoked(account); }
12,543,129
pragma solidity ^0.4.18; import './StudyLog.sol'; contract StudyData { /* Codes about Authority and SuperUser */ address public SuperUser; address public Owner; address public LogContract; StudyLog log = StudyLog(LogContract); struct Manager { uint ManagerID; address ManagerAddr; } mapping (uint => Manager) private managers; //ManagerID => Manager mapping (address => bool) private managerTag; uint[] private ManagerList; //storage ManagerID /* Things about Data Structure */ struct Course { uint CourseID; string CourseName; bool Compulsory; //课程属性,是否必修 uint Term; //学期号,筛选课程成绩时使用 uint Credit; uint[] Percentage; //课程的成绩组成 uint[] cStuIDs; //CourseID => StudentID[], 已选该课程的学生号集合 } /* Indexs */ mapping (uint => Course) private courses; //CourseID => Course uint[] private CourseList; enum LearningProgress { NotStart, Start, PreviewStart, PreviewEnd, Test, NotPass, Pass } struct Stu_Course { uint CourseID; uint[] TestGrade; uint CourseGrade; LearningProgress Lp; } struct Student { uint StudentID; string StudentName; uint StudentClass; address StudentAddr; uint[] sCourseIDs; //StudentID => CourseID[], index of "courses that student takes" uint[] sTermCourseIDs; //学生某学期选中的所有课程的的集合 mapping (uint => Stu_Course) stu_courses; //CourseID => Course, Coureses that student takes. mapping (uint => uint) stu_choose_course_timestamp; } /* Indexs */ mapping (uint => Student) private students; //StudentID => Student mapping (address => bool) private studentTag; uint[] private StudentList; mapping (uint => uint[]) private class_stu; //StudentClass => StudentID[] struct Tch_Course { uint CourseID; } struct Teacher { uint TeacherID; string TeacherName; address TeacherAddr; uint[] tCourseIDs; mapping (uint => Tch_Course) tch_courses; } mapping (uint => Teacher) private teachers; mapping (address => bool) private teacherTag; uint[] private TeacherList; /* Function Codes */ function StudyData () public { Owner = msg.sender; SuperUser = msg.sender; } /* Functions for debug */ function get_StudentList() onlyManager public view returns (uint[]) { uint[] memory list = StudentList; return list; } function get_TeacherList() onlyManager public view returns (uint[]) { uint[] memory list = TeacherList; return list; } function get_ManagerList() onlyManager public view returns (uint[]) { uint[] memory list = ManagerList; return list; } function get_CourseList() onlyManager public view returns (uint[]) { uint[] memory list = CourseList; return list; } /* function get_ClassStuIDs(uint _ClassID) onlyManager public view returns (uint[]) { uint[] memory list = class_stu[_ClassID]; return list; } function get_Student(uint _StudentID) onlyManager public view returns (uint StudentID, string StudentName, uint StudentClass, address StudentAddr, uint[] sCourseIDs, uint[] sTermCourseIDs) { Student storage si = students[_StudentID]; uint[] memory a = si.sCourseIDs; uint[] memory b = si.sTermCourseIDs; StudentID = si.StudentID; StudentName = si.StudentName; StudentClass = si.StudentClass; StudentAddr = si.StudentAddr; sCourseIDs = a; sTermCourseIDs = b; } function get_SC(uint _StudentID, uint _CourseID) onlyManager public view returns(uint CourseID, uint[] TestGrade, uint CourseGrade, LearningProgress Lp) { Stu_Course storage sci = students[_StudentID].stu_courses[_CourseID]; uint[] memory result = sci.TestGrade; CourseID = sci.CourseID; TestGrade = result; CourseGrade = sci.CourseGrade; Lp = sci.Lp; } function get_Course(uint _CourseID) onlyManager public view returns(uint CourseID, string CourseName, bool Compulsory, uint Term, uint Credit, uint[] Percentage, uint[] cStuIDs) { Course storage ci = courses[_CourseID]; uint[] memory a = ci.Percentage; uint[] memory b = ci.cStuIDs; CourseID = ci.CourseID; CourseName = ci.CourseName; Compulsory = ci.Compulsory; Term = ci.Term; Credit = ci.Credit; Percentage = a; cStuIDs = b; } function get_Teacher(uint _TeacherID) onlyManager public view returns(uint TeacherID, string TeacherName, address TeacherAddr, uint[] tCourseIDs) { Teacher storage ti = teachers[_TeacherID]; uint[] memory a = ti.tCourseIDs; TeacherID = ti.TeacherID; TeacherName = ti.TeacherName; TeacherAddr = ti.TeacherAddr; tCourseIDs = a; } function get_Manager(uint _ManagerID) onlyManager public view returns(uint ManagerID, address ManagerAddr) { Manager storage mi = managers[_ManagerID]; ManagerID = mi.ManagerID; ManagerAddr = mi.ManagerAddr; } */ /* currently not used debug function */ /* function get_cStuIDs(uint _CourseID) public view returns(uint[]) { uint[] memory result = courses[_CourseID].cStuIDs; return result; } function get_cPercentage(uint _CourseID) public view returns(uint[]) { uint[] memory result = courses[_CourseID].Percentage; return result; } function get_scTestGrade(uint _StudentID, uint _CourseID) public view returns(uint[]) { uint[] memory result = students[_StudentID].stu_courses[_CourseID].TestGrade; return result; } function get_sCourseIDs(uint _StudentID) public view returns(uint[]) { uint[] memory result = students[_StudentID].sCourseIDs; return result; } */ // set the address of SuperUser contract event SetSuperUser(address newSuperUser); function setSuperUser (address _SuperUser) onlyOwner public returns(bool) { SuperUser = _SuperUser; SetSuperUser(_SuperUser); return true; } uint8 private safeNumberForOwner = 0; event TransferOwnerShip(address newOwner); function transferOwnerShip(address _newOwner) onlyOwner public returns(bool) { //Have to call this func for 3 times to change Owner. if (safeNumberForOwner < 3) { safeNumberForOwner += 1; return false; } else { Owner = _newOwner; safeNumberForOwner = 0; TransferOwnerShip(_newOwner); return true; } } function get_safeNumberForOwner() onlyOwner public view returns(uint8) { return safeNumberForOwner; } /* event SetOwner(address newOwner); function setOwner(address _newOwner) onlySuperUser public returns(bool) { Owner = _newOwner; SetOwner(_newOwner); return true; } */ event SetLogAddress(address newLogContract); function setLogAddress(address _LogContract) onlyOwner public returns(bool) { LogContract = _LogContract; log = StudyLog(_LogContract); SetLogAddress(_LogContract); return true; } /* Modifiers */ modifier onlyOwner { if (msg.sender != Owner) revert(); _; } modifier onlySuperUser { if (msg.sender != SuperUser) revert(); _; } modifier onlyManager { if (msg.sender != SuperUser) { if (managerTag[msg.sender] != true) revert(); } _; } modifier onlyManagerAbove { if (managerTag[msg.sender] != true && msg.sender != SuperUser && msg.sender != Owner) revert(); _; } modifier onlyStudent { if (msg.sender != SuperUser) { if (studentTag[msg.sender] != true) revert(); } _; } modifier onlyTeacher { if (msg.sender != SuperUser) { if (teacherTag[msg.sender] != true) revert(); } _; } modifier onlyCourseTeacher (uint _TeacherID, uint _CourseID) { if (msg.sender != SuperUser) { bool Authenticated = false; for (uint i = 0; i < teachers[_TeacherID].tCourseIDs.length; i++) { if (teachers[_TeacherID].tCourseIDs[i] == _CourseID) { Authenticated = true; break; } } if (!Authenticated) revert(); } _; } modifier onlySelfStudent (uint _StudentID) { if (msg.sender != SuperUser) { if (studentTag[msg.sender] != true || students[_StudentID].StudentAddr != msg.sender) revert(); } _; } modifier onlyUser { if (msg.sender != SuperUser) { if (studentTag[msg.sender] != true && managerTag[msg.sender] != true && teacherTag[msg.sender] != true) revert(); } _; } modifier only_M_CT_SS (uint _ID, uint _CourseID) { if (msg.sender != SuperUser) { bool Authenticated = false; // msg.sender is Course Teacher? for (uint i = 0; i < teachers[_ID].tCourseIDs.length; i++) { if (teachers[_ID].tCourseIDs[i] == _CourseID && teacherTag[msg.sender] == true) { Authenticated = true; break; } } // msg.sender is Self Student? if (studentTag[msg.sender] == true && students[_ID].StudentAddr == msg.sender) Authenticated = true; // msg.sender is Manager? if (managerTag[msg.sender] == true) Authenticated = true; //Final check. if (!Authenticated) revert(); } _; } modifier only_M_CT (uint _ID, uint _CourseID) { if (msg.sender != SuperUser) { bool Authenticated = false; // msg.sender is Course Teacher? for (uint i = 0; i < teachers[_ID].tCourseIDs.length; i++) { if (teachers[_ID].tCourseIDs[i] == _CourseID && teacherTag[msg.sender] == true) { Authenticated = true; break; } } // msg.sender is Manager? if (managerTag[msg.sender] == true) Authenticated = true; //Final check. if (!Authenticated) revert(); } _; } modifier only_M_T_SS (uint _ID) { if (msg.sender != SuperUser) { if (!(studentTag[msg.sender] == true && students[_ID].StudentAddr == msg.sender) && managerTag[msg.sender] != true && teacherTag[msg.sender] != true) revert(); } _; } modifier only_M_T () { if (msg.sender != SuperUser) { if (managerTag[msg.sender] != true && teacherTag[msg.sender] != true) revert(); } _; } /* Functions */ // check whether the manager address or the managerID is exist or not function managerAddrExist (address _ManagerAddr) public view returns (bool) { for (uint m = 0; m < ManagerList.length; m++) { if(managers[ManagerList[m]].ManagerAddr == _ManagerAddr) { return true; } } return false; } // check whether the student address is exist or not function studentAddrExist (address _StudentAddr) public view returns (bool) { for (uint s = 0; s < StudentList.length; s++) { if (students[StudentList[s]].StudentAddr == _StudentAddr) { return true; } } return false; } // check whether the managerID is exist or not function managerIDExist (uint _ManagerID) public view returns (bool) { for (uint c = 0; c < ManagerList.length; c++) { if(ManagerList[c] == _ManagerID) return true; } return false; } // check whether the StudentID is exist or not function studentIDExist (uint _StudentID) public view returns (bool) { for (uint s = 0; s < StudentList.length; s++) { if (StudentList[s] == _StudentID) { return true; } } return false; } // check whether the courseID is exist or not function courseIDExist (uint _CourseID) public view returns (bool) { for (uint c = 0; c < CourseList.length; c++) { if(CourseList[c] == _CourseID) return true; } return false; } // check whether the teacherID is exist or not function teacherIDExist (uint _TeacherID) public view returns (bool) { for (uint c = 0; c < TeacherList.length; c++) { if(TeacherList[c] == _TeacherID) return true; } return false; } /* Add Info functions */ event TxMined(string indexed txid, bool indexed Success, address indexed Operator); mapping (string => bool) private TxTag; bool private enableTxTag = true; function setTxTag(string _Txid, bool value) internal { if (enableTxTag) { TxTag[_Txid] = value; } } function getTxTag(string _Txid) public view returns (bool) { if (enableTxTag) { return TxTag[_Txid]; } } function setEnableTxTag(bool value) onlySuperUser public { enableTxTag = value; } function getEnableTxTag() public view returns (bool) { return enableTxTag; } //set student ID and other info, push student ID into StudentList function addStuInfo (string _Txid, uint _StudentID, uint _StudentClass) //function addStuInfo (string _Txid, uint _StudentID, string _StudentName, uint _StudentClass) onlyManager public returns(bool) { if (!studentIDExist(_StudentID)) { stu_tmp.StudentID = _StudentID; stu_tmp.StudentName = "StudentName"; //stu_tmp.StudentName = _StudentName; stu_tmp.StudentClass = _StudentClass; students[_StudentID] = stu_tmp; class_stu[_StudentClass].push(_StudentID); StudentList.push(_StudentID); TxMined(_Txid, true, msg.sender); setTxTag(_Txid, true); log.addStuInfo(_Txid, true, msg.sender, _StudentID, "StudentName", _StudentClass); //log.addStuInfo(_Txid, true, msg.sender, _StudentID, _StudentName, _StudentClass); return true; } //Fail, already exists. TxMined(_Txid, false, msg.sender); setTxTag(_Txid, true); log.addStuInfo(_Txid, false, msg.sender, _StudentID, "StudentName", _StudentClass); //log.addStuInfo(_Txid, false, msg.sender, _StudentID, _StudentName, _StudentClass); return false; } Student public stu_tmp; //set teacher ID and other info, push teacher ID into TeacherList function addTchInfo (string _Txid, uint _TeacherID) onlyManager public returns(bool) { if (!teacherIDExist(_TeacherID)) { tch_tmp.TeacherID = _TeacherID; tch_tmp.TeacherName = "TeacherName"; //tch_tmp.TeacherName = _TeacherName; teachers[_TeacherID] = tch_tmp; TeacherList.push(_TeacherID); TxMined(_Txid, true, msg.sender); setTxTag(_Txid, true); log.addTeacherInfo(_Txid, true, msg.sender, _TeacherID, "TeacherName"); //log.addTeacherInfo(_Txid, true, msg.sender, _TeacherID, _TeacherName); return true; } //Fail, already exists. TxMined(_Txid, false, msg.sender); setTxTag(_Txid, true); log.addTeacherInfo(_Txid, false, msg.sender, _TeacherID, "TeacherName"); //log.addTeacherInfo(_Txid, false, msg.sender, _TeacherID, _TeacherName); return false; } Teacher public tch_tmp; //set course basic info. function addCourseInfo (string _Txid, uint _CourseID, bool _Compulsory, uint _Term, uint _Credit, uint[] _Percentage, uint _TeacherID) onlyManager public returns(bool) { if (!courseIDExist(_CourseID)) { course_tmp.CourseID = _CourseID; course_tmp.CourseName = "CourseName"; //course_tmp.CourseName = _CourseName; course_tmp.Compulsory = _Compulsory; course_tmp.Term = _Term; course_tmp.Credit = _Credit; course_tmp.Percentage = _Percentage; courses[_CourseID] = course_tmp; CourseList.push(_CourseID); teachers[_TeacherID].tCourseIDs.push(_CourseID); TxMined(_Txid, true, msg.sender); setTxTag(_Txid, true); //log.addCourseInfo(_Txid, true, msg.sender, _CourseID, _CourseName, _Compulsory, _Term, _Credit, _Percentage, _TeacherID); log.addCourseInfo(_Txid, true, msg.sender, _CourseID, "CourseName", _Compulsory, _Term, _Credit, _Percentage, _TeacherID); return true; } //Fail, already exists. TxMined(_Txid, false, msg.sender); setTxTag(_Txid, true); return false; } Course public course_tmp; //set manager ID and other info, push manager ID into ManagerList function addManagerInfo (string _Txid, uint _ManagerID) onlyManagerAbove public returns(bool) { if (!managerIDExist(_ManagerID)) { manager_tmp.ManagerID = _ManagerID; managers[_ManagerID] = manager_tmp; ManagerList.push(_ManagerID); TxMined(_Txid, true, msg.sender); setTxTag(_Txid, true); log.addManagerInfo(_Txid, true, msg.sender, _ManagerID); return true; } //Fail, already exists. TxMined(_Txid, false, msg.sender); setTxTag(_Txid, true); return false; } Manager public manager_tmp; /* Set address to registered account */ // set manager's address, manager info should have been exist. function AddStudentAddr (uint _StudentID, address _StudentAddress) onlyManager internal returns (bool) { if (studentIDExist(_StudentID)) { students[_StudentID].StudentAddr = _StudentAddress; studentTag[_StudentAddress] = true; return true; } //student Info not exists. return false; } function AddTeacherAddr (uint _TeacherID, address _TeacherAddress) onlyManager internal returns (bool) { if (teacherIDExist(_TeacherID)) { teachers[_TeacherID].TeacherAddr = _TeacherAddress; teacherTag[_TeacherAddress] = true; return true; } //Fail, teacher Info not exists. return false; } function AddManagerAddr (uint _ManagerID, address _ManagerAddress) onlyManagerAbove internal returns (bool) { if (managerIDExist(_ManagerID)) { managers[_ManagerID].ManagerAddr = _ManagerAddress; managerTag[_ManagerAddress] = true; return true; } return false; } /* After register, user generate a eth address, and record the addresss */ function addAccount (string _Txid, uint _Identity, uint _ID, address _Addr) onlyManagerAbove public returns(bool) { bool success = false; if (_Identity == 0) { //Students success = AddStudentAddr(_ID, _Addr); } else if (_Identity == 1) { //Teachers success = AddTeacherAddr(_ID, _Addr); } else if (_Identity == 2) { //Managers success = AddManagerAddr(_ID, _Addr); } else { //TxMined(_Txid, false, msg.sender); } TxMined(_Txid, success, msg.sender); log.addAccount(_Txid, true, msg.sender, _Identity, _ID, _Addr); setTxTag(_Txid, true); return success; } //Calculate student mark. function CalcMark(uint _CourseID, uint _StudentID) internal returns(uint mark) { uint[] memory grades = students[_StudentID].stu_courses[_CourseID].TestGrade; uint[] memory percents = courses[_CourseID].Percentage; uint gradeSum; uint percentSum; if (grades.length != percents.length) revert(); for (uint i = 0; i < grades.length; i++) { gradeSum += grades[i] * percents[i]; percentSum += percents[i]; } mark = gradeSum / percentSum; students[_StudentID].stu_courses[_CourseID].CourseGrade = mark; } //Teacher set the mark of one student. function setStuMark(string _Txid, uint _TeacherID, uint _CourseID, uint _StudentID, uint[] _Marks) only_M_T public returns(bool boolValue, uint mark){ boolValue = true; for (uint i = 0; i < students[_StudentID].sCourseIDs.length; i++) { if (_CourseID == students[_StudentID].sCourseIDs[i]) { students[_StudentID].stu_courses[_CourseID].TestGrade = _Marks; mark = CalcMark(_CourseID, _StudentID); TxMined(_Txid, boolValue, msg.sender); setTxTag(_Txid, boolValue); log.setStuMark(_Txid, boolValue, msg.sender, _TeacherID, _CourseID, _StudentID, _Marks); return (boolValue, mark); } } //Fail. Stu doesn't take this course. boolValue = false; TxMined(_Txid, boolValue, msg.sender); setTxTag(_Txid, false); log.setStuMark(_Txid, boolValue, msg.sender, _TeacherID, _CourseID, _StudentID, _Marks); return (boolValue, 0); } //How many classes has a student choose. function len_sCourseIDs (uint _StudentID) only_M_T_SS(_StudentID) public view returns(uint) { return students[_StudentID].sCourseIDs.length; } //How many students a course has. function len_cStuIDs (uint _CourseID) onlyUser public view returns(uint) { return courses[_CourseID].cStuIDs.length; } //Student choose Course. function stuChooseCourse(string _Txid, uint _CourseID, uint _StudentID, uint _requestTime) onlySelfStudent(_StudentID) public returns(bool) { for (uint i = 0; i < courses[_CourseID].cStuIDs.length; i++) { if (_StudentID == courses[_CourseID].cStuIDs[i]) { TxMined(_Txid, true, msg.sender); setTxTag(_Txid, true); log.stuChooseCourse(_Txid, true, msg.sender, _CourseID, _StudentID, _requestTime); return true; } } courses[_CourseID].cStuIDs.push(_StudentID); students[_StudentID].sCourseIDs.push(_CourseID); students[_StudentID].stu_courses[_CourseID].CourseID = _CourseID; students[_StudentID].stu_courses[_CourseID].Lp = LearningProgress.Start; TxMined(_Txid, true, msg.sender); setTxTag(_Txid, true); log.stuChooseCourse(_Txid, true, msg.sender, _CourseID, _StudentID, _requestTime); return true; } // return one course Mark of a student. function getStuMark (uint _StudentID, uint _CourseID) only_M_T_SS(_StudentID) public view returns(uint) { return students[_StudentID].stu_courses[_CourseID].CourseGrade; } /* This func was commented in 2018.03.20, to save gas consumption. function getStuMarks5 (uint _StudentID, uint _Page) only_M_T_SS(_StudentID) public view returns (uint[5] Terms, bool[5] Compulsorys, uint[5] Credits, uint[5] Marks) { uint len = len_sCourseIDs(_StudentID); //Number of courses that student takes. uint _NumOfLables = 5; uint endpoint; //return how many data. uint i = 0; uint j = 0; if (len/_NumOfLables < _Page) { if (len/_NumOfLables + 1 == _Page && _Page != 0) { endpoint = len; } else { revert(); } } else { endpoint = _Page*_NumOfLables; } for (i = _NumOfLables*(_Page-1); i < endpoint; i++) { //make a Stu_Course instance, name as sci. Stu_Course storage sci = students[_StudentID].stu_courses[i]; Course storage ci = courses[sci.CourseID]; (Terms[j],Compulsorys[j],Credits[j],Marks[j]) = (ci.Term,ci.Compulsory,ci.Credit,sci.CourseGrade); j++; } return; } */ function getStuMarksByCourse (uint _CourseID, uint _StudentID) only_M_T_SS(_StudentID) public view returns(uint) { return students[_StudentID].stu_courses[_CourseID].CourseGrade; } function getStuMarksByCourseAll (uint _CourseID) only_M_T public view returns (uint[], uint[]) { //uint len = courses[_CourseID].cStuIDs.length; uint[] memory StuIDs = courses[_CourseID].cStuIDs; uint[] memory Marks = courses[_CourseID].cStuIDs; //仅用此语句分配空间 for (uint i = 0; i< courses[_CourseID].cStuIDs.length; i++) { Marks[i] = students[StuIDs[i]].stu_courses[_CourseID].CourseGrade; } return (StuIDs, Marks); } }
currently not used debug function /
function get_cStuIDs(uint _CourseID) public view returns(uint[]) { uint[] memory result = courses[_CourseID].cStuIDs; return result; }
5,541,656
/** *Submitted for verification at Etherscan.io on 2019-12-31 */ // File: contracts/lib/Bytes32Library.sol /* Copyright 2018 Set Labs Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ pragma solidity 0.5.7; pragma experimental "ABIEncoderV2"; library Bytes32Library { /** * Converts a bytes32 data structure into a bytes array. * * @param data Piece of data encoded as bytes32 * @return bytes */ function bytes32ToBytes(bytes32 data) internal pure returns (bytes memory) { uint256 i = 0; while (i < 32 && uint256(bytes32(data[i])) != 0) { ++i; } bytes memory result = new bytes(i); i = 0; while (i < 32 && data[i] != 0) { result[i] = data[i]; ++i; } return result; } /** * Converts a piece of data encoded as bytes32 into a string. * * @param data Piece of data encoded as bytes32 * @return string */ function bytes32ToString(bytes32 data) internal pure returns (string memory) { bytes memory intermediate = bytes32ToBytes(data); return string(abi.encodePacked(intermediate)); } } // File: contracts/core/interfaces/ICore.sol /* Copyright 2018 Set Labs Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ pragma solidity 0.5.7; /** * @title ICore * @author Set Protocol * * The ICore Contract defines all the functions exposed in the Core through its * various extensions and is a light weight way to interact with the contract. */ interface ICore { /** * Return transferProxy address. * * @return address transferProxy address */ function transferProxy() external view returns (address); /** * Return vault address. * * @return address vault address */ function vault() external view returns (address); /** * Return address belonging to given exchangeId. * * @param _exchangeId ExchangeId number * @return address Address belonging to given exchangeId */ function exchangeIds( uint8 _exchangeId ) external view returns (address); /* * Returns if valid set * * @return bool Returns true if Set created through Core and isn't disabled */ function validSets(address) external view returns (bool); /* * Returns if valid module * * @return bool Returns true if valid module */ function validModules(address) external view returns (bool); /** * Return boolean indicating if address is a valid Rebalancing Price Library. * * @param _priceLibrary Price library address * @return bool Boolean indicating if valid Price Library */ function validPriceLibraries( address _priceLibrary ) external view returns (bool); /** * Exchanges components for Set Tokens * * @param _set Address of set to issue * @param _quantity Quantity of set to issue */ function issue( address _set, uint256 _quantity ) external; /** * Issues a specified Set for a specified quantity to the recipient * using the caller's components from the wallet and vault. * * @param _recipient Address to issue to * @param _set Address of the Set to issue * @param _quantity Number of tokens to issue */ function issueTo( address _recipient, address _set, uint256 _quantity ) external; /** * Converts user's components into Set Tokens held directly in Vault instead of user's account * * @param _set Address of the Set * @param _quantity Number of tokens to redeem */ function issueInVault( address _set, uint256 _quantity ) external; /** * Function to convert Set Tokens into underlying components * * @param _set The address of the Set token * @param _quantity The number of tokens to redeem. Should be multiple of natural unit. */ function redeem( address _set, uint256 _quantity ) external; /** * Redeem Set token and return components to specified recipient. The components * are left in the vault * * @param _recipient Recipient of Set being issued * @param _set Address of the Set * @param _quantity Number of tokens to redeem */ function redeemTo( address _recipient, address _set, uint256 _quantity ) external; /** * Function to convert Set Tokens held in vault into underlying components * * @param _set The address of the Set token * @param _quantity The number of tokens to redeem. Should be multiple of natural unit. */ function redeemInVault( address _set, uint256 _quantity ) external; /** * Composite method to redeem and withdraw with a single transaction * * Normally, you should expect to be able to withdraw all of the tokens. * However, some have central abilities to freeze transfers (e.g. EOS). _toExclude * allows you to optionally specify which component tokens to exclude when * redeeming. They will remain in the vault under the users' addresses. * * @param _set Address of the Set * @param _to Address to withdraw or attribute tokens to * @param _quantity Number of tokens to redeem * @param _toExclude Mask of indexes of tokens to exclude from withdrawing */ function redeemAndWithdrawTo( address _set, address _to, uint256 _quantity, uint256 _toExclude ) external; /** * Deposit multiple tokens to the vault. Quantities should be in the * order of the addresses of the tokens being deposited. * * @param _tokens Array of the addresses of the ERC20 tokens * @param _quantities Array of the number of tokens to deposit */ function batchDeposit( address[] calldata _tokens, uint256[] calldata _quantities ) external; /** * Withdraw multiple tokens from the vault. Quantities should be in the * order of the addresses of the tokens being withdrawn. * * @param _tokens Array of the addresses of the ERC20 tokens * @param _quantities Array of the number of tokens to withdraw */ function batchWithdraw( address[] calldata _tokens, uint256[] calldata _quantities ) external; /** * Deposit any quantity of tokens into the vault. * * @param _token The address of the ERC20 token * @param _quantity The number of tokens to deposit */ function deposit( address _token, uint256 _quantity ) external; /** * Withdraw a quantity of tokens from the vault. * * @param _token The address of the ERC20 token * @param _quantity The number of tokens to withdraw */ function withdraw( address _token, uint256 _quantity ) external; /** * Transfer tokens associated with the sender's account in vault to another user's * account in vault. * * @param _token Address of token being transferred * @param _to Address of user receiving tokens * @param _quantity Amount of tokens being transferred */ function internalTransfer( address _token, address _to, uint256 _quantity ) external; /** * Deploys a new Set Token and adds it to the valid list of SetTokens * * @param _factory The address of the Factory to create from * @param _components The address of component tokens * @param _units The units of each component token * @param _naturalUnit The minimum unit to be issued or redeemed * @param _name The bytes32 encoded name of the new Set * @param _symbol The bytes32 encoded symbol of the new Set * @param _callData Byte string containing additional call parameters * @return setTokenAddress The address of the new Set */ function createSet( address _factory, address[] calldata _components, uint256[] calldata _units, uint256 _naturalUnit, bytes32 _name, bytes32 _symbol, bytes calldata _callData ) external returns (address); /** * Exposes internal function that deposits a quantity of tokens to the vault and attributes * the tokens respectively, to system modules. * * @param _from Address to transfer tokens from * @param _to Address to credit for deposit * @param _token Address of token being deposited * @param _quantity Amount of tokens to deposit */ function depositModule( address _from, address _to, address _token, uint256 _quantity ) external; /** * Exposes internal function that withdraws a quantity of tokens from the vault and * deattributes the tokens respectively, to system modules. * * @param _from Address to decredit for withdraw * @param _to Address to transfer tokens to * @param _token Address of token being withdrawn * @param _quantity Amount of tokens to withdraw */ function withdrawModule( address _from, address _to, address _token, uint256 _quantity ) external; /** * Exposes internal function that deposits multiple tokens to the vault, to system * modules. Quantities should be in the order of the addresses of the tokens being * deposited. * * @param _from Address to transfer tokens from * @param _to Address to credit for deposits * @param _tokens Array of the addresses of the tokens being deposited * @param _quantities Array of the amounts of tokens to deposit */ function batchDepositModule( address _from, address _to, address[] calldata _tokens, uint256[] calldata _quantities ) external; /** * Exposes internal function that withdraws multiple tokens from the vault, to system * modules. Quantities should be in the order of the addresses of the tokens being withdrawn. * * @param _from Address to decredit for withdrawals * @param _to Address to transfer tokens to * @param _tokens Array of the addresses of the tokens being withdrawn * @param _quantities Array of the amounts of tokens to withdraw */ function batchWithdrawModule( address _from, address _to, address[] calldata _tokens, uint256[] calldata _quantities ) external; /** * Expose internal function that exchanges components for Set tokens, * accepting any owner, to system modules * * @param _owner Address to use tokens from * @param _recipient Address to issue Set to * @param _set Address of the Set to issue * @param _quantity Number of tokens to issue */ function issueModule( address _owner, address _recipient, address _set, uint256 _quantity ) external; /** * Expose internal function that exchanges Set tokens for components, * accepting any owner, to system modules * * @param _burnAddress Address to burn token from * @param _incrementAddress Address to increment component tokens to * @param _set Address of the Set to redeem * @param _quantity Number of tokens to redeem */ function redeemModule( address _burnAddress, address _incrementAddress, address _set, uint256 _quantity ) external; /** * Expose vault function that increments user's balance in the vault. * Available to system modules * * @param _tokens The addresses of the ERC20 tokens * @param _owner The address of the token owner * @param _quantities The numbers of tokens to attribute to owner */ function batchIncrementTokenOwnerModule( address[] calldata _tokens, address _owner, uint256[] calldata _quantities ) external; /** * Expose vault function that decrement user's balance in the vault * Only available to system modules. * * @param _tokens The addresses of the ERC20 tokens * @param _owner The address of the token owner * @param _quantities The numbers of tokens to attribute to owner */ function batchDecrementTokenOwnerModule( address[] calldata _tokens, address _owner, uint256[] calldata _quantities ) external; /** * Expose vault function that transfer vault balances between users * Only available to system modules. * * @param _tokens Addresses of tokens being transferred * @param _from Address tokens being transferred from * @param _to Address tokens being transferred to * @param _quantities Amounts of tokens being transferred */ function batchTransferBalanceModule( address[] calldata _tokens, address _from, address _to, uint256[] calldata _quantities ) external; /** * Transfers token from one address to another using the transfer proxy. * Only available to system modules. * * @param _token The address of the ERC20 token * @param _quantity The number of tokens to transfer * @param _from The address to transfer from * @param _to The address to transfer to */ function transferModule( address _token, uint256 _quantity, address _from, address _to ) external; /** * Expose transfer proxy function to transfer tokens from one address to another * Only available to system modules. * * @param _tokens The addresses of the ERC20 token * @param _quantities The numbers of tokens to transfer * @param _from The address to transfer from * @param _to The address to transfer to */ function batchTransferModule( address[] calldata _tokens, uint256[] calldata _quantities, address _from, address _to ) external; } // File: contracts/core/interfaces/ISetToken.sol /* Copyright 2018 Set Labs Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ pragma solidity 0.5.7; /** * @title ISetToken * @author Set Protocol * * The ISetToken interface provides a light-weight, structured way to interact with the * SetToken contract from another contract. */ interface ISetToken { /* ============ External Functions ============ */ /* * Get natural unit of Set * * @return uint256 Natural unit of Set */ function naturalUnit() external view returns (uint256); /* * Get addresses of all components in the Set * * @return componentAddresses Array of component tokens */ function getComponents() external view returns (address[] memory); /* * Get units of all tokens in Set * * @return units Array of component units */ function getUnits() external view returns (uint256[] memory); /* * Checks to make sure token is component of Set * * @param _tokenAddress Address of token being checked * @return bool True if token is component of Set */ function tokenIsComponent( address _tokenAddress ) external view returns (bool); /* * Mint set token for given address. * Can only be called by authorized contracts. * * @param _issuer The address of the issuing account * @param _quantity The number of sets to attribute to issuer */ function mint( address _issuer, uint256 _quantity ) external; /* * Burn set token for given address * Can only be called by authorized contracts * * @param _from The address of the redeeming account * @param _quantity The number of sets to burn from redeemer */ function burn( address _from, uint256 _quantity ) external; /** * 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 ) external; } // File: contracts/core/lib/Rebalance.sol /* Copyright 2019 Set Labs Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ pragma solidity 0.5.7; /** * @title Rebalance * @author Set Protocol * * Types and functions for Rebalance-related data. */ library Rebalance { struct Price { uint256 numerator; uint256 denominator; } struct TokenFlow { address[] addresses; uint256[] inflow; uint256[] outflow; } function composePrice( uint256 _numerator, uint256 _denominator ) internal pure returns(Price memory) { return Price({ numerator: _numerator, denominator: _denominator }); } function composeTokenFlow( address[] memory _addresses, uint256[] memory _inflow, uint256[] memory _outflow ) internal pure returns(TokenFlow memory) { return TokenFlow({addresses: _addresses, inflow: _inflow, outflow: _outflow }); } function decomposeTokenFlow(TokenFlow memory _tokenFlow) internal pure returns (address[] memory, uint256[] memory, uint256[] memory) { return (_tokenFlow.addresses, _tokenFlow.inflow, _tokenFlow.outflow); } function decomposeTokenFlowToBidPrice(TokenFlow memory _tokenFlow) internal pure returns (uint256[] memory, uint256[] memory) { return (_tokenFlow.inflow, _tokenFlow.outflow); } } // File: contracts/core/lib/RebalancingLibrary.sol /* Copyright 2018 Set Labs Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ pragma solidity 0.5.7; /** * @title RebalancingLibrary * @author Set Protocol * * The RebalancingLibrary contains functions for facilitating the rebalancing process for * Rebalancing Set Tokens. Removes the old calculation functions * */ library RebalancingLibrary { /* ============ Enums ============ */ enum State { Default, Proposal, Rebalance, Drawdown } /* ============ Structs ============ */ struct AuctionPriceParameters { uint256 auctionStartTime; uint256 auctionTimeToPivot; uint256 auctionStartPrice; uint256 auctionPivotPrice; } struct BiddingParameters { uint256 minimumBid; uint256 remainingCurrentSets; uint256[] combinedCurrentUnits; uint256[] combinedNextSetUnits; address[] combinedTokenArray; } } // File: contracts/core/interfaces/ILiquidator.sol /* Copyright 2019 Set Labs Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ pragma solidity 0.5.7; /** * @title ILiquidator * @author Set Protocol * */ interface ILiquidator { /* ============ External Functions ============ */ function startRebalance( ISetToken _currentSet, ISetToken _nextSet, uint256 _startingCurrentSetQuantity, bytes calldata _liquidatorData ) external; function getBidPrice( address _set, uint256 _quantity ) external view returns (Rebalance.TokenFlow memory); function placeBid( uint256 _quantity ) external returns (Rebalance.TokenFlow memory); function settleRebalance() external; function endFailedRebalance() external; // ---------------------------------------------------------------------- // Auction Price // ---------------------------------------------------------------------- function auctionPriceParameters(address _set) external view returns (RebalancingLibrary.AuctionPriceParameters memory); // ---------------------------------------------------------------------- // Auction // ---------------------------------------------------------------------- function hasRebalanceFailed(address _set) external view returns (bool); function minimumBid(address _set) external view returns (uint256); function startingCurrentSets(address _set) external view returns (uint256); function remainingCurrentSets(address _set) external view returns (uint256); function getCombinedCurrentSetUnits(address _set) external view returns (uint256[] memory); function getCombinedNextSetUnits(address _set) external view returns (uint256[] memory); function getCombinedTokenArray(address _set) external view returns (address[] memory); } // File: contracts/core/interfaces/IFeeCalculator.sol /* Copyright 2019 Set Labs Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ pragma solidity 0.5.7; /** * @title IFeeCalculator * @author Set Protocol * */ interface IFeeCalculator { /* ============ External Functions ============ */ function initialize( bytes calldata _feeCalculatorData ) external; function getFee() external view returns(uint256); } // File: contracts/core/interfaces/IRebalancingSetTokenV2.sol /* Copyright 2019 Set Labs Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ pragma solidity 0.5.7; /** * @title IRebalancingSetTokenV2 * @author Set Protocol * * The IRebalancingSetTokenV2 interface provides a light-weight, structured way to interact with the * RebalancingSetTokenV2 contract from another contract. */ interface IRebalancingSetTokenV2 { /* * Get totalSupply of Rebalancing Set * * @return totalSupply */ function totalSupply() external view returns (uint256); /** * Returns liquidator instance * * @return ILiquidator Liquidator instance */ function liquidator() external view returns (ILiquidator); /* * Get lastRebalanceTimestamp of Rebalancing Set * * @return lastRebalanceTimestamp */ function lastRebalanceTimestamp() external view returns (uint256); /* * Get rebalanceStartTime of Rebalancing Set * * @return rebalanceStartTime */ function rebalanceStartTime() external view returns (uint256); /* * Get startingCurrentSets of RebalancingSetToken * * @return startingCurrentSets */ function startingCurrentSetAmount() external view returns (uint256); /* * Get rebalanceInterval of Rebalancing Set * * @return rebalanceInterval */ function rebalanceInterval() external view returns (uint256); /* * Get array returning [startTime, timeToPivot, startPrice, endPrice] * * @return AuctionPriceParameters */ function getAuctionPriceParameters() external view returns (uint256[] memory); /* * Get array returning [minimumBid, remainingCurrentSets] * * @return BiddingParameters */ function getBiddingParameters() external view returns (uint256[] memory); /* * Get rebalanceState of Rebalancing Set * * @return RebalancingLibrary.State Current rebalance state of the RebalancingSetTokenV2 */ function rebalanceState() external view returns (RebalancingLibrary.State); /** * Gets the balance of the specified address. * * @param owner The address to query the balance of. * @return A uint256 representing the amount owned by the passed address. */ function balanceOf( address owner ) external view returns (uint256); /* * Get manager of Rebalancing Set * * @return manager */ function manager() external view returns (address); /* * Get feeRecipient of Rebalancing Set * * @return feeRecipient */ function feeRecipient() external view returns (address); /* * Get entryFee of Rebalancing Set * * @return entryFee */ function entryFee() external view returns (uint256); /* * Retrieves the current expected fee from the fee calculator * Value is returned as a scale decimal figure. */ function rebalanceFee() external view returns (uint256); /* * Get calculator contract used to compute rebalance fees * * @return rebalanceFeeCalculator */ function rebalanceFeeCalculator() external view returns (IFeeCalculator); /* * Initializes the RebalancingSetToken. Typically called by the Factory during creation */ function initialize( bytes calldata _rebalanceFeeCalldata ) external; /* * Set new liquidator address. Only whitelisted addresses are valid. */ function setLiquidator( ILiquidator _newLiquidator ) external; /* * Set new fee recipient address. */ function setFeeRecipient( address _newFeeRecipient ) external; /* * Set new fee entry fee. */ function setEntryFee( uint256 _newEntryFee ) external; /* * Initiates the rebalance in coordination with the Liquidator contract. * In this step, we redeem the currentSet and pass relevant information * to the liquidator. * * @param _nextSet The Set to rebalance into * @param _liquidatorData Bytecode formatted data with liquidator-specific arguments * * Can only be called if the rebalance interval has elapsed. * Can only be called by manager. */ function startRebalance( address _nextSet, bytes calldata _liquidatorData ) external; /* * After a successful rebalance, the new Set is issued. If there is a rebalance fee, * the fee is paid via inflation of the Rebalancing Set to the feeRecipient. * Full issuance functionality is now returned to set owners. * * Anyone can call this function. */ function settleRebalance() external; /* * Get natural unit of Set * * @return uint256 Natural unit of Set */ function naturalUnit() external view returns (uint256); /** * Returns the address of the current base SetToken with the current allocation * * @return A address representing the base SetToken */ function currentSet() external view returns (ISetToken); /** * Returns the address of the next base SetToken with the post auction allocation * * @return address Address representing the base SetToken */ function nextSet() external view returns (ISetToken); /* * Get the unit shares of the rebalancing Set * * @return unitShares Unit Shares of the base Set */ function unitShares() external view returns (uint256); /* * Place bid during rebalance auction. Can only be called by Core. * * @param _quantity The amount of currentSet to be rebalanced * @return combinedTokenArray Array of token addresses invovled in rebalancing * @return inflowUnitArray Array of amount of tokens inserted into system in bid * @return outflowUnitArray Array of amount of tokens taken out of system in bid */ function placeBid( uint256 _quantity ) external returns (address[] memory, uint256[] memory, uint256[] memory); /* * Get token inflows and outflows required for bid. Also the amount of Rebalancing * Sets that would be generated. * * @param _quantity The amount of currentSet to be rebalanced * @return inflowUnitArray Array of amount of tokens inserted into system in bid * @return outflowUnitArray Array of amount of tokens taken out of system in bid */ function getBidPrice( uint256 _quantity ) external view returns (uint256[] memory, uint256[] memory); /* * Get name of Rebalancing Set * * @return name */ function name() external view returns (string memory); /* * Get symbol of Rebalancing Set * * @return symbol */ function symbol() external view returns (string memory); } // File: contracts/external/0x/LibBytes.sol /* Copyright 2018 ZeroEx Intl. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ pragma solidity 0.5.7; library LibBytes { using LibBytes for bytes; /// @dev Gets the memory address for the contents of a byte array. /// @param input Byte array to lookup. /// @return memoryAddress Memory address of the contents of the byte array. function contentAddress(bytes memory input) internal pure returns (uint256 memoryAddress) { assembly { memoryAddress := add(input, 32) } return memoryAddress; } /// @dev Reads an unpadded bytes4 value from a position in a byte array. /// @param b Byte array containing a bytes4 value. /// @param index Index in byte array of bytes4 value. /// @return bytes4 value from byte array. function readBytes4( bytes memory b, uint256 index) internal pure returns (bytes4 result) { require( b.length >= index + 4, "GREATER_OR_EQUAL_TO_4_LENGTH_REQUIRED" ); assembly { result := mload(add(b, 32)) // Solidity does not require us to clean the trailing bytes. // We do it anyway result := and(result, 0xFFFFFFFF00000000000000000000000000000000000000000000000000000000) } return result; } /// @dev Reads a bytes32 value from a position in a byte array. /// @param b Byte array containing a bytes32 value. /// @param index Index in byte array of bytes32 value. /// @return bytes32 value from byte array. function readBytes32( bytes memory b, uint256 index ) internal pure returns (bytes32 result) { require( b.length >= index + 32, "GREATER_OR_EQUAL_TO_32_LENGTH_REQUIRED" ); // Arrays are prefixed by a 256 bit length parameter index += 32; // Read the bytes32 from array memory assembly { result := mload(add(b, index)) } return result; } /// @dev Copies `length` bytes from memory location `source` to `dest`. /// @param dest memory address to copy bytes to. /// @param source memory address to copy bytes from. /// @param length number of bytes to copy. function memCopy( uint256 dest, uint256 source, uint256 length ) internal pure { if (length < 32) { // Handle a partial word by reading destination and masking // off the bits we are interested in. // This correctly handles overlap, zero lengths and source == dest assembly { let mask := sub(exp(256, sub(32, length)), 1) let s := and(mload(source), not(mask)) let d := and(mload(dest), mask) mstore(dest, or(s, d)) } } else { // Skip the O(length) loop when source == dest. if (source == dest) { return; } // For large copies we copy whole words at a time. The final // word is aligned to the end of the range (instead of after the // previous) to handle partial words. So a copy will look like this: // // #### // #### // #### // #### // // We handle overlap in the source and destination range by // changing the copying direction. This prevents us from // overwriting parts of source that we still need to copy. // // This correctly handles source == dest // if (source > dest) { assembly { // We subtract 32 from `sEnd` and `dEnd` because it // is easier to compare with in the loop, and these // are also the addresses we need for copying the // last bytes. length := sub(length, 32) let sEnd := add(source, length) let dEnd := add(dest, length) // Remember the last 32 bytes of source // This needs to be done here and not after the loop // because we may have overwritten the last bytes in // source already due to overlap. let last := mload(sEnd) // Copy whole words front to back // Note: the first check is always true, // this could have been a do-while loop. for {} lt(source, sEnd) {} { mstore(dest, mload(source)) source := add(source, 32) dest := add(dest, 32) } // Write the last 32 bytes mstore(dEnd, last) } } else { assembly { // We subtract 32 from `sEnd` and `dEnd` because those // are the starting points when copying a word at the end. length := sub(length, 32) let sEnd := add(source, length) let dEnd := add(dest, length) // Remember the first 32 bytes of source // This needs to be done here and not after the loop // because we may have overwritten the first bytes in // source already due to overlap. let first := mload(source) // Copy whole words back to front // We use a signed comparisson here to allow dEnd to become // negative (happens when source and dest < 32). Valid // addresses in local memory will never be larger than // 2**255, so they can be safely re-interpreted as signed. // Note: the first check is always true, // this could have been a do-while loop. for {} slt(dest, dEnd) {} { mstore(dEnd, mload(sEnd)) sEnd := sub(sEnd, 32) dEnd := sub(dEnd, 32) } // Write the first 32 bytes mstore(dest, first) } } } } /// @dev Returns a slices from a byte array. /// @param b The byte array to take a slice from. /// @param from The starting index for the slice (inclusive). /// @param to The final index for the slice (exclusive). /// @return result The slice containing bytes at indices [from, to) function slice(bytes memory b, uint256 from, uint256 to) internal pure returns (bytes memory result) { require( from <= to, "FROM_LESS_THAN_TO_REQUIRED" ); require( // NOTE: Set Protocol changed from `to < b.length` so that the last byte can be sliced off to <= b.length, "TO_LESS_THAN_LENGTH_REQUIRED" ); // Create a new bytes structure and copy contents result = new bytes(to - from); memCopy( result.contentAddress(), b.contentAddress() + from, result.length); return result; } } // File: openzeppelin-solidity/contracts/token/ERC20/IERC20.sol pragma solidity ^0.5.2; /** * @title ERC20 interface * @dev see https://eips.ethereum.org/EIPS/eip-20 */ interface IERC20 { function transfer(address to, uint256 value) external returns (bool); function approve(address spender, uint256 value) external returns (bool); function transferFrom(address from, address to, uint256 value) external returns (bool); function totalSupply() external view returns (uint256); function balanceOf(address who) external view returns (uint256); function allowance(address owner, address spender) external view returns (uint256); event Transfer(address indexed from, address indexed to, uint256 value); event Approval(address indexed owner, address indexed spender, uint256 value); } // File: openzeppelin-solidity/contracts/math/SafeMath.sol pragma solidity ^0.5.2; /** * @title SafeMath * @dev Unsigned math operations with safety checks that revert on error */ library SafeMath { /** * @dev Multiplies two unsigned integers, reverts on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b); return c; } /** * @dev Integer division of two unsigned integers truncating the quotient, reverts on division by zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // Solidity only automatically asserts when dividing by 0 require(b > 0); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Subtracts two unsigned integers, reverts on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a); uint256 c = a - b; return c; } /** * @dev Adds two unsigned integers, reverts on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a); return c; } /** * @dev Divides two unsigned integers and returns the remainder (unsigned integer modulo), * reverts when dividing by zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b != 0); return a % b; } } // File: openzeppelin-solidity/contracts/token/ERC20/ERC20.sol pragma solidity ^0.5.2; /** * @title Standard ERC20 token * * @dev Implementation of the basic standard token. * https://eips.ethereum.org/EIPS/eip-20 * Originally based on code by FirstBlood: * https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol * * This implementation emits additional Approval events, allowing applications to reconstruct the allowance status for * all accounts just by listening to said events. Note that this isn't required by the specification, and other * compliant implementations may not do it. */ contract ERC20 is IERC20 { using SafeMath for uint256; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowed; uint256 private _totalSupply; /** * @dev Total number of tokens in existence */ function totalSupply() public view returns (uint256) { return _totalSupply; } /** * @dev Gets the balance of the specified address. * @param owner The address to query the balance of. * @return A uint256 representing the amount owned by the passed address. */ function balanceOf(address owner) public view returns (uint256) { return _balances[owner]; } /** * @dev Function to check the amount of tokens that an owner allowed to a spender. * @param owner address The address which owns the funds. * @param spender address The address which will spend the funds. * @return A uint256 specifying the amount of tokens still available for the spender. */ function allowance(address owner, address spender) public view returns (uint256) { return _allowed[owner][spender]; } /** * @dev Transfer token to a specified address * @param to The address to transfer to. * @param value The amount to be transferred. */ function transfer(address to, uint256 value) public returns (bool) { _transfer(msg.sender, to, value); return true; } /** * @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender. * Beware that changing an allowance with this method brings the risk that someone may use both the old * and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this * race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * @param spender The address which will spend the funds. * @param value The amount of tokens to be spent. */ function approve(address spender, uint256 value) public returns (bool) { _approve(msg.sender, spender, value); return true; } /** * @dev Transfer tokens from one address to another. * Note that while this function emits an Approval event, this is not required as per the specification, * and other compliant implementations may not emit the event. * @param from address The address which you want to send tokens from * @param to address The address which you want to transfer to * @param value uint256 the amount of tokens to be transferred */ function transferFrom(address from, address to, uint256 value) public returns (bool) { _transfer(from, to, value); _approve(from, msg.sender, _allowed[from][msg.sender].sub(value)); return true; } /** * @dev Increase the amount of tokens that an owner allowed to a spender. * approve should be called when _allowed[msg.sender][spender] == 0. To increment * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * Emits an Approval event. * @param spender The address which will spend the funds. * @param addedValue The amount of tokens to increase the allowance by. */ function increaseAllowance(address spender, uint256 addedValue) public returns (bool) { _approve(msg.sender, spender, _allowed[msg.sender][spender].add(addedValue)); return true; } /** * @dev Decrease the amount of tokens that an owner allowed to a spender. * approve should be called when _allowed[msg.sender][spender] == 0. To decrement * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * Emits an Approval event. * @param spender The address which will spend the funds. * @param subtractedValue The amount of tokens to decrease the allowance by. */ function decreaseAllowance(address spender, uint256 subtractedValue) public returns (bool) { _approve(msg.sender, spender, _allowed[msg.sender][spender].sub(subtractedValue)); return true; } /** * @dev Transfer token for a specified addresses * @param from The address to transfer from. * @param to The address to transfer to. * @param value The amount to be transferred. */ function _transfer(address from, address to, uint256 value) internal { require(to != address(0)); _balances[from] = _balances[from].sub(value); _balances[to] = _balances[to].add(value); emit Transfer(from, to, value); } /** * @dev Internal function that mints an amount of the token and assigns it to * an account. This encapsulates the modification of balances such that the * proper events are emitted. * @param account The account that will receive the created tokens. * @param value The amount that will be created. */ function _mint(address account, uint256 value) internal { require(account != address(0)); _totalSupply = _totalSupply.add(value); _balances[account] = _balances[account].add(value); emit Transfer(address(0), account, value); } /** * @dev Internal function that burns an amount of the token of a given * account. * @param account The account whose tokens will be burnt. * @param value The amount that will be burnt. */ function _burn(address account, uint256 value) internal { require(account != address(0)); _totalSupply = _totalSupply.sub(value); _balances[account] = _balances[account].sub(value); emit Transfer(account, address(0), value); } /** * @dev Approve an address to spend another addresses' tokens. * @param owner The address that owns the tokens. * @param spender The address that will spend the tokens. * @param value The number of tokens that can be spent. */ function _approve(address owner, address spender, uint256 value) internal { require(spender != address(0)); require(owner != address(0)); _allowed[owner][spender] = value; emit Approval(owner, spender, value); } /** * @dev Internal function that burns an amount of the token of a given * account, deducting from the sender's allowance for said account. Uses the * internal burn function. * Emits an Approval event (reflecting the reduced allowance). * @param account The account whose tokens will be burnt. * @param value The amount that will be burnt. */ function _burnFrom(address account, uint256 value) internal { _burn(account, value); _approve(account, msg.sender, _allowed[account][msg.sender].sub(value)); } } // File: openzeppelin-solidity/contracts/token/ERC20/ERC20Detailed.sol pragma solidity ^0.5.2; /** * @title ERC20Detailed token * @dev The decimals are only for visualization purposes. * All the operations are done using the smallest and indivisible token unit, * just as on Ethereum all the operations are done in wei. */ contract ERC20Detailed is IERC20 { string private _name; string private _symbol; uint8 private _decimals; constructor (string memory name, string memory symbol, uint8 decimals) public { _name = name; _symbol = symbol; _decimals = decimals; } /** * @return the name of the token. */ function name() public view returns (string memory) { return _name; } /** * @return the symbol of the token. */ function symbol() public view returns (string memory) { return _symbol; } /** * @return the number of decimals of the token. */ function decimals() public view returns (uint8) { return _decimals; } } // File: zos-lib/contracts/Initializable.sol pragma solidity >=0.4.24 <0.6.0; /** * @title Initializable * * @dev Helper contract to support initializer functions. To use it, replace * the constructor with a function that has the `initializer` modifier. * WARNING: Unlike constructors, initializer functions must be manually * invoked. This applies both to deploying an Initializable contract, as well * as extending an Initializable contract via inheritance. * WARNING: When used with inheritance, manual care must be taken to not invoke * a parent initializer twice, or ensure that all initializers are idempotent, * because this is not dealt with automatically as with constructors. */ contract Initializable { /** * @dev Indicates that the contract has been initialized. */ bool private initialized; /** * @dev Indicates that the contract is in the process of being initialized. */ bool private initializing; /** * @dev Modifier to use in the initializer function of a contract. */ modifier initializer() { require(initializing || isConstructor() || !initialized, "Contract instance has already been initialized"); bool isTopLevelCall = !initializing; if (isTopLevelCall) { initializing = true; initialized = true; } _; if (isTopLevelCall) { initializing = false; } } /// @dev Returns true if and only if the function is running in the constructor function isConstructor() private view returns (bool) { // extcodesize checks the size of the code stored in an address, and // address returns the current address. Since the code is still not // deployed when running a constructor, any checks on its code size will // yield zero, making it an effective way to detect if a contract is // under construction or not. uint256 cs; assembly { cs := extcodesize(address) } return cs == 0; } // Reserved storage space to allow for layout changes in the future. uint256[50] private ______gap; } // File: contracts/core/interfaces/ISetFactory.sol /* Copyright 2018 Set Labs Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ pragma solidity 0.5.7; /** * @title ISetFactory * @author Set Protocol * * The ISetFactory interface provides operability for authorized contracts * to interact with SetTokenFactory */ interface ISetFactory { /* ============ External Functions ============ */ /** * Return core address * * @return address core address */ function core() external returns (address); /** * Deploys a new Set Token and adds it to the valid list of SetTokens * * @param _components The address of component tokens * @param _units The units of each component token * @param _naturalUnit The minimum unit to be issued or redeemed * @param _name The bytes32 encoded name of the new Set * @param _symbol The bytes32 encoded symbol of the new Set * @param _callData Byte string containing additional call parameters * @return setTokenAddress The address of the new Set */ function createSet( address[] calldata _components, uint[] calldata _units, uint256 _naturalUnit, bytes32 _name, bytes32 _symbol, bytes calldata _callData ) external returns (address); } // File: contracts/core/interfaces/IWhiteList.sol /* Copyright 2018 Set Labs Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ pragma solidity 0.5.7; /** * @title IWhiteList * @author Set Protocol * * The IWhiteList interface exposes the whitelist mapping to check components */ interface IWhiteList { /* ============ External Functions ============ */ /** * Validates address against white list * * @param _address Address to check * @return bool Whether passed in address is whitelisted */ function whiteList( address _address ) external view returns (bool); /** * Verifies an array of addresses against the whitelist * * @param _addresses Array of addresses to verify * @return bool Whether all addresses in the list are whitelsited */ function areValidAddresses( address[] calldata _addresses ) external view returns (bool); } // File: contracts/core/interfaces/IRebalancingSetFactory.sol /* Copyright 2018 Set Labs Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ pragma solidity 0.5.7; /** * @title IRebalancingSetFactory * @author Set Protocol * * The IRebalancingSetFactory interface provides operability for authorized contracts * to interact with RebalancingSetTokenFactory */ contract IRebalancingSetFactory is ISetFactory { /** * Getter for minimumRebalanceInterval of RebalancingSetTokenFactory, used * to enforce rebalanceInterval when creating a RebalancingSetToken * * @return uint256 Minimum amount of time between rebalances in seconds */ function minimumRebalanceInterval() external returns (uint256); /** * Getter for minimumProposalPeriod of RebalancingSetTokenFactory, used * to enforce proposalPeriod when creating a RebalancingSetToken * * @return uint256 Minimum amount of time users can review proposals in seconds */ function minimumProposalPeriod() external returns (uint256); /** * Getter for minimumTimeToPivot of RebalancingSetTokenFactory, used * to enforce auctionTimeToPivot when proposing a rebalance * * @return uint256 Minimum amount of time before auction pivot reached */ function minimumTimeToPivot() external returns (uint256); /** * Getter for maximumTimeToPivot of RebalancingSetTokenFactory, used * to enforce auctionTimeToPivot when proposing a rebalance * * @return uint256 Maximum amount of time before auction pivot reached */ function maximumTimeToPivot() external returns (uint256); /** * Getter for minimumNaturalUnit of RebalancingSetTokenFactory * * @return uint256 Minimum natural unit */ function minimumNaturalUnit() external returns (uint256); /** * Getter for maximumNaturalUnit of RebalancingSetTokenFactory * * @return uint256 Maximum Minimum natural unit */ function maximumNaturalUnit() external returns (uint256); /** * Getter for rebalanceAuctionModule address on RebalancingSetTokenFactory * * @return address Address of rebalanceAuctionModule */ function rebalanceAuctionModule() external returns (address); } // File: contracts/core/interfaces/IVault.sol /* Copyright 2018 Set Labs Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ pragma solidity 0.5.7; /** * @title IVault * @author Set Protocol * * The IVault interface provides a light-weight, structured way to interact with the Vault * contract from another contract. */ interface IVault { /* * Withdraws user's unassociated tokens to user account. Can only be * called by authorized core contracts. * * @param _token The address of the ERC20 token * @param _to The address to transfer token to * @param _quantity The number of tokens to transfer */ function withdrawTo( address _token, address _to, uint256 _quantity ) external; /* * Increment quantity owned of a token for a given address. Can * only be called by authorized core contracts. * * @param _token The address of the ERC20 token * @param _owner The address of the token owner * @param _quantity The number of tokens to attribute to owner */ function incrementTokenOwner( address _token, address _owner, uint256 _quantity ) external; /* * Decrement quantity owned of a token for a given address. Can only * be called by authorized core contracts. * * @param _token The address of the ERC20 token * @param _owner The address of the token owner * @param _quantity The number of tokens to deattribute to owner */ function decrementTokenOwner( address _token, address _owner, uint256 _quantity ) external; /** * Transfers tokens associated with one account to another account in the vault * * @param _token Address of token being transferred * @param _from Address token being transferred from * @param _to Address token being transferred to * @param _quantity Amount of tokens being transferred */ function transferBalance( address _token, address _from, address _to, uint256 _quantity ) external; /* * Withdraws user's unassociated tokens to user account. Can only be * called by authorized core contracts. * * @param _tokens The addresses of the ERC20 tokens * @param _owner The address of the token owner * @param _quantities The numbers of tokens to attribute to owner */ function batchWithdrawTo( address[] calldata _tokens, address _to, uint256[] calldata _quantities ) external; /* * Increment quantites owned of a collection of tokens for a given address. Can * only be called by authorized core contracts. * * @param _tokens The addresses of the ERC20 tokens * @param _owner The address of the token owner * @param _quantities The numbers of tokens to attribute to owner */ function batchIncrementTokenOwner( address[] calldata _tokens, address _owner, uint256[] calldata _quantities ) external; /* * Decrements quantites owned of a collection of tokens for a given address. Can * only be called by authorized core contracts. * * @param _tokens The addresses of the ERC20 tokens * @param _owner The address of the token owner * @param _quantities The numbers of tokens to attribute to owner */ function batchDecrementTokenOwner( address[] calldata _tokens, address _owner, uint256[] calldata _quantities ) external; /** * Transfers tokens associated with one account to another account in the vault * * @param _tokens Addresses of tokens being transferred * @param _from Address tokens being transferred from * @param _to Address tokens being transferred to * @param _quantities Amounts of tokens being transferred */ function batchTransferBalance( address[] calldata _tokens, address _from, address _to, uint256[] calldata _quantities ) external; /* * Get balance of particular contract for owner. * * @param _token The address of the ERC20 token * @param _owner The address of the token owner */ function getOwnerBalance( address _token, address _owner ) external view returns (uint256); } // File: contracts/lib/ScaleValidations.sol /* Copyright 2019 Set Labs Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ pragma solidity 0.5.7; library ScaleValidations { using SafeMath for uint256; uint256 private constant ONE_HUNDRED_PERCENT = 1e18; uint256 private constant ONE_BASIS_POINT = 1e14; function validateLessThanEqualOneHundredPercent(uint256 _value) internal view { require(_value <= ONE_HUNDRED_PERCENT, "Must be <= 100%"); } function validateMultipleOfBasisPoint(uint256 _value) internal view { require( _value.mod(ONE_BASIS_POINT) == 0, "Must be multiple of 0.01%" ); } } // File: contracts/core/tokens/rebalancing-v2/RebalancingSetState.sol /* Copyright 2019 Set Labs Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ pragma solidity 0.5.7; /** * @title RebalancingSetState * @author Set Protocol * */ contract RebalancingSetState { /* ============ State Variables ============ */ // ---------------------------------------------------------------------- // System Related // ---------------------------------------------------------------------- // Set Protocol's Core Contract ICore public core; // The Factory that created this Set IRebalancingSetFactory public factory; // Set Protocol's Vault contract IVault public vault; // The token whitelist that components are checked against during proposals IWhiteList public componentWhiteList; // WhiteList of liquidator contracts IWhiteList public liquidatorWhiteList; // Contract holding the state and logic required for rebalance liquidation // The Liquidator interacts closely with the Set during rebalances. ILiquidator public liquidator; // Contract responsible for calculation of rebalance fees IFeeCalculator public rebalanceFeeCalculator; // The account that is allowed to make proposals address public manager; // The account that receives any fees address public feeRecipient; // ---------------------------------------------------------------------- // Configuration // ---------------------------------------------------------------------- // Time in seconds that must elapsed from last rebalance to propose uint256 public rebalanceInterval; // Time in seconds after rebalanceStartTime before the Set believes the auction has failed uint256 public rebalanceFailPeriod; // Fee levied to feeRecipient every mint operation, paid during minting // Represents a decimal value scaled by 1e18 (e.g. 100% = 1e18 and 1% = 1e16) uint256 public entryFee; // ---------------------------------------------------------------------- // Current State // ---------------------------------------------------------------------- // The Set currently collateralizing the Rebalancing Set ISetToken public currentSet; // The number of currentSet per naturalUnit of the Rebalancing Set uint256 public unitShares; // The minimum issuable value of a Set uint256 public naturalUnit; // The current state of the Set (e.g. Default, Proposal, Rebalance, Drawdown) // Proposal is unused RebalancingLibrary.State public rebalanceState; // The number of rebalances in the Set's history; starts at index 0 uint256 public rebalanceIndex; // The timestamp of the last completed rebalance uint256 public lastRebalanceTimestamp; // ---------------------------------------------------------------------- // Live Rebalance State // ---------------------------------------------------------------------- // The proposal's SetToken to rebalance into ISetToken public nextSet; // The timestamp of the last rebalance was initiated at uint256 public rebalanceStartTime; // Whether a successful bid has been made during the rebalance. // In the case that the rebalance has failed, hasBidded is used // to determine whether the Set should be put into Drawdown or Default state. bool public hasBidded; // In the event a Set is put into the Drawdown state, these components // that can be withdrawn by users address[] internal failedRebalanceComponents; /* ============ Modifier ============ */ modifier onlyManager() { validateManager(); _; } /* ============ Events ============ */ event NewManagerAdded( address newManager, address oldManager ); event NewLiquidatorAdded( address newLiquidator, address oldLiquidator ); event NewEntryFee( uint256 newEntryFee, uint256 oldEntryFee ); event NewFeeRecipient( address newFeeRecipient, address oldFeeRecipient ); event EntryFeePaid( address indexed feeRecipient, uint256 feeQuantity ); event RebalanceStarted( address oldSet, address newSet, uint256 rebalanceIndex, uint256 currentSetQuantity ); event RebalanceSettled( address indexed feeRecipient, uint256 feeQuantity, uint256 feePercentage, uint256 rebalanceIndex, uint256 issueQuantity, uint256 unitShares ); /* ============ Setter Functions ============ */ /* * Set new manager address. */ function setManager( address _newManager ) external onlyManager { emit NewManagerAdded(_newManager, manager); manager = _newManager; } function setEntryFee( uint256 _newEntryFee ) external onlyManager { ScaleValidations.validateLessThanEqualOneHundredPercent(_newEntryFee); ScaleValidations.validateMultipleOfBasisPoint(_newEntryFee); emit NewEntryFee(_newEntryFee, entryFee); entryFee = _newEntryFee; } /* * Set new liquidator address. Only whitelisted addresses are valid. */ function setLiquidator( ILiquidator _newLiquidator ) external onlyManager { require( rebalanceState != RebalancingLibrary.State.Rebalance, "Invalid state" ); require( liquidatorWhiteList.whiteList(address(_newLiquidator)), "Not whitelisted" ); emit NewLiquidatorAdded(address(_newLiquidator), address(liquidator)); liquidator = _newLiquidator; } function setFeeRecipient( address _newFeeRecipient ) external onlyManager { emit NewFeeRecipient(_newFeeRecipient, feeRecipient); feeRecipient = _newFeeRecipient; } /* ============ Getter Functions ============ */ /* * Retrieves the current expected fee from the fee calculator * Value is returned as a scale decimal figure. */ function rebalanceFee() external view returns (uint256) { return rebalanceFeeCalculator.getFee(); } /* * Function for compatability with ISetToken interface. Returns currentSet. */ function getComponents() external view returns (address[] memory) { address[] memory components = new address[](1); components[0] = address(currentSet); return components; } /* * Function for compatability with ISetToken interface. Returns unitShares. */ function getUnits() external view returns (uint256[] memory) { uint256[] memory units = new uint256[](1); units[0] = unitShares; return units; } /* * Returns whether the address is the current set of the RebalancingSetToken. * Conforms to the ISetToken Interface. */ function tokenIsComponent( address _tokenAddress ) external view returns (bool) { return _tokenAddress == address(currentSet); } /* ============ Validations ============ */ function validateManager() internal view { require( msg.sender == manager, "Not manager" ); } function validateCallerIsCore() internal view { require( msg.sender == address(core), "Not Core" ); } function validateCallerIsModule() internal view { require( core.validModules(msg.sender), "Not approved module" ); } function validateRebalanceStateIs(RebalancingLibrary.State _requiredState) internal view { require( rebalanceState == _requiredState, "Invalid state" ); } function validateRebalanceStateIsNot(RebalancingLibrary.State _requiredState) internal view { require( rebalanceState != _requiredState, "Invalid state" ); } } // File: contracts/core/tokens/rebalancing-v2/BackwardCompatibility.sol /* Copyright 2019 Set Labs Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ pragma solidity 0.5.7; /** * @title BackwardCompatibility * @author Set Protocol * * This module allows full backwards compatability with RebalancingSetTokenV1. It implements * all the same getter functions to allow upstream applications to make minimized changes * to support the new version. * * The following interfaces are not included: * - propose(address, address, uint256, uint256, uint256): Implementation would have *. been a revert. * - biddingParameters: RebalancingSetToken V1 biddingParameters reverts on call */ contract BackwardCompatibility is RebalancingSetState { /* ============ Empty Variables ============ */ // Deprecated auctionLibrary. Returns 0x00 to prevent reverts address public auctionLibrary; // Deprecated proposal period. Returns 0 to prevent reverts uint256 public proposalPeriod; // Deprecated proposal start time. Returns 0 to prevent reverts uint256 public proposalStartTime; /* ============ Getters ============ */ function getAuctionPriceParameters() external view returns (uint256[] memory) { RebalancingLibrary.AuctionPriceParameters memory params = liquidator.auctionPriceParameters( address(this) ); uint256[] memory auctionPriceParams = new uint256[](4); auctionPriceParams[0] = params.auctionStartTime; auctionPriceParams[1] = params.auctionTimeToPivot; auctionPriceParams[2] = params.auctionStartPrice; auctionPriceParams[2] = params.auctionPivotPrice; return auctionPriceParams; } function getCombinedCurrentUnits() external view returns (uint256[] memory) { return liquidator.getCombinedCurrentSetUnits(address(this)); } function getCombinedNextSetUnits() external view returns (uint256[] memory) { return liquidator.getCombinedNextSetUnits(address(this)); } function getCombinedTokenArray() external view returns (address[] memory) { return liquidator.getCombinedTokenArray(address(this)); } function getCombinedTokenArrayLength() external view returns (uint256) { return liquidator.getCombinedTokenArray(address(this)).length; } function startingCurrentSetAmount() external view returns (uint256) { return liquidator.startingCurrentSets(address(this)); } function auctionPriceParameters() external view returns (RebalancingLibrary.AuctionPriceParameters memory) { return liquidator.auctionPriceParameters(address(this)); } /* * Since structs with arrays cannot be retrieved, we return * minimumBid and remainingCurrentSets separately. * * @return biddingParams Array with minimumBid and remainingCurrentSets */ function getBiddingParameters() public view returns (uint256[] memory) { uint256[] memory biddingParams = new uint256[](2); biddingParams[0] = liquidator.minimumBid(address(this)); biddingParams[1] = liquidator.remainingCurrentSets(address(this)); return biddingParams; } function biddingParameters() external view returns (uint256, uint256) { uint256[] memory biddingParams = getBiddingParameters(); return (biddingParams[0], biddingParams[1]); } function getFailedAuctionWithdrawComponents() external view returns (address[] memory) { return failedRebalanceComponents; } } // File: openzeppelin-solidity/contracts/math/Math.sol pragma solidity ^0.5.2; /** * @title Math * @dev Assorted math operations */ 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 Calculates the average of two numbers. Since these are integers, * averages of an even and odd number cannot be represented, and will be * rounded down. */ 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: contracts/lib/AddressArrayUtils.sol // Pulled in from Cryptofin Solidity package in order to control Solidity compiler version // https://github.com/cryptofinlabs/cryptofin-solidity/blob/master/contracts/array-utils/AddressArrayUtils.sol pragma solidity 0.5.7; library AddressArrayUtils { /** * Finds the index of the first occurrence of the given element. * @param A The input array to search * @param a The value to find * @return Returns (index and isIn) for the first occurrence starting from index 0 */ function indexOf(address[] memory A, address a) internal pure returns (uint256, bool) { uint256 length = A.length; for (uint256 i = 0; i < length; i++) { if (A[i] == a) { return (i, true); } } return (0, false); } /** * Returns true if the value is present in the list. Uses indexOf internally. * @param A The input array to search * @param a The value to find * @return Returns isIn for the first occurrence starting from index 0 */ function contains(address[] memory A, address a) internal pure returns (bool) { bool isIn; (, isIn) = indexOf(A, a); return isIn; } /** * Returns the combination of the two arrays * @param A The first array * @param B The second array * @return Returns A extended by B */ function extend(address[] memory A, address[] memory B) internal pure returns (address[] memory) { uint256 aLength = A.length; uint256 bLength = B.length; address[] memory newAddresses = new address[](aLength + bLength); for (uint256 i = 0; i < aLength; i++) { newAddresses[i] = A[i]; } for (uint256 j = 0; j < bLength; j++) { newAddresses[aLength + j] = B[j]; } return newAddresses; } /** * Returns the array with a appended to A. * @param A The first array * @param a The value to append * @return Returns A appended by a */ function append(address[] memory A, address a) internal pure returns (address[] memory) { address[] memory newAddresses = new address[](A.length + 1); for (uint256 i = 0; i < A.length; i++) { newAddresses[i] = A[i]; } newAddresses[A.length] = a; return newAddresses; } /** * Returns the intersection of two arrays. Arrays are treated as collections, so duplicates are kept. * @param A The first array * @param B The second array * @return The intersection of the two arrays */ function intersect(address[] memory A, address[] memory B) internal pure returns (address[] memory) { uint256 length = A.length; bool[] memory includeMap = new bool[](length); uint256 newLength = 0; for (uint256 i = 0; i < length; i++) { if (contains(B, A[i])) { includeMap[i] = true; newLength++; } } address[] memory newAddresses = new address[](newLength); uint256 j = 0; for (uint256 k = 0; k < length; k++) { if (includeMap[k]) { newAddresses[j] = A[k]; j++; } } return newAddresses; } /** * Returns the union of the two arrays. Order is not guaranteed. * @param A The first array * @param B The second array * @return The union of the two arrays */ function union(address[] memory A, address[] memory B) internal pure returns (address[] memory) { address[] memory leftDifference = difference(A, B); address[] memory rightDifference = difference(B, A); address[] memory intersection = intersect(A, B); return extend(leftDifference, extend(intersection, rightDifference)); } /** * Computes the difference of two arrays. Assumes there are no duplicates. * @param A The first array * @param B The second array * @return The difference of the two arrays */ function difference(address[] memory A, address[] memory B) internal pure returns (address[] memory) { uint256 length = A.length; bool[] memory includeMap = new bool[](length); uint256 count = 0; // First count the new length because can't push for in-memory arrays for (uint256 i = 0; i < length; i++) { address e = A[i]; if (!contains(B, e)) { includeMap[i] = true; count++; } } address[] memory newAddresses = new address[](count); uint256 j = 0; for (uint256 k = 0; k < length; k++) { if (includeMap[k]) { newAddresses[j] = A[k]; j++; } } return newAddresses; } /** * Removes specified index from array * Resulting ordering is not guaranteed * @return Returns the new array and the removed entry */ function pop(address[] memory A, uint256 index) internal pure returns (address[] memory, address) { uint256 length = A.length; address[] memory newAddresses = new address[](length - 1); for (uint256 i = 0; i < index; i++) { newAddresses[i] = A[i]; } for (uint256 j = index + 1; j < length; j++) { newAddresses[j - 1] = A[j]; } return (newAddresses, A[index]); } /** * @return Returns the new array */ function remove(address[] memory A, address a) internal pure returns (address[] memory) { (uint256 index, bool isIn) = indexOf(A, a); if (!isIn) { revert(); } else { (address[] memory _A,) = pop(A, index); return _A; } } /** * Returns whether or not there's a duplicate. Runs in O(n^2). * @param A Array to search * @return Returns true if duplicate, false otherwise */ function hasDuplicate(address[] memory A) internal pure returns (bool) { if (A.length == 0) { return false; } for (uint256 i = 0; i < A.length - 1; i++) { for (uint256 j = i + 1; j < A.length; j++) { if (A[i] == A[j]) { return true; } } } return false; } /** * Returns whether the two arrays are equal. * @param A The first array * @param B The second array * @return True is the arrays are equal, false if not. */ function isEqual(address[] memory A, address[] memory B) internal pure returns (bool) { if (A.length != B.length) { return false; } for (uint256 i = 0; i < A.length; i++) { if (A[i] != B[i]) { return false; } } return true; } } // File: contracts/lib/CommonMath.sol /* Copyright 2018 Set Labs Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ pragma solidity 0.5.7; library CommonMath { using SafeMath for uint256; uint256 public constant SCALE_FACTOR = 10 ** 18; uint256 public constant MAX_UINT_256 = 2 ** 256 - 1; /** * Returns scale factor equal to 10 ** 18 * * @return 10 ** 18 */ function scaleFactor() internal pure returns (uint256) { return SCALE_FACTOR; } /** * Calculates and returns the maximum value for a uint256 * * @return The maximum value for uint256 */ function maxUInt256() internal pure returns (uint256) { return MAX_UINT_256; } /** * Increases a value by the scale factor to allow for additional precision * during mathematical operations */ function scale( uint256 a ) internal pure returns (uint256) { return a.mul(SCALE_FACTOR); } /** * Divides a value by the scale factor to allow for additional precision * during mathematical operations */ function deScale( uint256 a ) internal pure returns (uint256) { return a.div(SCALE_FACTOR); } /** * @dev Performs the power on a specified value, reverts on overflow. */ function safePower( uint256 a, uint256 pow ) internal pure returns (uint256) { require(a > 0); uint256 result = 1; for (uint256 i = 0; i < pow; i++){ uint256 previousResult = result; // Using safemath multiplication prevents overflows result = previousResult.mul(a); } return result; } /** * Checks for rounding errors and returns value of potential partial amounts of a principal * * @param _principal Number fractional amount is derived from * @param _numerator Numerator of fraction * @param _denominator Denominator of fraction * @return uint256 Fractional amount of principal calculated */ function getPartialAmount( uint256 _principal, uint256 _numerator, uint256 _denominator ) internal pure returns (uint256) { // Get remainder of partial amount (if 0 not a partial amount) uint256 remainder = mulmod(_principal, _numerator, _denominator); // Return if not a partial amount if (remainder == 0) { return _principal.mul(_numerator).div(_denominator); } // Calculate error percentage uint256 errPercentageTimes1000000 = remainder.mul(1000000).div(_numerator.mul(_principal)); // Require error percentage is less than 0.1%. require( errPercentageTimes1000000 < 1000, "CommonMath.getPartialAmount: Rounding error exceeds bounds" ); return _principal.mul(_numerator).div(_denominator); } /* * Gets the rounded up log10 of passed value * * @param _value Value to calculate ceil(log()) on * @return uint256 Output value */ function ceilLog10( uint256 _value ) internal pure returns (uint256) { // Make sure passed value is greater than 0 require ( _value > 0, "CommonMath.ceilLog10: Value must be greater than zero." ); // Since log10(1) = 0, if _value = 1 return 0 if (_value == 1) return 0; // Calcualte ceil(log10()) uint256 x = _value - 1; uint256 result = 0; if (x >= 10 ** 64) { x /= 10 ** 64; result += 64; } if (x >= 10 ** 32) { x /= 10 ** 32; result += 32; } if (x >= 10 ** 16) { x /= 10 ** 16; result += 16; } if (x >= 10 ** 8) { x /= 10 ** 8; result += 8; } if (x >= 10 ** 4) { x /= 10 ** 4; result += 4; } if (x >= 100) { x /= 100; result += 2; } if (x >= 10) { result += 1; } return result + 1; } } // File: contracts/core/lib/SetTokenLibrary.sol /* Copyright 2018 Set Labs Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ pragma solidity 0.5.7; library SetTokenLibrary { using SafeMath for uint256; struct SetDetails { uint256 naturalUnit; address[] components; uint256[] units; } /** * Validates that passed in tokens are all components of the Set * * @param _set Address of the Set * @param _tokens List of tokens to check */ function validateTokensAreComponents( address _set, address[] calldata _tokens ) external view { for (uint256 i = 0; i < _tokens.length; i++) { // Make sure all tokens are members of the Set require( ISetToken(_set).tokenIsComponent(_tokens[i]), "SetTokenLibrary.validateTokensAreComponents: Component must be a member of Set" ); } } /** * Validates that passed in quantity is a multiple of the natural unit of the Set. * * @param _set Address of the Set * @param _quantity Quantity to validate */ function isMultipleOfSetNaturalUnit( address _set, uint256 _quantity ) external view { require( _quantity.mod(ISetToken(_set).naturalUnit()) == 0, "SetTokenLibrary.isMultipleOfSetNaturalUnit: Quantity is not a multiple of nat unit" ); } /** * Validates that passed in quantity is a multiple of the natural unit of the Set. * * @param _core Address of Core * @param _set Address of the Set */ function requireValidSet( ICore _core, address _set ) internal view { require( _core.validSets(_set), "SetTokenLibrary: Must be an approved SetToken address" ); } /** * Retrieves the Set's natural unit, components, and units. * * @param _set Address of the Set * @return SetDetails Struct containing the natural unit, components, and units */ function getSetDetails( address _set ) internal view returns (SetDetails memory) { // Declare interface variables ISetToken setToken = ISetToken(_set); // Fetch set token properties uint256 naturalUnit = setToken.naturalUnit(); address[] memory components = setToken.getComponents(); uint256[] memory units = setToken.getUnits(); return SetDetails({ naturalUnit: naturalUnit, components: components, units: units }); } } // File: contracts/core/tokens/rebalancing-v2/RebalancingSettlement.sol /* Copyright 2019 Set Labs Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ pragma solidity 0.5.7; /** * @title RebalancingSettlement * @author Set Protocol * */ contract RebalancingSettlement is ERC20, RebalancingSetState { using SafeMath for uint256; uint256 public constant SCALE_FACTOR = 10 ** 18; /* ============ Internal Functions ============ */ /* * Validates that the settle function can be called. */ function validateRebalancingSettlement() internal view { validateRebalanceStateIs(RebalancingLibrary.State.Rebalance); } /* * Issue nextSet to RebalancingSetToken; The issued Set is held in the Vault * * @param _issueQuantity Quantity of next Set to issue */ function issueNextSet( uint256 _issueQuantity ) internal { core.issueInVault( address(nextSet), _issueQuantity ); } /* * Updates state post-settlement. * * @param _nextUnitShares The new implied unit shares */ function transitionToDefault( uint256 _newUnitShares ) internal { rebalanceState = RebalancingLibrary.State.Default; lastRebalanceTimestamp = block.timestamp; currentSet = nextSet; unitShares = _newUnitShares; rebalanceIndex = rebalanceIndex.add(1); nextSet = ISetToken(address(0)); hasBidded = false; } /** * Calculate the amount of Sets to issue by using the component amounts in the * vault. */ function calculateSetIssueQuantity( ISetToken _setToken ) internal view returns (uint256) { // Collect data necessary to compute issueAmounts SetTokenLibrary.SetDetails memory setToken = SetTokenLibrary.getSetDetails(address(_setToken)); uint256 maxIssueAmount = calculateMaxIssueAmount(setToken); // Issue amount of Sets that is closest multiple of nextNaturalUnit to the maxIssueAmount // Since the initial division will round down to the nearest whole number when we multiply // by that same number we will return the closest multiple less than the maxIssueAmount uint256 issueAmount = maxIssueAmount.sub(maxIssueAmount.mod(setToken.naturalUnit)); return issueAmount; } /** * Calculates the fee and mints the rebalancing SetToken quantity to the recipient. * The minting is done without an increase to the total collateral controlled by the * rebalancing SetToken. In effect, the existing holders are paying the fee via inflation. * * @return feePercentage * @return feeQuantity */ function handleFees() internal returns (uint256, uint256) { // Represents a decimal value scaled by 1e18 (e.g. 100% = 1e18 and 1% = 1e16) uint256 feePercent = rebalanceFeeCalculator.getFee(); uint256 feeQuantity = calculateRebalanceFeeInflation(feePercent); if (feeQuantity > 0) { ERC20._mint(feeRecipient, feeQuantity); } return (feePercent, feeQuantity); } /** * Returns the new rebalance fee. The calculation for the fee involves implying * mint quantity so that the feeRecipient owns the fee percentage of the entire * supply of the Set. * * The formula to solve for fee is: * feeQuantity / feeQuantity + totalSupply = fee / scaleFactor * * The simplified formula utilized below is: * feeQuantity = fee * totalSupply / (scaleFactor - fee) * * @param _rebalanceFeePercent Fee levied to feeRecipient every rebalance, paid during settlement * @return uint256 New RebalancingSet issue quantity */ function calculateRebalanceFeeInflation( uint256 _rebalanceFeePercent ) internal view returns(uint256) { // fee * totalSupply uint256 a = _rebalanceFeePercent.mul(totalSupply()); // ScaleFactor (10e18) - fee uint256 b = SCALE_FACTOR.sub(_rebalanceFeePercent); return a.div(b); } /** * Calculates the new unitShares, defined as issueQuantity / naturalUnitsOutstanding * * @param _issueQuantity Amount of nextSets to issue * * @return uint256 New unitShares for the rebalancingSetToken */ function calculateNextSetNewUnitShares( uint256 _issueQuantity ) internal view returns (uint256) { // Calculate the amount of naturalUnits worth of rebalancingSetToken outstanding. uint256 naturalUnitsOutstanding = totalSupply().div(naturalUnit); // Divide final issueAmount by naturalUnitsOutstanding to get newUnitShares return _issueQuantity.div(naturalUnitsOutstanding); } /* ============ Private Functions ============ */ /** * Get the maximum possible issue amount of nextSet based on number of components owned by rebalancing * set token. * * @param _setToken Struct of Set Token details */ function calculateMaxIssueAmount( SetTokenLibrary.SetDetails memory _setToken ) private view returns (uint256) { uint256 maxIssueAmount = CommonMath.maxUInt256(); for (uint256 i = 0; i < _setToken.components.length; i++) { // Get amount of components in vault owned by rebalancingSetToken uint256 componentAmount = vault.getOwnerBalance( _setToken.components[i], address(this) ); // Calculate amount of Sets that can be issued from those components, if less than amount for other // components then set that as maxIssueAmount. We divide before multiplying so that we don't get // an amount that isn't a multiple of the naturalUnit uint256 componentIssueAmount = componentAmount.div(_setToken.units[i]).mul(_setToken.naturalUnit); if (componentIssueAmount < maxIssueAmount) { maxIssueAmount = componentIssueAmount; } } return maxIssueAmount; } } // File: contracts/core/tokens/rebalancing-v2/RebalancingFailure.sol /* Copyright 2019 Set Labs Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ pragma solidity 0.5.7; /** * @title RebalancingFailure * @author Set Protocol * */ contract RebalancingFailure is RebalancingSetState, RebalancingSettlement { using SafeMath for uint256; using AddressArrayUtils for address[]; /* ============ Internal Functions ============ */ /* * Validations for failRebalance: * - State is Rebalance * - Either liquidator recognizes failure OR fail period breached on RB Set * * @param _quantity The amount of currentSet to be rebalanced */ function validateFailRebalance() internal view { // Token must be in Rebalance State validateRebalanceStateIs(RebalancingLibrary.State.Rebalance); // Failure triggers must be met require( liquidatorBreached() || failPeriodBreached(), "Triggers not breached" ); } /* * Determine the new Rebalance State. If there has been a bid, then we put it to * Drawdown, where the Set is effectively killed. If no bids, we reissue the currentSet. */ function getNewRebalanceState() internal view returns (RebalancingLibrary.State) { return hasBidded ? RebalancingLibrary.State.Drawdown : RebalancingLibrary.State.Default; } /* * Update state based on new Rebalance State. * * @param _newRebalanceState The new State to transition to */ function transitionToNewState( RebalancingLibrary.State _newRebalanceState ) internal { reissueSetIfRevertToDefault(_newRebalanceState); setWithdrawComponentsIfDrawdown(_newRebalanceState); rebalanceState = _newRebalanceState; rebalanceIndex = rebalanceIndex.add(1); lastRebalanceTimestamp = block.timestamp; nextSet = ISetToken(address(0)); hasBidded = false; } /* ============ Private Functions ============ */ /* * Returns whether the liquidator believes the rebalance has failed. * * @return If liquidator thinks rebalance failed */ function liquidatorBreached() private view returns (bool) { return liquidator.hasRebalanceFailed(address(this)); } /* * Returns whether the the fail time has elapsed, which means that a period * of time where the auction should have succeeded has not. * * @return If fail period has passed on Rebalancing Set Token */ function failPeriodBreached() private view returns(bool) { uint256 rebalanceFailTime = rebalanceStartTime.add(rebalanceFailPeriod); return block.timestamp >= rebalanceFailTime; } /* * If the determination is Default State, reissue the Set. */ function reissueSetIfRevertToDefault( RebalancingLibrary.State _newRebalanceState ) private { if (_newRebalanceState == RebalancingLibrary.State.Default) { uint256 issueQuantity = calculateSetIssueQuantity(currentSet); // If bid not placed, reissue current Set core.issueInVault( address(currentSet), issueQuantity ); } } /* * If the determination is Drawdown State, set the drawdown components which is the union of * the current and next Set components. */ function setWithdrawComponentsIfDrawdown( RebalancingLibrary.State _newRebalanceState ) private { if (_newRebalanceState == RebalancingLibrary.State.Drawdown) { address[] memory currentSetComponents = currentSet.getComponents(); address[] memory nextSetComponents = nextSet.getComponents(); failedRebalanceComponents = currentSetComponents.union(nextSetComponents); } } } // File: contracts/core/tokens/rebalancing-v2/Issuance.sol /* Copyright 2019 Set Labs Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ pragma solidity 0.5.7; /** * @title Issuance * @author Set Protocol * * Default implementation of Rebalancing Set Token propose function */ contract Issuance is ERC20, RebalancingSetState { using SafeMath for uint256; using CommonMath for uint256; /* ============ Internal Functions ============ */ /* * Validate call to mint new Rebalancing Set Token * * - Make sure caller is Core * - Make sure state is not Rebalance or Drawdown */ function validateMint() internal view { validateCallerIsCore(); validateRebalanceStateIs(RebalancingLibrary.State.Default); } /* * Validate call to burn Rebalancing Set Token * * - Make sure state is not Rebalance or Drawdown * - Make sure sender is module when in drawdown, core otherwise */ function validateBurn() internal view { validateRebalanceStateIsNot(RebalancingLibrary.State.Rebalance); if (rebalanceState == RebalancingLibrary.State.Drawdown) { // In Drawdown Sets can only be burned as part of the withdrawal process validateCallerIsModule(); } else { // When in non-Rebalance or Drawdown state, check that function caller is Core // so that Sets can be redeemed validateCallerIsCore(); } } /* * Calculates entry fees and mints the feeRecipient a portion of the issue quantity. * * @param _quantity The number of rebalancing SetTokens the issuer mints * @return issueQuantityNetOfFees Quantity of rebalancing SetToken to mint issuer net of fees */ function handleEntryFees( uint256 _quantity ) internal returns(uint256) { // The entryFee is a scaled decimal figure by 10e18. We multiply the fee by the quantity // Then descale by 10e18 uint256 fee = _quantity.mul(entryFee).deScale(); if (fee > 0) { ERC20._mint(feeRecipient, fee); emit EntryFeePaid(feeRecipient, fee); } // Return the issue quantity less fees return _quantity.sub(fee); } } // File: contracts/core/tokens/rebalancing-v2/RebalancingBid.sol /* Copyright 2019 Set Labs Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ pragma solidity 0.5.7; /** * @title RebalancingBid * @author Set Protocol * * Implementation of Rebalancing Set Token V2 bidding-related functionality. */ contract RebalancingBid is RebalancingSetState { using SafeMath for uint256; /* ============ Internal Functions ============ */ /* * Validates conditions to retrieve a Bid Price: * - State is Rebalance * - Quanity is greater than zero * * @param _quantity The amount of currentSet to be rebalanced */ function validateGetBidPrice( uint256 _quantity ) internal view { validateRebalanceStateIs(RebalancingLibrary.State.Rebalance); require( _quantity > 0, "Bid not > 0" ); } /* * Validations for placeBid: * - Module is sender * - getBidPrice validations * * @param _quantity The amount of currentSet to be rebalanced */ function validatePlaceBid( uint256 _quantity ) internal view { validateCallerIsModule(); validateGetBidPrice(_quantity); } /* * If a successful bid has been made, flip the hasBidded boolean. */ function updateHasBiddedIfNecessary() internal { if (!hasBidded) { hasBidded = true; } } } // File: contracts/core/tokens/rebalancing-v2/RebalancingStart.sol /* Copyright 2019 Set Labs Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ pragma solidity 0.5.7; /** * @title RebalancingStart * @author Set Protocol * * Implementation of Rebalancing Set Token V2 start rebalance functionality */ contract RebalancingStart is RebalancingSetState { using SafeMath for uint256; /* ============ Internal Functions ============ */ /** * Validate that start rebalance can be called: * - Current state is Default * - rebalanceInterval has elapsed * - Proposed set is valid in Core * - Components in set are all valid * - NaturalUnits are multiples of each other * * @param _nextSet The Set to rebalance into */ function validateStartRebalance( ISetToken _nextSet ) internal view { validateRebalanceStateIs(RebalancingLibrary.State.Default); // Enough time must have passed from last rebalance to start a new proposal require( block.timestamp >= lastRebalanceTimestamp.add(rebalanceInterval), "Interval not elapsed" ); // New proposed Set must be a valid Set created by Core require( core.validSets(address(_nextSet)), "Invalid Set" ); // Check proposed components on whitelist. This is to ensure managers are unable to add contract addresses // to a propose that prohibit the set from carrying out an auction i.e. a token that only the manager possesses require( componentWhiteList.areValidAddresses(_nextSet.getComponents()), "Invalid component" ); // Check that the proposed set natural unit is a multiple of current set natural unit, or vice versa. // Done to make sure that when calculating token units there will are be rounding errors. require( naturalUnitsAreValid(currentSet, _nextSet), "Invalid natural unit" ); } /** * Calculates the maximum quantity of the currentSet that can be redeemed. This is defined * by how many naturalUnits worth of the Set there are. * * @return Maximum quantity of the current Set that can be redeemed */ function calculateStartingSetQuantity() internal view returns (uint256) { uint256 currentSetBalance = vault.getOwnerBalance(address(currentSet), address(this)); uint256 currentSetNaturalUnit = currentSet.naturalUnit(); // Rounds the redemption quantity to a multiple of the current Set natural unit return currentSetBalance.sub(currentSetBalance.mod(currentSetNaturalUnit)); } /** * Signals to the Liquidator to initiate the rebalance. * * @param _nextSet Next set instance * @param _startingCurrentSetQuantity Amount of currentSets the rebalance is initiated with * @param _liquidatorData Bytecode formatted data with liquidator-specific arguments */ function liquidatorRebalancingStart( ISetToken _nextSet, uint256 _startingCurrentSetQuantity, bytes memory _liquidatorData ) internal { liquidator.startRebalance( currentSet, _nextSet, _startingCurrentSetQuantity, _liquidatorData ); } /** * Updates rebalance-related state parameters. * * @param _nextSet The Set to rebalance into */ function transitionToRebalance(ISetToken _nextSet) internal { nextSet = _nextSet; rebalanceState = RebalancingLibrary.State.Rebalance; rebalanceStartTime = block.timestamp; } /* ============ Private Functions ============ */ /** * Check that the proposed set natural unit is a multiple of current set natural unit, or vice versa. * Done to make sure that when calculating token units there will be no rounding errors. * * @param _currentSet The current base SetToken * @param _nextSet The proposed SetToken */ function naturalUnitsAreValid( ISetToken _currentSet, ISetToken _nextSet ) private view returns (bool) { uint256 currentNaturalUnit = _currentSet.naturalUnit(); uint256 nextSetNaturalUnit = _nextSet.naturalUnit(); return Math.max(currentNaturalUnit, nextSetNaturalUnit).mod( Math.min(currentNaturalUnit, nextSetNaturalUnit) ) == 0; } } // File: contracts/core/tokens/RebalancingSetTokenV2.sol /* Copyright 2019 Set Labs Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ pragma solidity 0.5.7; /** * @title RebalancingSetTokenV2 * @author Set Protocol * * Implementation of Rebalancing Set token V2. Major improvements vs. V1 include: * - Decouple the Rebalancing Set state and rebalance state from the rebalance execution (e.g. auction) * This allows us to rapidly iterate and build new liquidation mechanisms for rebalances. * - Proposals are removed in favor of starting an auction directly. * - The Set retains ability to fail an auction if the minimum fail time has elapsed. * - RebalanceAuctionModule execution should be backwards compatible with V1. * - Bidding and auction parameters state no longer live on this contract. They live on the liquidator * BackwardsComptability is used to allow retrieving of previous supported states. * - Introduces entry and rebalance fees, where rebalance fees are configurable based on an external * fee calculator contract */ contract RebalancingSetTokenV2 is ERC20, ERC20Detailed, Initializable, RebalancingSetState, BackwardCompatibility, Issuance, RebalancingStart, RebalancingBid, RebalancingSettlement, RebalancingFailure { /* ============ Constructor ============ */ /** * Constructor function for Rebalancing Set Token * * addressConfig [factory, manager, liquidator, initialSet, componentWhiteList, * liquidatorWhiteList, feeRecipient, rebalanceFeeCalculator] * [0]factory Factory used to create the Rebalancing Set * [1]manager Address that is able to propose the next Set * [2]liquidator Address of the liquidator contract * [3]initialSet Initial set that collateralizes the Rebalancing set * [4]componentWhiteList Whitelist that nextSet components are checked against during propose * [5]liquidatorWhiteList Whitelist of valid liquidators * [6]feeRecipient Address that receives any incentive fees * [7]rebalanceFeeCalculator Address to retrieve rebalance fee during settlement * * uintConfig [initialUnitShares, naturalUnit, rebalanceInterval, rebalanceFailPeriod, * lastRebalanceTimestamp, entryFee] * [0]initialUnitShares Units of currentSet that equals one share * [1]naturalUnit The minimum multiple of Sets that can be issued or redeemed * [2]rebalanceInterval: Minimum amount of time between rebalances * [3]rebalanceFailPeriod: Time after auctionStart where something in the rebalance has gone wrong * [4]lastRebalanceTimestamp: Time of the last rebalance; Allows customized deployments * [5]entryFee: Mint fee represented in a scaled decimal value (e.g. 100% = 1e18, 1% = 1e16) * * @param _addressConfig List of configuration addresses * @param _uintConfig List of uint addresses * @param _name The name of the new RebalancingSetTokenV2 * @param _symbol The symbol of the new RebalancingSetTokenV2 */ constructor( address[8] memory _addressConfig, uint256[6] memory _uintConfig, string memory _name, string memory _symbol ) public ERC20Detailed( _name, _symbol, 18 ) { factory = IRebalancingSetFactory(_addressConfig[0]); manager = _addressConfig[1]; liquidator = ILiquidator(_addressConfig[2]); currentSet = ISetToken(_addressConfig[3]); componentWhiteList = IWhiteList(_addressConfig[4]); liquidatorWhiteList = IWhiteList(_addressConfig[5]); feeRecipient = _addressConfig[6]; rebalanceFeeCalculator = IFeeCalculator(_addressConfig[7]); unitShares = _uintConfig[0]; naturalUnit = _uintConfig[1]; rebalanceInterval = _uintConfig[2]; rebalanceFailPeriod = _uintConfig[3]; lastRebalanceTimestamp = _uintConfig[4]; entryFee = _uintConfig[5]; core = ICore(factory.core()); vault = IVault(core.vault()); rebalanceState = RebalancingLibrary.State.Default; } /* * Intended to be called during creation by the RebalancingSetTokenFactory. Can only be initialized * once. This implementation initializes the rebalance fee. * * * @param _rebalanceFeeCalldata Bytes encoded rebalance fee represented as a scaled percentage value */ function initialize( bytes calldata _rebalanceFeeCalldata ) external initializer { rebalanceFeeCalculator.initialize(_rebalanceFeeCalldata); } /* ============ External Functions ============ */ /* * Initiates the rebalance in coordination with the Liquidator contract. * In this step, we redeem the currentSet and pass relevant information * to the liquidator. * * @param _nextSet The Set to rebalance into * @param _liquidatorData Bytecode formatted data with liquidator-specific arguments * * Can only be called if the rebalance interval has elapsed. * Can only be called by manager. */ function startRebalance( ISetToken _nextSet, bytes calldata _liquidatorData ) external onlyManager { RebalancingStart.validateStartRebalance(_nextSet); uint256 startingCurrentSetQuantity = RebalancingStart.calculateStartingSetQuantity(); core.redeemInVault(address(currentSet), startingCurrentSetQuantity); RebalancingStart.liquidatorRebalancingStart(_nextSet, startingCurrentSetQuantity, _liquidatorData); RebalancingStart.transitionToRebalance(_nextSet); emit RebalanceStarted( address(currentSet), address(nextSet), rebalanceIndex, startingCurrentSetQuantity ); } /* * Get token inflows and outflows required for bid from the Liquidator. * * @param _quantity The amount of currentSet to be rebalanced * @return inflowUnitArray Array of amount of tokens inserted into system in bid * @return outflowUnitArray Array of amount of tokens taken out of system in bid */ function getBidPrice( uint256 _quantity ) public view returns (uint256[] memory, uint256[] memory) { RebalancingBid.validateGetBidPrice(_quantity); return Rebalance.decomposeTokenFlowToBidPrice( liquidator.getBidPrice(address(this), _quantity) ); } /* * Place bid during rebalance auction. * * The intended caller is the RebalanceAuctionModule, which must be approved by Core. * Call Flow: * RebalanceAuctionModule -> RebalancingSetTokenV2 -> Liquidator * * @param _quantity The amount of currentSet to be rebalanced * @return combinedTokenArray Array of token addresses invovled in rebalancing * @return inflowUnitArray Array of amount of tokens inserted into system in bid * @return outflowUnitArray Array of amount of tokens taken out of system in bid */ function placeBid( uint256 _quantity ) external returns (address[] memory, uint256[] memory, uint256[] memory) { RebalancingBid.validatePlaceBid(_quantity); // Place bid and get back inflow and outflow arrays Rebalance.TokenFlow memory tokenFlow = liquidator.placeBid(_quantity); RebalancingBid.updateHasBiddedIfNecessary(); return Rebalance.decomposeTokenFlow(tokenFlow); } /* * After a successful rebalance, the new Set is issued. If there is a rebalance fee, * the fee is paid via inflation of the Rebalancing Set to the feeRecipient. * Full issuance functionality is now returned to set owners. * * Anyone can call this function. */ function settleRebalance() external { RebalancingSettlement.validateRebalancingSettlement(); uint256 issueQuantity = RebalancingSettlement.calculateSetIssueQuantity(nextSet); // Calculates fees and mints Rebalancing Set to the feeRecipient, increasing supply (uint256 feePercent, uint256 feeQuantity) = RebalancingSettlement.handleFees(); uint256 newUnitShares = RebalancingSettlement.calculateNextSetNewUnitShares(issueQuantity); // The unit shares must result in a quantity greater than the number of natural units outstanding require( newUnitShares > 0, "Failed: unitshares is 0." ); RebalancingSettlement.issueNextSet(issueQuantity); liquidator.settleRebalance(); // Rebalance index is the current vs next rebalance emit RebalanceSettled( feeRecipient, feeQuantity, feePercent, rebalanceIndex, issueQuantity, newUnitShares ); RebalancingSettlement.transitionToDefault(newUnitShares); } /* * Ends a rebalance if there are any signs that there is a failure. * Possible failure reasons: * 1. The rebalance has elapsed the failRebalancePeriod * 2. The liquidator responds that the rebalance has failed * * Move to Drawdown state if bids have been placed. Reset to Default state if no bids placed. */ function endFailedRebalance() public { RebalancingFailure.validateFailRebalance(); RebalancingLibrary.State newRebalanceState = RebalancingFailure.getNewRebalanceState(); liquidator.endFailedRebalance(); RebalancingFailure.transitionToNewState(newRebalanceState); } /* * Mint set token for given address. If there if is an entryFee, calculates the fee and mints * the rebalancing SetToken to the feeRecipient. * * Can only be called by Core contract. * * @param _issuer The address of the issuing account * @param _quantity The number of sets to attribute to issuer */ function mint( address _issuer, uint256 _quantity ) external { Issuance.validateMint(); uint256 issueQuantityNetOfFees = Issuance.handleEntryFees(_quantity); ERC20._mint(_issuer, issueQuantityNetOfFees); } /* * Burn set token for given address. Can only be called by authorized contracts. * * @param _from The address of the redeeming account * @param _quantity The number of sets to burn from redeemer */ function burn( address _from, uint256 _quantity ) external { Issuance.validateBurn(); ERC20._burn(_from, _quantity); } /* ============ Backwards Compatability ============ */ /* * Alias for endFailedRebalance */ function endFailedAuction() external { endFailedRebalance(); } } // File: contracts/core/tokens/RebalancingSetTokenV2Factory.sol /* Copyright 2019 Set Labs Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ pragma solidity 0.5.7; /** * @title RebalancingSetTokenV2Factory * @author Set Protocol * * RebalancingSetTokenV2Factory is a smart contract used to deploy new RebalancingSetTokenV2 contracts. * RebalancingSetTokenV2s deployed by the factory can only have their mint and burn functions * called by Core */ contract RebalancingSetTokenV2Factory { using LibBytes for bytes; using Bytes32Library for bytes32; /* ============ State Variables ============ */ // Address of the Core contract used to verify factory when creating a Set ICore public core; // Address of the WhiteList contract used to verify the tokens in a rebalance proposal IWhiteList public rebalanceComponentWhitelist; // Whitelist contract for approved liquidators IWhiteList public liquidatorWhitelist; // Whitelist contract for approved fee calcualtors IWhiteList public feeCalculatorWhitelist; // Minimum amount of time between rebalances in seconds uint256 public minimumRebalanceInterval; // Minimum fail auction period uint256 public minimumFailRebalancePeriod; // Maximum fail auction period uint256 public maximumFailRebalancePeriod; // Minimum number for the token natural unit // The bounds are used for calculations of unitShares and in settlement uint256 public minimumNaturalUnit; // Maximum number for the token natural unit uint256 public maximumNaturalUnit; // ============ Structs ============ struct InitRebalancingParameters { address manager; ILiquidator liquidator; address feeRecipient; address rebalanceFeeCalculator; uint256 rebalanceInterval; uint256 rebalanceFailPeriod; uint256 lastRebalanceTimestamp; uint256 entryFee; bytes rebalanceFeeCalculatorData; } /* ============ Constructor ============ */ /** * Set core. Also requires a minimum rebalance interval and minimum proposal periods that are enforced * on RebalancingSetTokenV2 * * @param _core Address of deployed core contract * @param _componentWhitelist Address of component whitelist contract * @param _liquidatorWhitelist Address of liquidator whitelist contract * @param _feeCalculatorWhitelist Address of feeCalculator whitelist contract * @param _minimumRebalanceInterval Minimum amount of time between rebalances in seconds * @param _minimumNaturalUnit Minimum number for the token natural unit * @param _maximumNaturalUnit Maximum number for the token natural unit */ constructor( ICore _core, IWhiteList _componentWhitelist, IWhiteList _liquidatorWhitelist, IWhiteList _feeCalculatorWhitelist, uint256 _minimumRebalanceInterval, uint256 _minimumFailRebalancePeriod, uint256 _maximumFailRebalancePeriod, uint256 _minimumNaturalUnit, uint256 _maximumNaturalUnit ) public { core = _core; rebalanceComponentWhitelist = _componentWhitelist; liquidatorWhitelist = _liquidatorWhitelist; feeCalculatorWhitelist = _feeCalculatorWhitelist; minimumRebalanceInterval = _minimumRebalanceInterval; minimumFailRebalancePeriod = _minimumFailRebalancePeriod; maximumFailRebalancePeriod = _maximumFailRebalancePeriod; minimumNaturalUnit = _minimumNaturalUnit; maximumNaturalUnit = _maximumNaturalUnit; } /* ============ External Functions ============ */ /** * Deploys a new RebalancingSetTokenV2 contract, conforming to IFactory * Can only be called by core contracts. * * * | CallData | Location | * |----------------------------|-------------------------------| * | manager | 32 | * | liquidator | 64 | * | feeRecipient | 96 | * | rebalanceFeeCalculator | 128 | * | rebalanceInterval | 160 | * | rebalanceFailPeriod | 192 | * | entryFee | 224 | * | rebalanceFeeCalculatorData | 256 to end | * * @param _components The address of component tokens * @param _units The units of each component token * -- Unused natural unit parameters, passed in to conform to IFactory -- * @param _name The bytes32 encoded name of the new RebalancingSetTokenV2 * @param _symbol The bytes32 encoded symbol of the new RebalancingSetTokenV2 * @param _callData Byte string containing additional call parameters * * @return setToken The address of the newly created SetToken */ function createSet( address[] calldata _components, uint256[] calldata _units, uint256 _naturalUnit, bytes32 _name, bytes32 _symbol, bytes calldata _callData ) external returns (address) { require( msg.sender == address(core), "Sender must be core" ); // Ensure component array only includes one address which will be the currentSet require( _components.length == 1 && _units.length == 1, "Components & units must be len 1" ); require( _units[0] > 0, "UnitShares not > 0" ); address startingSet = _components[0]; // Expect Set to rebalance to be valid and enabled Set require( core.validSets(startingSet), "Invalid SetToken" ); require( _naturalUnit >= minimumNaturalUnit && _naturalUnit <= maximumNaturalUnit, "Invalid natural unit" ); InitRebalancingParameters memory parameters = parseRebalanceSetCallData(_callData); require( parameters.manager != address(0), "Invalid manager" ); // Require liquidator address is non-zero and is whitelisted by the liquidatorWhitelist require( address(parameters.liquidator) != address(0) && liquidatorWhitelist.whiteList(address(parameters.liquidator)), "Invalid liquidator" ); // Require rebalance fee is whitelisted by the liquidatorWhitelist require( feeCalculatorWhitelist.whiteList(address(parameters.rebalanceFeeCalculator)), "Invalid fee calculator" ); require( parameters.rebalanceInterval >= minimumRebalanceInterval, "Rebalance interval too short" ); require( parameters.rebalanceFailPeriod >= minimumFailRebalancePeriod && parameters.rebalanceFailPeriod <= maximumFailRebalancePeriod, "Invalid Fail Period" ); require( parameters.lastRebalanceTimestamp <= block.timestamp, "Invalid RebalanceTimestamp" ); address rebalancingSet = address( new RebalancingSetTokenV2( [ address(this), // factory parameters.manager, // manager address(parameters.liquidator), // liquidator startingSet, // initialSet address(rebalanceComponentWhitelist), // componentWhiteList address(liquidatorWhitelist), // liquidatorWhiteList parameters.feeRecipient, // feeRecipient parameters.rebalanceFeeCalculator // rebalanceFeeCalculator ], [ _units[0], // unitShares _naturalUnit, // naturalUnit parameters.rebalanceInterval, // rebalanceInterval parameters.rebalanceFailPeriod, // rebalanceFailPeriod parameters.lastRebalanceTimestamp, // lastRebalanceTimestamp parameters.entryFee // entryFee ], _name.bytes32ToString(), _symbol.bytes32ToString() ) ); // Initaializes the RebalancingSetToken IRebalancingSetTokenV2(rebalancingSet).initialize(parameters.rebalanceFeeCalculatorData); return rebalancingSet; } /* ============ Private Functions ============ */ function parseRebalanceSetCallData( bytes memory _callData ) private pure returns (InitRebalancingParameters memory) { InitRebalancingParameters memory parameters; assembly { mstore(parameters, mload(add(_callData, 32))) // manager mstore(add(parameters, 32), mload(add(_callData, 64))) // liquidator mstore(add(parameters, 64), mload(add(_callData, 96))) // feeRecipient mstore(add(parameters, 96), mload(add(_callData, 128))) // rebalanceFeeCalculator mstore(add(parameters, 128), mload(add(_callData, 160))) // rebalanceInterval mstore(add(parameters, 160), mload(add(_callData, 192))) // rebalanceFailPeriod mstore(add(parameters, 192), mload(add(_callData, 224))) // lastRebalanceTimestamp mstore(add(parameters, 224), mload(add(_callData, 256))) // entryFee } // Extracts the fee calculator data from the remaining calldata parameters.rebalanceFeeCalculatorData = _callData.slice(256, _callData.length); return parameters; } }
Returns whether the liquidator believes the rebalance has failed. return If liquidator thinks rebalance failed/
function liquidatorBreached() private view returns (bool) { return liquidator.hasRebalanceFailed(address(this)); }
6,405,745
pragma solidity >=0.5.0; pragma experimental ABIEncoderV2; /// @title Multicall2 - Aggregate results from multiple read-only function calls. Allow failures /// @author Michael Elliot <[email protected]> /// @author Joshua Levine <[email protected]> /// @author Nick Johnson <[email protected]> /// @author Bryan Stitt <[email protected]> contract Multicall2 { struct Call { address target; bytes callData; } struct Result { bool success; bytes returnData; } // Multiple calls in one! (Replaced by block_and_aggregate and try_block_and_aggregate) // Reverts if any call fails. function aggregate(Call[] memory calls) public returns (uint256 blockNumber, bytes[] memory returnData) { blockNumber = block.number; returnData = new bytes[](calls.length); for(uint256 i = 0; i < calls.length; i++) { // we use low level calls to intionally allow calling arbitrary functions. // solium-disable-next-line security/no-low-level-calls (bool success, bytes memory ret) = calls[i].target.call(calls[i].callData); require(success, "Multicall2 aggregate: call failed"); returnData[i] = ret; } } // Multiple calls in one! // Reverts if any call fails. // Use when you are querying the latest block and need all the calls to succeed. // Check the hash to protect yourself from re-orgs! function block_and_aggregate(Call[] memory calls) public returns (uint256 blockNumber, bytes32 blockHash, Result[] memory returnData) { (blockNumber, blockHash, returnData) = try_block_and_aggregate(true, calls); } // Multiple calls in one! // If `require_success == true`, this revert if a call fails. // If `require_success == false`, failures are allowed. Check the success bool before using the returnData. // Use when you are querying the latest block. // Returns the block and hash so you can protect yourself from re-orgs. function try_block_and_aggregate(bool require_success, Call[] memory calls) public returns (uint256 blockNumber, bytes32 blockHash, Result[] memory returnData) { blockNumber = block.number; blockHash = blockhash(blockNumber); returnData = try_aggregate(require_success, calls); } // Multiple calls in one! // If `require_success == true`, this revert if a call fails. // If `require_success == false`, failures are allowed. Check the success bool before using the returnData. // Use when you are querying a specific block number and hash. function try_aggregate(bool require_success, Call[] memory calls) public returns (Result[] memory returnData) { returnData = new Result[](calls.length); for(uint256 i = 0; i < calls.length; i++) { // we use low level calls to intionally allow calling arbitrary functions. // solium-disable-next-line security/no-low-level-calls (bool success, bytes memory ret) = calls[i].target.call(calls[i].callData); if (require_success) { // TODO: give a more useful message about specifically which call failed require(success, "Multicall2 aggregate: call failed"); } returnData[i] = Result(success, ret); } } // Helper functions function getBlockHash() public view returns (bytes32 blockHash) { blockHash = blockhash(block.number); } function getBlockNumber() public view returns (uint256 blockNumber) { blockNumber = block.number; } function getCurrentBlockCoinbase() public view returns (address coinbase) { coinbase = block.coinbase; } function getCurrentBlockDifficulty() public view returns (uint256 difficulty) { difficulty = block.difficulty; } function getCurrentBlockGasLimit() public view returns (uint256 gaslimit) { gaslimit = block.gaslimit; } function getCurrentBlockTimestamp() public view returns (uint256 timestamp) { // solium-disable-next-line security/no-block-members timestamp = block.timestamp; } function getEthBalance(address addr) public view returns (uint256 balance) { balance = addr.balance; } function getLastBlockHash() public view returns (bytes32 blockHash) { blockHash = blockhash(block.number - 1); } }
Multiple calls in one! (Replaced by block_and_aggregate and try_block_and_aggregate) Reverts if any call fails. we use low level calls to intionally allow calling arbitrary functions. solium-disable-next-line security/no-low-level-calls
function aggregate(Call[] memory calls) public returns (uint256 blockNumber, bytes[] memory returnData) { blockNumber = block.number; returnData = new bytes[](calls.length); for(uint256 i = 0; i < calls.length; i++) { (bool success, bytes memory ret) = calls[i].target.call(calls[i].callData); require(success, "Multicall2 aggregate: call failed"); returnData[i] = ret; } }
7,292,135
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /* import "Initiative_Legislative_lib.sol"; import "Register.sol"; import "Citizens_Register.sol"; import "IVote.sol"; import "IDelegation.sol"; */ import "contracts/Initiative_Legislative_lib.sol"; import "contracts/Register.sol"; import "contracts/Citizens_Register.sol"; import "contracts/IVote.sol"; import "contracts/IDelegation.sol"; /** * @notice Delegation_Uils library is used to reduce the size of Delegation contract in order to avoid to exceed contract limit size. It contains heavy functions and data structures. */ library Delegation_Uils{ using EnumerableSet for EnumerableSet.AddressSet; /** * @dev Parameters related to the democratic process of registers governance. * - Member_Max_Token_Usage: The maximum amount of token a member is allowed to use for a specific law project elaboration * - Law_Initialisation_Price: The price in token for creating a law project * - FunctionCall_Price: The price in token for one FunctionCall. * - Proposition_Duration: The duration of the stage in which members are allowed to submit propositions * - Vote_Duration: The duration of the stage in which members are allowed to vote for the proposition they want * - Law_Censor_Period_Duration: The duration of the stage in which all citizens are allowed to sign a etition against the law project proposed by the Delegation * - Censor_Proposition_Petition_Rate The minimum ratio of citizens required to cancel a law project * - Censor_Penalty_Rate The amount of token the delegation will lost if their law project is rejected by citizens * - Ivote_address Address of the IVote contract that will be used during voting stage */ struct Law_Project_Parameters{ uint Member_Max_Token_Usage; uint Law_Initialisation_Price; uint FunctionCall_Price; uint Proposition_Duration; uint Vote_Duration; uint Law_Censor_Period_Duration; uint16 Censor_Proposition_Petition_Rate; uint16 Censor_Penalty_Rate; address Ivote_address; } /** * @dev Structure reresenting parameters related to the democratic process of registers governance. * - Election_Duration Duration of the stage in which citizens are allowed to vote for Candidats they prefer * - Validation_Duration Duration of the stage in which citizens can validate their hased vote by revealing their choice and the salt that has been used for hasing * - Mandate_Duration Duration of a delegation mandate * - Immunity_Duration Amount of time after the beginning of a new mandate during which delegation's members can't be revoked * - Next_Mandate_Max_Members Maximum number of members in the delegation. * - New_Election_Petition_Rate The minimum ratio of citizens required to revoke the current delegation's members and start a new election * - Ivote_address Address of the IVote contract that will be used during election stage */ struct Mandate_Parameter{ uint Election_Duration; uint Validation_Duration; uint Mandate_Duration; uint Immunity_Duration; uint16 Next_Mandate_Max_Members; uint16 New_Election_Petition_Rate; address Ivote_address; } /** * @dev Structure representing a mandate. * - Members Duration : List of members of the delegation * - New_Election_Petitions: List of citizens who have signed petition for revoking the current delegation's members. * - Next_Mandate_Candidats: List of accounts that are candidates for the next election * - Inauguration_Timestamps: Beginning of current mandate * - Election_Timestamps: Beginning of election * - Version: Version of parameters (Id of {Mandate_Parameter} object) used by this mandate */ struct Mandate{ EnumerableSet.AddressSet Members; EnumerableSet.AddressSet New_Election_Petitions; EnumerableSet.AddressSet Next_Mandate_Candidats; uint Inauguration_Timestamps; uint Election_Timestamps; uint Version; } event Governance_Parameters_Updated(); event Legislatif_Parameters_Updated(); event New_Candidat(address Candidat); event Remove_Candidat(address Candidat); event Sign(); event New_election(bytes32 Vote_key); event New_Mandate(); ///@dev Function used for updating parameters related to the democratic process of rmembers election. See {Update_Internal_Governance] function of {Delegation} or {IDelegation} contract function Update_Mandate_Parameter(Mandate_Parameter storage mandate_param, uint Election_Duration, uint Validation_Duration, uint Mandate_Duration, uint Immunity_Duration, uint16 Next_Mandate_Max_Members, uint16 New_Election_Petition_Rate, address Ivote_address) external { mandate_param.Election_Duration = Election_Duration; mandate_param.Validation_Duration = Validation_Duration; mandate_param.Mandate_Duration = Mandate_Duration; mandate_param.Immunity_Duration = Immunity_Duration; mandate_param.Next_Mandate_Max_Members = Next_Mandate_Max_Members; mandate_param.New_Election_Petition_Rate = New_Election_Petition_Rate; mandate_param.Ivote_address = Ivote_address; emit Governance_Parameters_Updated(); } ///@dev Function used for updating parameters related to the democratic process of registers governance. See {Update_Legislatif_Process] function of {Delegation} or {IDelegation} contract function Update_Law_Parameters(Law_Project_Parameters storage projet_param, uint[6] calldata Uint256_Legislatifs_Arg, uint16 Censor_Proposition_Petition_Rate, uint16 Censor_Penalty_Rate, address Ivote_address) external { projet_param.Member_Max_Token_Usage = Uint256_Legislatifs_Arg[0]; projet_param.Law_Initialisation_Price = Uint256_Legislatifs_Arg[1]; projet_param.FunctionCall_Price = Uint256_Legislatifs_Arg[2]; projet_param.Proposition_Duration = Uint256_Legislatifs_Arg[3]; projet_param.Vote_Duration = Uint256_Legislatifs_Arg[4]; projet_param.Law_Censor_Period_Duration = Uint256_Legislatifs_Arg[5]; projet_param.Censor_Proposition_Petition_Rate = Censor_Proposition_Petition_Rate; projet_param.Censor_Penalty_Rate = Censor_Penalty_Rate; projet_param.Ivote_address = Ivote_address; emit Legislatif_Parameters_Updated(); } /** * @dev Function called by {End_Election} function of {Delegation} Contract to end the current contract and start a new one. * @param Mandates mapping of Mandate structure idexed by uint corresponding to their order of apparition * @param ivote_address Address of IVote contract used by citizens to vote during election. * @param last_mandate_num Index in {Mandates} mapping of the last mandate * @param Internal_Governance_Version Version of Parameters ({Mandate_Parameter} structur) u.sed by the current mandate * */ function Transition_Mandate(mapping (uint=>Mandate) storage Mandates, address ivote_address, uint last_mandate_num, uint Internal_Governance_Version) external{ uint new_mandate_num=last_mandate_num+1; uint[] memory results; IVote Vote_Instance = IVote(ivote_address); results = Vote_Instance.Get_Winning_Propositions(keccak256(abi.encodePacked(address(this),Mandates[last_mandate_num].Election_Timestamps))); if(results[0]==0){ uint actual_member_length = Mandates[last_mandate_num].Members.length(); for(uint i =0; i<actual_member_length; i++){ Mandates[new_mandate_num].Members.add(Mandates[last_mandate_num].Members.at(i)); } }else{ for(uint i =0; i<results.length; i++){ Mandates[new_mandate_num].Members.add(Mandates[last_mandate_num].Next_Mandate_Candidats.at(results[i]-1)); } } Mandates[new_mandate_num].Inauguration_Timestamps = block.timestamp; Mandates[new_mandate_num].Version = Internal_Governance_Version; emit New_Mandate(); } /** * @dev Function called by {Candidate_Election} function of {Delegation} contract to add a new account to the list of candidats for next election * @param mandate Current Mandate object * @param new_candidat Account to add to the list of candidats */ function Add_Candidats(Mandate storage mandate, address new_candidat)external{ require(!mandate.Next_Mandate_Candidats.contains(new_candidat), "Already Candidate"); mandate.Next_Mandate_Candidats.add(new_candidat); emit New_Candidat(new_candidat); } /** * @dev Function called by {Remove_Candidature} function of {Delegation} contract to remove an account from the list of candidats for next election * @param mandate Current Mandate object * @param remove_candidat Account to remove from the list of candidats */ function Remove_Candidats(Mandate storage mandate, address remove_candidat)external{ require(mandate.Next_Mandate_Candidats.contains(remove_candidat), "Not Candidate"); mandate.Next_Mandate_Candidats.remove(remove_candidat); emit Remove_Candidat(remove_candidat); } /** * @dev Function called by {Sign_New_Election_Petition} function of {Delegation} contract to add an account to list petition for revoking current delegation members * @param mandate Current Mandate object * @param Immunity_Duration Amount of time after the beginning of a new mandate during which delegation's members can't be revoked * @param signer Address of account who want to sign the petition */ function Sign_Petition(Mandate storage mandate, uint Immunity_Duration, address signer)external{ require(block.timestamp - mandate.Inauguration_Timestamps > Immunity_Duration, "Immunity Period"); require(!mandate.New_Election_Petitions.contains(signer), "Already signed petition"); mandate.New_Election_Petitions.add(signer); emit Sign(); } /** * @dev Function called by {New_Election} function of {Delegation} contract to start a new election * @param Mandates mapping of Mandate structure idexed by uint corresponding to their order of apparition * @param mandate_version Mandate_Parameter object corresponding to parameters that are used by current mandate * @param num_mandate Index of the current mandate in the {Mandates} mapping * @param citizen_register_address Address of {Citizens_Register} contract used in the current project to handle citizens registration */ function New_Election(mapping(uint=>Mandate) storage Mandates, Mandate_Parameter storage mandate_version, uint num_mandate, address citizen_register_address)external returns(bool new_election){ uint candidats_number = Mandates[num_mandate].Next_Mandate_Candidats.length(); Citizens_Register citizen = Citizens_Register(citizen_register_address); require(candidats_number>0, "No Candidats"); require(Mandates[num_mandate].New_Election_Petitions.length() >= Percentage(mandate_version.New_Election_Petition_Rate, citizen.Get_Citizen_Number()) || (block.timestamp - Mandates[num_mandate].Inauguration_Timestamps) > mandate_version.Mandate_Duration, "New election impossible for now"); if(candidats_number <= mandate_version.Next_Mandate_Max_Members){ uint new_mandate_num = num_mandate+1; for(uint i =0; i<candidats_number; i++){ Mandates[new_mandate_num].Members.add(Mandates[num_mandate].Next_Mandate_Candidats.at(i)); } Mandates[new_mandate_num].Inauguration_Timestamps = block.timestamp; emit New_Mandate(); return false; }else{ Mandates[num_mandate].Election_Timestamps = block.timestamp; IVote Vote_Instance = IVote(mandate_version.Ivote_address); bytes32 key = keccak256(abi.encodePacked(address(this),block.timestamp)); emit New_election(key); Vote_Instance.Create_Ballot(key, citizen_register_address, Citizens_Register(citizen_register_address).Contains_Function_Selector(), mandate_version.Election_Duration, mandate_version.Validation_Duration, candidats_number, mandate_version.Next_Mandate_Max_Members); return true; } } /** * @dev Function called by the constructor function of {Delegation} contract to start the first mandate. * @param mandate Current Mandate object * @param Initial_members Members of the first Delegation */ function Set_First_Mandate(Mandate storage mandate, address[] memory Initial_members)external{ mandate.Inauguration_Timestamps = block.timestamp; for(uint i=0; i<Initial_members.length; i++){ mandate.Members.add(Initial_members[i]); } mandate.Version= 1; } /** * @dev Utility function for computing Percentage. * @param ratio The ratio is represented with 2 decimals * @param base The base's number of decimal is arbitrary * @return Return the {ratio}% of {base}. The result is represented with the number of decimals of {base} */ function Percentage(uint16 ratio, uint base) internal pure returns(uint){ return (ratio*base)/10000 ;// ((ratio*base)/100) * 10^(-ratio_decimals) } } /** * @notice Delegation contract is an implementation of IDelegation and thus aims at implementing a governance system in which a group of elected accounts is allowed to rule one or more controled registers contract. */ contract Delegation is Institution, IDelegation{// Initiative_Legislative{ using EnumerableSet for EnumerableSet.AddressSet; using SafeMath for uint; using Initiative_Legislative_Lib for Initiative_Legislative_Lib.Law_Project; using Delegation_Uils for Delegation_Uils.Mandate_Parameter; using Delegation_Uils for Delegation_Uils.Mandate; using Delegation_Uils for Delegation_Uils.Law_Project_Parameters; /** * @dev status of a law project */ enum Status{ PROPOSITION, VOTE, CENSOR_LAW_PERIOD, ADOPTED, EXECUTED, ABORTED } /** * @dev Structure representing parameters related to the democratic process of registers governance. * * - Member_Max_Token_Usage: The maximum amount of token a member is allowed to use for a law project elaboration * - Law_Initialisation_Price: The price in token for creating a law project * - FunctionCall_Price: The price in token for one FunctionCall. * - Proposition_Duration: The duration of the stage in which members are allowed to submit propositions * - Vote_Duration: The duration of the stage in which members are allowed to vote for the proposition they want * - Law_Censor_Period_Duration: The duration of the stage in which all citizens are allowed to sign a etition against the law project proposed by the Delegation * - Censor_Proposition_Petition_Rate The minimum ratio of citizens required to cancel a law project * - Censor_Penalty_Rate Ratio of total amount of token belonged by the delegation that will be lost if a law project is rejected by citizens * - Ivote_address Address of the IVote contract that will be used during voting stage */ struct Law_Project_Parameters{ //uint Revert_Penalty_Limit; uint Member_Max_Token_Usage; uint Law_Initialisation_Price; uint FunctionCall_Price; uint Proposition_Duration; uint Vote_Duration; uint Law_Censor_Period_Duration; uint16 Censor_Proposition_Petition_Rate; uint16 Censor_Penalty_Rate; address Ivote_address; } /** * @dev Structure representing {Register} contract that are controled by the Delegation * - Active: Whether the register is still under the actual Delegation control in the Constitution. * - Law_Project_Counter: Number of pending law project related to this register * The Register can't be removed from delegation's control if there are pending law project related to it. However if {Active} field is false, then we can't start a new law project whose controled register is the current one. */ struct Controlable_Register{ bool Active; uint Law_Project_Counter; } /** * @dev Structure representing a law project * - Institution_Address: Address of register being concerned by this law project * - Law_Project_Status: Status ({Status} structure) of the law project * - Version: Version of Parameters ({Law_Project_Parameters} structure) used by the current law project * - Creation_Timestamp: Beginning of current law project * - Start_Vote_Timestamps: Beginning of voting stage * - Start_Censor_Law_Period_Timestamps: Beginning of law project censorable stage * - Law_Total_Potentialy_Lost: Amount of token that could be lost in penalty fee if all pending law project were to be censored by citizens petition * - Censor_Law_Petition_Counter: Number of citizens that have signed the petition to censor the current law project * - Censor_Law_Petitions: List of citizens that have signed the petition to censor the current law project * - Members_Token_Consumption: Mapping of the amount of token consummed by each member of the delegation */ struct Delegation_Law_Project{ address Institution_Address; Status Law_Project_Status; uint Version; uint Creation_Timestamp; uint Start_Vote_Timestamps; uint Start_Censor_Law_Period_Timestamps; uint Law_Total_Potentialy_Lost; uint Censor_Law_Petition_Counter; mapping(address=>bool) Censor_Law_Petitions; mapping(address=>uint) Members_Token_Consumption; } modifier Citizen_Only{ require(Citizens.Contains(msg.sender),"Citizen Only"); _; } modifier Delegation_Only{ require(Mandates[Actual_Mandate].Members.contains(msg.sender), "Delegation Only"); _; } event Governance_Parameters_Updated(); event Legislatif_Parameters_Updated(); event New_Candidat(address Candidat); event Remove_Candidat(address Candidat); event Sign(); event New_election(bytes32 Vote_key); event New_Mandate(); event Controled_Register_Added(address register); event Controled_Register_Canceled(address register); event Controled_Register_Removed(address register); event New_Law(bytes32 key); event New_Proposal(bytes32 key, uint proposal_index); event Proposal_Modified(bytes32 key, uint proposal_index); event Voting_Stage_Started(bytes32 law_project, bytes32 key); event Voting_Stage_Achieved(bytes32 key); event Law_Aborted(bytes32 key); event Law_Adopted(bytes32 key); event Law_executed(bytes32 key); event Function_Call_Executed( bytes32 key, uint num_function_call_ToExecute); //event New_Proposal(bytes32 key, uint num); /// @dev function selector of {Contains} function used to check Whether an account is member of the delegation bytes4 constant Contains_Function_Selector = 0x57f98d32; ///@dev Instance of the {DemoCoin} token used by the Project DemoCoin Democoin; ///@dev Instance of the {Citizens_Register} contract used by the Project Citizens_Register Citizens; //dev Address of the {Agora} contract used by the Project address Agora_address; ///@dev Total amount of token potentially lost via penalty fee. uint Potentialy_Lost_Amount; /*Legislatif Process*/ /** @dev Mapping of {Law_Project} structure ({Initiative_Legislative_Lib} library) * * */ mapping(bytes32 => Initiative_Legislative_Lib.Law_Project) public List_Law_Project; ///@dev Mapping of Registers ({Controlable_Register} structure) that can receive orders from the actual Delegation mapping(address=>Controlable_Register) public Controled_Registers; /// @dev List of Controled Registers EnumerableSet.AddressSet List_Controled_Registers; ///@dev Mapping of {Delegation_Law_Project} structure corresponding to law project of delegation (pending, aborted and passed) mapping(bytes32=>Delegation_Law_Project) public Delegation_Law_Projects; ///@dev List of law projects bytes32[] List_Delegation_Law_Projects; ///@dev Mapping of versions of Parameters ({Law_Project_Parameters} of {Delegation_Uils} library) used for law project process mapping(uint=>Delegation_Uils.Law_Project_Parameters) public Law_Parameters_Versions; /*Internal Governance*/ ///@dev Mapping of {Mandate} structure ({Delegation_Uils} library) corresponding to mandates of delegation (pending and passed) mapping(uint=>Delegation_Uils.Mandate) Mandates; ///@dev Mapping of versions of Parameters ({Mandate_Parameter} of {Delegation_Uils} library) used for delegation internal governance. mapping(uint=>Delegation_Uils.Mandate_Parameter) public Mandates_Versions; ///@dev Current version of parameters related to law project process uint Legislatif_Process_Version; ///@dev Current version of parameters related to delegation internal governance uint Internal_Governance_Version; /// @dev Id in {Mandate} mapping of the current mandate uint Actual_Mandate; /// @dev Boolean set whether we are in election stage or not. bool In_election_stage; /** * @param Name name of the Institution * @param Initial_members List of initial members of the delegation * @param token_address Address of {DemoCoin} token that will be used to transfert initial token amount to new registered citizens * @param citizen_address Address of the {Citizens_Register} contract used in the Project * @param agora_address Address of the {Agora} contract used in the project. */ constructor(string memory Name, address[] memory Initial_members, address token_address, address citizen_address, address agora_address) Institution(Name) { Type_Institution = Institution_Type.DELEGATION; Democoin = DemoCoin(token_address); Citizens = Citizens_Register(citizen_address); Agora_address = agora_address; Mandates[0].Set_First_Mandate( Initial_members); } /*Members Election related functions*/ /** * @dev Function called by a citizen who wish to candidate to next mandate's elections. */ function Candidate_Election() external override Citizen_Only{ require(!In_election_stage, "Election Time"); Mandates[Actual_Mandate].Add_Candidats(msg.sender); emit New_Candidat(msg.sender); } /** * @dev Function called by a citizen who wish to remove his candidature from next mandate's elections. */ function Remove_Candidature()external override{ require(!In_election_stage, "Election Time"); Mandates[Actual_Mandate].Remove_Candidats(msg.sender); emit Remove_Candidat(msg.sender); } /** * @dev When the current mandate duration is over or if the {New_Election_Petition_Rate} (see {Mandate} struct of {Delegation_Uils} library) is reached, any citizen can call this function to start a new election */ function New_Election() external override Citizen_Only { require(!In_election_stage, "An Election is Pending"); uint num_mandate = Actual_Mandate; if(Delegation_Uils.New_Election(Mandates,Mandates_Versions[Mandates[num_mandate].Version], num_mandate, address(Citizens))){ In_election_stage= true; emit New_election(keccak256(abi.encodePacked(address(this),block.timestamp))); }else{ uint new_mandate_num = num_mandate+1; Actual_Mandate = new_mandate_num; Mandates[new_mandate_num].Version = Internal_Governance_Version; emit New_Mandate(); } } /** * @dev Function can be called by a citizen to sign petition for a new election */ function Sign_New_Election_Petition() external override Citizen_Only{ uint num_mandate = Actual_Mandate; Mandates[num_mandate].Sign_Petition(Mandates_Versions[Mandates[num_mandate].Version].Immunity_Duration, msg.sender); emit Sign(); } /** * @dev When voting stage is over, any citizen can call this function to end the election and start a new mandate. */ function End_Election()external override { require(In_election_stage, "Not in Election time"); uint num_mandate = Actual_Mandate; //uint new_num_mandate = num_mandate.add(1); In_election_stage=false; Actual_Mandate = num_mandate + 1; emit New_Mandate(); Delegation_Uils.Transition_Mandate(Mandates, Mandates_Versions[Mandates[num_mandate].Version].Ivote_address, num_mandate, Internal_Governance_Version); } /*Legislatif Process related functions*/ /** * @dev Function can be called by a delegation member to submit a new law project. This function put {Law_Initialisation_Price} (see {Law_Project_Parameters} struct of {Delegation_Uils library}) DemoCoin token of Delegation contract in Escrow. * @param register_address Address of the register contract the law project is about. Must be contained in Controled_Registers mapping. * @param Title Title of the law project. Can be an hash. * @param Description Text explaining the spirit and generals goals of the law project. Can be an hash. */ function Add_Law_Project(address register_address, bytes calldata Title, bytes calldata Description)external override Delegation_Only{ //_Update_Law_Project(); require(Controled_Registers[register_address].Active, "Register Not Controled"); bytes32 key = keccak256(abi.encode(Title,Description)); require(Delegation_Law_Projects[key].Version==0,"Law project already created"); uint version =Legislatif_Process_Version; Delegation_Law_Projects[key].Version = version; Token_Consumption_Handler(msg.sender, Law_Parameters_Versions[version].Law_Initialisation_Price, key); Delegation_Law_Projects[key].Institution_Address = register_address; Delegation_Law_Projects[key].Creation_Timestamp = block.timestamp; List_Delegation_Law_Projects.push(key); List_Law_Project[key].Title = Title; List_Law_Project[key].Description = Description; Controled_Registers[register_address].Law_Project_Counter++; emit New_Law(key); } /** * @dev Function can be called by a delegation member to submit a corpus of function calls propositions to an existing pending law project. This function put in Escrow {FunctionCall_Price} (see {Law_Project_Parameters} struct of {Delegation_Uils library}) DemoCoin token * multiplied by the number of function call contained in the proposition. * @param law_project Id of the law project hte caller wants to add a proposition to. The Id is obtained by hashing the Title with the Description of the law project. * @param Parent Proposition Id the caller wants to attach his proposition to. It's the parent proposition in the proposal tree. If there isn't any proposition in the tree we want to attach the new proposition to, we set Parent to 0 * @param Parent_Proposals_Reuse List of Parent's function calls index we want to reuse in the new proposition. Function calls are ordered in the order we want them to be executed. 0 elements correspond to new function calls that have to be added by the caller in {New_Function_Call} argument. * @param New_Function_Call List of new function calls added by the caller. For each element of the New_Function_Call array, caller must set a 0 element in {Parent_Proposals_Reuse} array at the index he want the custom function call to be positioned * @param Description Text to justify the new proposal. Can be an hash. */ function Add_Proposal(bytes32 law_project, uint Parent, uint[] calldata Parent_Proposals_Reuse, bytes[] calldata New_Function_Call, bytes calldata Description) external override Delegation_Only{ require(Delegation_Law_Projects[law_project].Law_Project_Status == Status.PROPOSITION, "Not at PROPOSITION status"); uint version = Delegation_Law_Projects[law_project].Version; require( version != 0, "No existing Law Project"); Token_Consumption_Handler(msg.sender, Law_Parameters_Versions[version].FunctionCall_Price.mul(New_Function_Call.length), law_project); uint proposal_index = List_Law_Project[law_project].Proposal_Count.add(1); List_Law_Project[law_project].Proposals_Tree[proposal_index].Author = msg.sender; List_Law_Project[law_project].Add_Corpus_Proposal(Parent, Parent_Proposals_Reuse, New_Function_Call, Description); emit New_Proposal( law_project, proposal_index); } /** * @dev Function can be called by a delegation member to add function calls to a proposition that he has already created (He have to be the author of the proposition). * Caller must approve {FunctionCall_Price} (see {Law_Project_Parameters} struct of {Delegation_Uils library}) * multiplied by the number of function call he wants to add to the proposition, token for Delegation contract. * @param law_project Id of the law project the caller wants to add a proposition to. The Id is obtained by hashing the Title with the Description of the law project. * @param Proposal Proposition Id to modify. * @param New_Items Array of new function calls to add to the Proposition. * @param Indexs array of Proposition's function call list indexs to inser new function call (contained in {New_Items}) to. {New_Items} and {Indexs} have the same length. */ function Add_Item(bytes32 law_project, uint Proposal, bytes[] calldata New_Items, uint[] calldata Indexs) external override Delegation_Only{ require(Delegation_Law_Projects[law_project].Law_Project_Status == Status.PROPOSITION, "Law Not at PROPOSITION status"); uint version = Delegation_Law_Projects[law_project].Version; require( version != 0, "No existing Law Project"); Token_Consumption_Handler(msg.sender, Law_Parameters_Versions[version].FunctionCall_Price.mul(New_Items.length), law_project); List_Law_Project[law_project].Add_Item_Proposal( Proposal, New_Items, Indexs, msg.sender); emit Proposal_Modified(law_project, Proposal); } /** * @dev When the period of proposition submiting is over, any citizen can call this function to start the voting stage. The Id of the ballot corresponding to current law project the IVote contract is computed by hashing {law_project} Id with current block timestamps. * @param law_project Id of the law project the caller wants to add a proposition to. The Id is obtained by hashing the Title with the Description of the law project. */ function Start_Vote(bytes32 law_project)external override Delegation_Only{ uint version = Delegation_Law_Projects[law_project].Version; require( version != 0, "No existing Law Project"); require(Delegation_Law_Projects[law_project].Law_Project_Status == Status.PROPOSITION, "Law Not at PROPOSITION status"); require(block.timestamp.sub(Delegation_Law_Projects[law_project].Creation_Timestamp) > Law_Parameters_Versions[version].Proposition_Duration, "PROPOSITION stage not finished"); bytes32 key=keccak256(abi.encodePacked(law_project,block.timestamp)); Delegation_Law_Projects[law_project].Start_Vote_Timestamps = block.timestamp; Delegation_Law_Projects[law_project].Law_Project_Status = Status.VOTE; emit Voting_Stage_Started(law_project, key); IVote Vote_Instance = IVote(Law_Parameters_Versions[version].Ivote_address); Vote_Instance.Create_Ballot(key, address(this), Contains_Function_Selector, Law_Parameters_Versions[version].Vote_Duration,0, List_Law_Project[law_project].Proposal_Count, 1); } /** * @dev When the voting period is over, any citizen can call this function to end the voting stage. If the winning proposition is the default proposition is the default one (Proposition 0) the law proejct is aborted. Otherwise, the Law Censoring stage is started. * @param law_project Id of the law project the caller wants to add a proposition to. The Id is obtained by hashing the Title with the Description of the law project. */ function Achiev_Vote(bytes32 law_project) external override Delegation_Only{ IVote Vote_Instance = IVote(Law_Parameters_Versions[Delegation_Law_Projects[law_project].Version].Ivote_address); bytes32 key = keccak256(abi.encodePacked(law_project,Delegation_Law_Projects[law_project].Start_Vote_Timestamps)); uint winning_proposal= Vote_Instance.Get_Winning_Proposition_byId(key,0); List_Law_Project[law_project].Winning_Proposal = winning_proposal; if(winning_proposal==0){ Delegation_Law_Projects[law_project].Law_Project_Status = Status.ABORTED; emit Law_Aborted(law_project); }else{ Delegation_Law_Projects[law_project].Start_Censor_Law_Period_Timestamps = block.timestamp; Delegation_Law_Projects[law_project].Law_Project_Status = Status.CENSOR_LAW_PERIOD; emit Voting_Stage_Achieved(law_project); } } /** * @dev If we are at the Law censor stage, any citizen can call this function to sign the petition for canceling the law project. If the {Censor_Proposition_Petition_Rate} (see {Law_Project_Parameters} structure) is reached, the law project is aborted. * @param law_project Id of the law project the caller wants to add a proposition to. The Id is obtained by hashing the Title with the Description of the law project. */ function Censor_Law(bytes32 law_project)external override Citizen_Only{ require(Delegation_Law_Projects[law_project].Law_Project_Status == Status.CENSOR_LAW_PERIOD, "Law Not at CENSOR LAW status"); require(!Delegation_Law_Projects[law_project].Censor_Law_Petitions[msg.sender], "Already Signed"); uint counter =Delegation_Law_Projects[law_project].Censor_Law_Petition_Counter.add(1); Delegation_Law_Projects[law_project].Censor_Law_Petitions[msg.sender]=true; if(counter>= Percentage(Law_Parameters_Versions[Delegation_Law_Projects[law_project].Version].Censor_Proposition_Petition_Rate, Citizens.Get_Citizen_Number())){ //If the number of censure petitions signatures reach the minimum ratio. uint law_total_potentialy_lost = Delegation_Law_Projects[law_project].Law_Total_Potentialy_Lost; Delegation_Law_Projects[law_project].Law_Project_Status = Status.ABORTED; Potentialy_Lost_Amount = Potentialy_Lost_Amount.sub(law_total_potentialy_lost); Update_Controled_Registers(Delegation_Law_Projects[law_project].Institution_Address); Democoin.transfer(Agora_address,law_total_potentialy_lost); emit Law_Aborted(law_project); } Delegation_Law_Projects[law_project].Censor_Law_Petition_Counter = counter; } /** * @dev If the Law censor period is over and the law project hasn't been rejected by citizens, then any delegation member can call this function to set the law project as ADOPTED (see {Status} enumeration). * @param law_project Id of the law project the caller wants to add a proposition to. The Id is obtained by hashing the Title with the Description of the law project. */ function Adopt_Law(bytes32 law_project)external override Delegation_Only{ require(Delegation_Law_Projects[law_project].Law_Project_Status == Status.CENSOR_LAW_PERIOD, "Law Not at CENSOR LAW status"); require(block.timestamp.sub(Delegation_Law_Projects[law_project].Start_Censor_Law_Period_Timestamps) > Law_Parameters_Versions[Delegation_Law_Projects[law_project].Version].Law_Censor_Period_Duration, "CENSOR LAW PERIOD not over"); Delegation_Law_Projects[law_project].Law_Project_Status = Status.ADOPTED; emit Law_Adopted(law_project); } /** * @dev Once the law project has been adopted (ADOPTED value of {Status} enum) then any delegation member can call this function to execute all or some of the remaining function call of the winning proposition. * For the law project to be fully executed all function call have to be executed. * @param law_project Id of the law project the caller wants to add a proposition to. The Id is obtained by hashing the Title with the Description of the law project. * @param num_function_call_ToExecute Number of function calls to execute. */ function Execute_Law(bytes32 law_project, uint num_function_call_ToExecute)external override Delegation_Only nonReentrant{ require(Delegation_Law_Projects[law_project].Law_Project_Status == Status.ADOPTED, "Law Not ADOPTED"); emit Function_Call_Executed( law_project, num_function_call_ToExecute); if(List_Law_Project[law_project].Execute_Winning_Proposal(num_function_call_ToExecute, Delegation_Law_Projects[law_project].Institution_Address)){ Delegation_Law_Projects[law_project].Law_Project_Status = Status.EXECUTED; Potentialy_Lost_Amount = Potentialy_Lost_Amount.sub(Delegation_Law_Projects[law_project].Law_Total_Potentialy_Lost); Update_Controled_Registers(Delegation_Law_Projects[law_project].Institution_Address); emit Law_executed(law_project); } } /*Constitution_Only Delegation parameters initialisation*/ /** * @dev See {IDelegation} interface */ function Update_Legislatif_Process(uint[6] calldata Uint256_Legislatifs_Arg, uint16 Censor_Proposition_Petition_Rate, uint16 Censor_Penalty_Rate, address Ivote_address)external override Constitution_Only{ uint version = Legislatif_Process_Version.add(1); Law_Parameters_Versions[version].Update_Law_Parameters(Uint256_Legislatifs_Arg, Censor_Proposition_Petition_Rate, Censor_Penalty_Rate, Ivote_address); /*Law_Parameters_Versions[version].Member_Max_Token_Usage = Uint256_Legislatifs_Arg[0]; Law_Parameters_Versions[version].Law_Initialisation_Price = Uint256_Legislatifs_Arg[1]; Law_Parameters_Versions[version].FunctionCall_Price = Uint256_Legislatifs_Arg[2]; Law_Parameters_Versions[version].Proposition_Duration = Uint256_Legislatifs_Arg[3]; Law_Parameters_Versions[version].Vote_Duration = Uint256_Legislatifs_Arg[4]; Law_Parameters_Versions[version].Law_Censor_Period_Duration = Uint256_Legislatifs_Arg[5]; Law_Parameters_Versions[version].Censor_Proposition_Petition_Rate = Censor_Proposition_Petition_Rate; Law_Parameters_Versions[version].Censor_Penalty_Rate = Censor_Penalty_Rate; Law_Parameters_Versions[version].Ivote_address = Ivote_address;*/ Legislatif_Process_Version = version; emit Legislatif_Parameters_Updated(); } /** * @dev See {IDelegation} interface */ function Update_Internal_Governance( uint Election_Duration, uint Validation_Duration, uint Mandate_Duration, uint Immunity_Duration, uint16 Num_Max_Members, uint16 New_Election_Petition_Rate, address Ivote_address)external override Constitution_Only{ uint version = Internal_Governance_Version.add(1); Mandates_Versions[version].Update_Mandate_Parameter(Election_Duration, Validation_Duration, Mandate_Duration, Immunity_Duration, Num_Max_Members, New_Election_Petition_Rate, Ivote_address); /*Mandates_Versions[version].Election_Duration = Election_Duration; Mandates_Versions[version].Validation_Duration = Validation_Duration; Mandates_Versions[version].Mandate_Duration = Mandate_Duration; Mandates_Versions[version].Immunity_Duration = Immunity_Duration; Mandates_Versions[version].Num_Max_Members = Num_Max_Members; Mandates_Versions[version].New_Election_Petition_Rate = New_Election_Petition_Rate; Mandates_Versions[version].Ivote_address = Ivote_address;*/ Internal_Governance_Version = version; emit Governance_Parameters_Updated(); } /** * @dev See {IDelegation} interface * */ function Add_Controled_Register(address register_address) external override Constitution_Only { require(!Controled_Registers[register_address].Active, "Register already Controled"); Controled_Registers[register_address].Active = true; List_Controled_Registers.add(register_address); emit Controled_Register_Added(register_address); } /** * @dev See {IDelegation} interface * */ function Remove_Controled_Register(address register_address) external override Constitution_Only { require(Controled_Registers[register_address].Active, "Register Not Controled"); Controled_Registers[register_address].Active = false; if(Controled_Registers[register_address].Law_Project_Counter ==0){ Register(register_address).Remove_Authority(address(this)); List_Controled_Registers.remove(register_address); emit Controled_Register_Removed(register_address); }else{ emit Controled_Register_Canceled(register_address); } } /*Utils*/ /** * @notice Handle token consumption in the context of law project elaboration * @dev The function: check that: * - check that the member's max token consumption limit for the current law project isn't exceeded by the sender * - check that the Delegation has enough funds to afford penalties if current pending were to be reverted by citizens. * - Update the value of the amount of token consumed by the sender for the law project identified by "key". * - Update the "Law_Total_Potentialy_Lost" field of the corresponding "Delegation_Law_Project" struct. * - Update the "Potentialy_Lost_Amount" state variable * * @param sender Address of the sender of the transaction * @param amount Amount of DemoCoin sent in the transaction * @param key Id of the law project * */ function Token_Consumption_Handler(address sender, uint amount, bytes32 key) internal{ uint version = Delegation_Law_Projects[key].Version; require(Delegation_Law_Projects[key].Members_Token_Consumption[sender] +amount <= Law_Parameters_Versions[version].Member_Max_Token_Usage, "Member consumption exceeded"); uint amount_potentialy_lost = Percentage(Law_Parameters_Versions[version].Censor_Penalty_Rate, amount); uint new_potentialy_lost_amount = Potentialy_Lost_Amount.add(amount_potentialy_lost); require(new_potentialy_lost_amount <= Democoin.balanceOf(address(this)), "No enough colaterals funds"); Delegation_Law_Projects[key].Members_Token_Consumption[sender] += amount; Delegation_Law_Projects[key].Law_Total_Potentialy_Lost = Delegation_Law_Projects[key].Law_Total_Potentialy_Lost.add(amount_potentialy_lost); Potentialy_Lost_Amount = new_potentialy_lost_amount; } /** * @dev Decrease the counter ("Law_Project_Counter" field of Controlable_Register struct) of pending law project related to the register of address "institution_address". If the counter becomes null and the "Actual" field of Controlable_Registers struct is false, * then the corresponding register is removed from List_Controled_Registers and the delegation removes it self from the register's Authorithies list ("Register_Authorities" state variable) * @param institution_address Address of the controled register to be updated. */ function Update_Controled_Registers(address institution_address) internal{ uint counter = Controled_Registers[institution_address].Law_Project_Counter.sub(1); Controled_Registers[institution_address].Law_Project_Counter = counter; if(counter==0 && !Controled_Registers[institution_address].Active){ Register(institution_address).Remove_Authority(address(this)); List_Controled_Registers.remove(institution_address); } } /*Getters*/ /** * @dev See {IDelegation} interface * */ function Contains(address member_address) external view override returns(bool contain){ return Mandates[Actual_Mandate].Members.contains(member_address); } /** * @dev Get 2 arrays: * - The list of law project Id * - The list of controled Register * @return Law_Project_List List of law project (pending, executed and aborted) * @return Controled_Register List of register address (represented in bytes32) whose contract is under Delegation control */ function Get_List_Law_Register()external view returns(bytes32[] memory Law_Project_List, bytes32[] memory Controled_Register ){ return (List_Delegation_Law_Projects, List_Controled_Registers._inner._values); } /** * @dev Get informations about a mandate * @param Id Id of the mandate * @return version Parameter Version used for this mandate * @return Inauguration_Timestamps Inauguration_Timestamps: Beginning of current mandate * @return Election_Timestamps Beginning of election * @return New_Election_Petition_Number Number of signatures obtained for revoking the delegation members related to {Id} Mandate * @return Members Array of {Id} mandate delegation member's address (represented in bytes32) * @return Candidats Array candidats address (represented in bytes32) */ function Get_Mandate(uint Id)external view returns(uint version, uint Inauguration_Timestamps, uint Election_Timestamps, uint New_Election_Petition_Number, bytes32[] memory Members, bytes32[] memory Candidats){ version = Mandates[Id].Version; Inauguration_Timestamps = Mandates[Id].Inauguration_Timestamps; Election_Timestamps= Mandates[Id].Election_Timestamps; New_Election_Petition_Number=Mandates[Id].New_Election_Petitions.length(); Members = Mandates[Id].Members._inner._values; Candidats = Mandates[Id].Next_Mandate_Candidats._inner._values; } /** * @dev Get the amount of DemoCoin token owned by the Delegation and used by a Delegation member for a specific delegation law project. * @param key Id of law project * @param member Address of delegation member * @return amount Amount of token used by {member} address for {key} law project * */ function Get_Member_Amount_Consumed(bytes32 key, address member)external view returns(uint amount){ return Delegation_Law_Projects[key].Members_Token_Consumption[member]; } /** * @dev Get various Delegation state variables values. * @return legislatif_process_version Current version of parameters related to delegation law project process. * @return internal_governance_version Current version of parameters related to delegation internal governance. * @return actual_mandate Id number of the current mandate * @return potentialy_lost_amount Total amount of token potentially lost via penalty fee. * @return in_election_stage Boolean assesing whether we are in election stage or not. */ function Get_Delegation_Infos()external view returns (uint legislatif_process_version, uint internal_governance_version, uint actual_mandate, uint potentialy_lost_amount, bool in_election_stage){ return (Legislatif_Process_Version, Internal_Governance_Version, Actual_Mandate, Potentialy_Lost_Amount, In_election_stage); } /** * @dev Get informations about a law project proposition * @param key Id of the law project * @param id Id of the proposition * @return description Description of the proposition * @return childrens Proposition node's children in the Proposal Tree. (See {Add_Corpus_Proposal} function of {Initiative_Legislative_Lib} library) * @return function_calls List of function calls proposed by the proposition * @return func_call_counter Number of function calls proposed by the proposition. * @return parent Id of the proposition's parent in the Proposal Tree * @return author Address of the author of the proposition. */ function Get_Proposal(bytes32 key, uint id)external view returns(bytes memory description, uint[] memory childrens, bytes[] memory function_calls, uint func_call_counter, uint parent, address author){ function_calls = List_Law_Project[key].Get_Proposal_FunctionCall_List(id); (description, childrens,func_call_counter, parent, author) = List_Law_Project[key].Get_Proposal_Infos(id); } /** * @dev Get Results of a law project * @return Winning_Proposal Id of the proposition that has been voted. * @return Receipts List of receipts of {Winning_Proposal} function call's execution. */ function Get_Law_Results(bytes32 key)external view returns(uint Winning_Proposal, Initiative_Legislative_Lib.Function_Call_Result[] memory Receipts){ return(List_Law_Project[key].Winning_Proposal, List_Law_Project[key].Function_Call_Receipts); } }
Get the amount of DemoCoin token owned by the Delegation and used by a Delegation member for a specific delegation law project. key Id of law project member Address of delegation member return amount Amount of token used by {member} address for {key} law project/
function Get_Member_Amount_Consumed(bytes32 key, address member)external view returns(uint amount){ return Delegation_Law_Projects[key].Members_Token_Consumption[member]; }
12,618,301
pragma solidity >=0.4.22 <0.6.0; import "./helperFunctions.sol"; import "./SafeMath.sol"; import "./Tier.sol"; import "./layerCounter.sol"; contract GoldLocations is helperFunctions { // Tier t; using SafeMath for uint; uint public TotalGoldLocated; //until t+0 uint public TotalGoldFound; mapping(uint => bool) trackingTiers; mapping(address => uint) tiers; mapping(uint => address) _tiers; uint[] allValues; uint[] tiersToDate; address[] allTiersAddress; function GenerateNewFields (uint amount, uint tier, uint layer) public returns (uint) { // for(uint i=0; i < amount; i++) { if(trackingTiers[tier] == false) { //new tier detected Tier child = new Tier(tier); address tierAddress = child.getAddress(); tiersToDate.push(tier); tiers[tierAddress] = tier; _tiers[tier]= tierAddress; Tier activeTier = Tier(tierAddress); uint answer = activeTier.addNewValue(layer, amount); allValues.push(answer); allTiersAddress.push(tierAddress); TotalGoldLocated += answer; // tier activeTier = new Tier(); }else{ // tier is known Tier activeTier = Tier(_tiers[tier]); uint answer = activeTier.addNewValue(layer, amount); allValues.push(answer); TotalGoldLocated += answer; //} } // uint value = addNewValue(layer); //allValues.push(value); } function getAllValues () public view returns (uint[] memory) { return allValues; } function getAllTiers () public view returns (uint[] memory) { return tiersToDate; } function getAllAddresses () public view returns (address[] memory) { return allTiersAddress; } }
for(uint i=0; i < amount; i++) { tier activeTier = new Tier();}
function GenerateNewFields (uint amount, uint tier, uint layer) public returns (uint) { Tier child = new Tier(tier); address tierAddress = child.getAddress(); tiersToDate.push(tier); tiers[tierAddress] = tier; _tiers[tier]= tierAddress; Tier activeTier = Tier(tierAddress); uint answer = activeTier.addNewValue(layer, amount); allValues.push(answer); allTiersAddress.push(tierAddress); TotalGoldLocated += answer; Tier activeTier = Tier(_tiers[tier]); uint answer = activeTier.addNewValue(layer, amount); allValues.push(answer); TotalGoldLocated += answer; }
12,578,555
./full_match/1/0x702860f8fBaCecAbE4Fe21b88BE490D3740276CE/sources/contracts/Credits.sol
Batch function for owner/admin to activate multiple credit buy plans at once. _planIds An array of plan ids to be activated./ Plan id should be valid. Activate the plan id.
function batchActivateCreditBuyPlans( uint256[] memory _planIds ) external onlyAdminOrOwner { for (uint256 i = 0; i < _planIds.length; i++) { uint256 planId = _planIds[i]; require( planId != 0 && planId <= creditBuyPlansAvailable, "Invalid plan id." ); creditBuyPlans[planId].isActive = true; } emit ActivatedCreditBuyPlans(msg.sender, _planIds, block.timestamp); }
9,737,196
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; import "@openzeppelin/contracts/utils/math/SafeCast.sol"; import "@openzeppelin/contracts/utils/structs/EnumerableSet.sol"; import "@openzeppelin/contracts/security/ReentrancyGuard.sol"; import "../utils/Operators.sol"; contract AllocationPool is Operators, ReentrancyGuard { using SafeERC20 for IERC20; using SafeCast for uint256; using EnumerableSet for EnumerableSet.UintSet; uint64 private constant ACCUMULATED_MULTIPLIER = 1e12; uint64 public constant ALLOC_MAXIMUM_DELAY_DURATION = 35 days; // maximum 35 days delay // Info of each user. struct AllocUserInfo { uint256 amount; // How many LP tokens the user has provided. uint256 rewardDebt; // Reward debt. See explanation below. uint256 pendingReward; // Reward but not harvest uint256 joinTime; // // 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. } // Info of each pool. struct AllocPoolInfo { IERC20 lpToken; // Address of LP token contract. uint256 lpSupply; // Total lp tokens deposited to this pool. uint64 allocPoint; // How many allocation points assigned to this pool. Rewards to distribute per block. uint256 lastRewardBlock; // Last block number that rewards distribution occurs. uint256 accRewardPerShare; // Accumulated rewards per share, times 1e12. See below. uint256 delayDuration; // The duration user need to wait when withdraw. uint256 lockDuration; } struct AllocPendingWithdrawal { uint256 amount; uint256 applicableAt; } // The reward token! IERC20 public allocRewardToken; // Total rewards for each block. uint256 public allocRewardPerBlock; // The reward distribution address address public allocRewardDistributor; // Allow emergency withdraw feature bool public allocAllowEmergencyWithdraw; // Info of each pool. AllocPoolInfo[] public allocPoolInfo; // A record status of LP pool. mapping(IERC20 => bool) public allocIsAdded; // Info of each user that stakes LP tokens. mapping(uint256 => mapping(address => AllocUserInfo)) public allocUserInfo; // Global allocation points across chains uint64 public globalAllocPoint; // The block number when rewards mining starts. uint256 public allocStartBlockNumber; // The block number when rewards mining ends. uint64 public allocEndBlockNumber; // Info of pending withdrawals. mapping(uint256 => mapping(address => AllocPendingWithdrawal)) public allocPendingWithdrawals; event AllocPoolCreated( uint256 indexed pid, address indexed token, uint256 allocPoint ); event AllocDeposit( address indexed user, uint256 indexed pid, uint256 amount ); event AllocWithdraw( address indexed user, uint256 indexed pid, uint256 amount ); event AllocPendingWithdraw( address indexed user, uint256 indexed pid, uint256 amount ); event AllocEmergencyWithdraw( address indexed user, uint256 indexed pid, uint256 amount ); event AllocRewardsHarvested( address indexed user, uint256 indexed pid, uint256 amount ); /** * @notice Initialize the contract, get called in the first time deploy * @param _rewardToken the reward token address * @param _rewardPerBlock the number of reward tokens that got unlocked each block * @param _startBlock the block number when farming start */ constructor( IERC20 _rewardToken, uint256 _rewardPerBlock, uint256 _startBlock, uint64 _globalAllocPoint ) Ownable() { require( address(_rewardToken) != address(0), "AllocStakingPool: invalid reward token address" ); allocRewardToken = _rewardToken; allocRewardPerBlock = _rewardPerBlock; allocStartBlockNumber = _startBlock; globalAllocPoint = _globalAllocPoint; } /** * @notice Validate pool by pool ID * @param _pid id of the pool */ modifier allocValidatePoolById(uint256 _pid) { require( _pid < allocPoolInfo.length, "AllocStakingPool: pool are not exist" ); _; } /** * @notice Return total number of pools */ function allocPoolLength() external view returns (uint256) { return allocPoolInfo.length; } /** * @notice Add a new lp to the pool. Can only be called by the operators. * @param _allocPoint the allocation point of the pool, used when calculating total reward the whole pool will receive each block * @param _lpToken the token which this pool will accept * @param _delayDuration the time user need to wait when withdraw */ function allocAddPool( uint64 _allocPoint, IERC20 _lpToken, uint256 _delayDuration, uint256 _lockDuration ) external onlyOperator { require( !allocIsAdded[_lpToken], "AllocStakingPool: pool already is added" ); require( _delayDuration <= ALLOC_MAXIMUM_DELAY_DURATION, "AllocStakingPool: delay duration is too long" ); allocMassUpdatePools(); uint256 lastRewardBlock = block.number > allocStartBlockNumber ? block.number : allocStartBlockNumber; allocPoolInfo.push( AllocPoolInfo({ lpToken: _lpToken, lpSupply: 0, allocPoint: _allocPoint, lastRewardBlock: lastRewardBlock, accRewardPerShare: 0, delayDuration: _delayDuration, lockDuration: _lockDuration }) ); allocIsAdded[_lpToken] = true; emit AllocPoolCreated( allocPoolInfo.length - 1, address(_lpToken), _allocPoint ); } /** * @notice Update the given pool's reward allocation point. Can only be called by the operators. * @param _pid id of the pool * @param _allocPoint the allocation point of the pool, used when calculating total reward the whole pool will receive each block * @param _delayDuration the time user need to wait when withdraw */ function allocSetPool( uint256 _pid, uint64 _allocPoint, uint256 _delayDuration, uint256 _lockDuration ) external onlyOperator allocValidatePoolById(_pid) { require( _delayDuration <= ALLOC_MAXIMUM_DELAY_DURATION, "AllocStakingPool: delay duration is too long" ); allocMassUpdatePools(); allocPoolInfo[_pid].allocPoint = _allocPoint; allocPoolInfo[_pid].delayDuration = _delayDuration; allocPoolInfo[_pid].lockDuration = _lockDuration; } /** * @notice Set the approval amount of distributor. Can only be called by the owner. * @param _amount amount of approval */ function allocApproveSelfDistributor(uint256 _amount) external onlyOwner { require( allocRewardDistributor == address(this), "AllocStakingPool: distributor is difference pool" ); allocRewardToken.safeApprove(allocRewardDistributor, _amount); } /** * @notice Set the reward distributor. Can only be called by the owner. * @param _allocRewardDistributor the reward distributor */ function allocSetRewardDistributor(address _allocRewardDistributor) external onlyOwner { require( _allocRewardDistributor != address(0), "AllocStakingPool: invalid reward distributor" ); allocRewardDistributor = _allocRewardDistributor; } /** * @notice Set the end block number. Can only be called by the operators. */ function allocSetEndBlock(uint64 _endBlockNumber) external onlyOperator { require( _endBlockNumber > block.number, "AllocStakingPool: invalid reward distributor" ); allocEndBlockNumber = _endBlockNumber; } /** * @notice Set the global allocation point of this master pool contract. */ function allocSetGlobalAllocPoint(uint64 _globalAllocPoint) external onlyOperator { globalAllocPoint = _globalAllocPoint; } /** * @notice Return time multiplier over the given _from to _to block. * @param _from the number of starting block * @param _to the number of ending block */ function allocTimeMultiplier(uint256 _from, uint256 _to) public view returns (uint256) { if (allocEndBlockNumber > 0 && _to > allocEndBlockNumber) { return allocEndBlockNumber > _from ? allocEndBlockNumber - _from : 0; } return _to - _from; } /** * @notice Update number of reward per block * @param _rewardPerBlock the number of reward tokens that got unlocked each block */ function allocSetRewardPerBlock(uint256 _rewardPerBlock) external onlyOperator { allocMassUpdatePools(); allocRewardPerBlock = _rewardPerBlock; } /** * @notice View function to see pending rewards on frontend. * @param _pid id of the pool * @param _user the address of the user */ function allocPendingReward(uint256 _pid, address _user) public view allocValidatePoolById(_pid) returns (uint256) { AllocPoolInfo storage pool = allocPoolInfo[_pid]; AllocUserInfo storage user = allocUserInfo[_pid][_user]; uint256 accRewardPerShare = pool.accRewardPerShare; uint256 lpSupply = pool.lpSupply; if (block.number > pool.lastRewardBlock && lpSupply != 0) { uint256 multiplier = allocTimeMultiplier( pool.lastRewardBlock, block.number ); uint256 poolReward = (multiplier * allocRewardPerBlock * pool.allocPoint) / globalAllocPoint; accRewardPerShare = accRewardPerShare + ((poolReward * ACCUMULATED_MULTIPLIER) / lpSupply); } return user.pendingReward + (((user.amount * accRewardPerShare) / ACCUMULATED_MULTIPLIER) - user.rewardDebt); } /** * @notice Update reward vairables for all pools. Be careful of gas spending! */ function allocMassUpdatePools() public { uint256 length = allocPoolInfo.length; for (uint256 pid = 0; pid < length; ++pid) { allocUpdatePool(pid); } } /** * @notice Update reward variables of the given pool to be up-to-date. * @param _pid id of the pool */ function allocUpdatePool(uint256 _pid) public allocValidatePoolById(_pid) { AllocPoolInfo storage pool = allocPoolInfo[_pid]; if (block.number <= pool.lastRewardBlock) { return; } uint256 lpSupply = pool.lpSupply; if (lpSupply == 0) { pool.lastRewardBlock = block.number; return; } uint256 multiplier = allocTimeMultiplier( pool.lastRewardBlock, block.number ); uint256 poolReward = (multiplier * allocRewardPerBlock * pool.allocPoint) / globalAllocPoint; pool.accRewardPerShare = (pool.accRewardPerShare + ((poolReward * ACCUMULATED_MULTIPLIER) / lpSupply)); pool.lastRewardBlock = block.number; } /** * @notice Deposit LP tokens to the farm for reward allocation. * @param _pid id of the pool * @param _amount amount to deposit */ function allocDeposit(uint256 _pid, uint256 _amount) external nonReentrant allocValidatePoolById(_pid) { AllocPoolInfo storage pool = allocPoolInfo[_pid]; AllocUserInfo storage user = allocUserInfo[_pid][msg.sender]; allocUpdatePool(_pid); uint256 pending = ((user.amount * pool.accRewardPerShare) / ACCUMULATED_MULTIPLIER) - user.rewardDebt; user.joinTime = block.timestamp; user.pendingReward = user.pendingReward + pending; user.amount = user.amount + _amount; user.rewardDebt = (user.amount * pool.accRewardPerShare) / ACCUMULATED_MULTIPLIER; pool.lpSupply = pool.lpSupply + _amount; pool.lpToken.safeTransferFrom( address(msg.sender), address(this), _amount ); emit AllocDeposit(msg.sender, _pid, _amount); } /** * @notice Withdraw LP tokens from Pool. * @param _pid id of the pool * @param _amount amount to withdraw * @param _harvestReward whether the user want to claim the rewards or not */ function allocWithdraw( uint256 _pid, uint256 _amount, bool _harvestReward ) external nonReentrant allocValidatePoolById(_pid) { _allocWithdraw(_pid, _amount, _harvestReward); AllocPoolInfo storage pool = allocPoolInfo[_pid]; if (pool.delayDuration == 0) { pool.lpToken.safeTransfer(address(msg.sender), _amount); emit AllocWithdraw(msg.sender, _pid, _amount); return; } AllocPendingWithdrawal storage pendingWithdraw = allocPendingWithdrawals[_pid][msg.sender]; pendingWithdraw.amount = pendingWithdraw.amount + _amount; pendingWithdraw.applicableAt = block.timestamp + pool.delayDuration; } /** * @notice Claim pending withdrawal * @param _pid id of the pool */ function allocClaimPendingWithdraw(uint256 _pid) external nonReentrant allocValidatePoolById(_pid) { AllocPoolInfo storage pool = allocPoolInfo[_pid]; AllocPendingWithdrawal storage pendingWithdraw = allocPendingWithdrawals[_pid][msg.sender]; uint256 amount = pendingWithdraw.amount; require(amount > 0, "AllocStakingPool: nothing is currently pending"); require( pendingWithdraw.applicableAt <= block.timestamp, "AllocStakingPool: not released yet" ); delete allocPendingWithdrawals[_pid][msg.sender]; pool.lpToken.safeTransfer(address(msg.sender), amount); emit AllocWithdraw(msg.sender, _pid, amount); } /** * @notice Update allowance for emergency withdraw * @param _shouldAllow should allow emergency withdraw or not */ function allocSetAllowEmergencyWithdraw(bool _shouldAllow) external onlyOperator { allocAllowEmergencyWithdraw = _shouldAllow; } /** * @notice Withdraw without caring about rewards. EMERGENCY ONLY. * @param _pid id of the pool */ function allocEmergencyWithdraw(uint256 _pid) external nonReentrant allocValidatePoolById(_pid) { require( allocAllowEmergencyWithdraw, "AllocStakingPool: emergency withdrawal is not allowed yet" ); AllocPoolInfo storage pool = allocPoolInfo[_pid]; AllocUserInfo storage user = allocUserInfo[_pid][msg.sender]; uint256 amount = user.amount; user.amount = 0; user.rewardDebt = 0; pool.lpSupply = pool.lpSupply - amount; pool.lpToken.safeTransfer(address(msg.sender), amount); emit AllocEmergencyWithdraw(msg.sender, _pid, amount); } /** * @notice Compound rewards to reward pool * @param _rewardPoolId id of the reward pool */ function allocCompoundReward(uint256 _rewardPoolId) external nonReentrant allocValidatePoolById(_rewardPoolId) { AllocPoolInfo storage pool = allocPoolInfo[_rewardPoolId]; AllocUserInfo storage user = allocUserInfo[_rewardPoolId][msg.sender]; require( pool.lpToken == allocRewardToken, "AllocStakingPool: invalid reward pool" ); uint256 totalPending = allocPendingReward(_rewardPoolId, msg.sender); require(totalPending > 0, "AllocStakingPool: invalid reward amount"); user.pendingReward = 0; allocSafeRewardTransfer(address(this), totalPending); emit AllocRewardsHarvested(msg.sender, _rewardPoolId, totalPending); allocUpdatePool(_rewardPoolId); user.amount = user.amount + totalPending; user.rewardDebt = (user.amount * pool.accRewardPerShare) / ACCUMULATED_MULTIPLIER; pool.lpSupply = pool.lpSupply + totalPending; emit AllocDeposit(msg.sender, _rewardPoolId, totalPending); } /** * @notice Harvest proceeds msg.sender * @param _pid id of the pool */ function allocClaimReward(uint256 _pid) public nonReentrant allocValidatePoolById(_pid) returns (uint256) { return _allocClaimReward(_pid); } /** * @notice Harvest proceeds of all pools for msg.sender * @param _pids ids of the pools */ function allocClaimAll(uint256[] memory _pids) external nonReentrant { uint256 length = _pids.length; for (uint256 pid = 0; pid < length; ++pid) { _allocClaimReward(pid); } } /** * @notice Safe reward transfer function, just in case if reward distributor dose not have enough reward tokens. * @param _to address of the receiver * @param _amount amount of the reward token */ function allocSafeRewardTransfer(address _to, uint256 _amount) internal { uint256 bal = allocRewardToken.balanceOf(allocRewardDistributor); require(_amount <= bal, "AllocStakingPool: not enough reward token"); allocRewardToken.safeTransferFrom(allocRewardDistributor, _to, _amount); } /** * @notice Withdraw LP tokens from Pool. * @param _pid id of the pool * @param _amount amount to withdraw * @param _harvestReward whether the user want to claim the rewards or not */ function _allocWithdraw( uint256 _pid, uint256 _amount, bool _harvestReward ) internal { AllocPoolInfo storage pool = allocPoolInfo[_pid]; AllocUserInfo storage user = allocUserInfo[_pid][msg.sender]; require(user.amount >= _amount, "AllocStakingPool: invalid amount"); require( block.timestamp >= user.joinTime + pool.lockDuration, "LinearStakingPool: still locked" ); if (_harvestReward || user.amount == _amount) { _allocClaimReward(_pid); } else { allocUpdatePool(_pid); uint256 pending = ((user.amount * pool.accRewardPerShare) / ACCUMULATED_MULTIPLIER) - user.rewardDebt; if (pending > 0) { user.pendingReward = user.pendingReward + pending; } } user.amount -= _amount; user.rewardDebt = (user.amount * pool.accRewardPerShare) / ACCUMULATED_MULTIPLIER; pool.lpSupply = pool.lpSupply - _amount; } function _allocClaimReward(uint256 _pid) internal returns (uint256) { allocUpdatePool(_pid); AllocPoolInfo storage pool = allocPoolInfo[_pid]; AllocUserInfo storage user = allocUserInfo[_pid][msg.sender]; uint256 totalPending = allocPendingReward(_pid, msg.sender); user.pendingReward = 0; user.rewardDebt = (user.amount * pool.accRewardPerShare) / (ACCUMULATED_MULTIPLIER); if (totalPending > 0) { allocSafeRewardTransfer(msg.sender, totalPending); } emit AllocRewardsHarvested(msg.sender, _pid, totalPending); return totalPending; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom( address sender, address recipient, uint256 amount ) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../IERC20.sol"; import "../../../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; /** * @dev Wrappers over Solidity's uintXX/intXX casting operators with added overflow * checks. * * Downcasting from uint256/int256 in Solidity does not revert on overflow. This can * easily result in undesired exploitation or bugs, since developers usually * assume that overflows raise errors. `SafeCast` restores this intuition by * reverting the transaction when such an operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. * * Can be combined with {SafeMath} and {SignedSafeMath} to extend it to smaller types, by performing * all math on `uint256` and `int256` and then downcasting. */ library SafeCast { /** * @dev Returns the downcasted uint224 from uint256, reverting on * overflow (when the input is greater than largest uint224). * * Counterpart to Solidity's `uint224` operator. * * Requirements: * * - input must fit into 224 bits */ function toUint224(uint256 value) internal pure returns (uint224) { require(value <= type(uint224).max, "SafeCast: value doesn't fit in 224 bits"); return uint224(value); } /** * @dev Returns the downcasted uint128 from uint256, reverting on * overflow (when the input is greater than largest uint128). * * Counterpart to Solidity's `uint128` operator. * * Requirements: * * - input must fit into 128 bits */ function toUint128(uint256 value) internal pure returns (uint128) { require(value <= type(uint128).max, "SafeCast: value doesn't fit in 128 bits"); return uint128(value); } /** * @dev Returns the downcasted uint96 from uint256, reverting on * overflow (when the input is greater than largest uint96). * * Counterpart to Solidity's `uint96` operator. * * Requirements: * * - input must fit into 96 bits */ function toUint96(uint256 value) internal pure returns (uint96) { require(value <= type(uint96).max, "SafeCast: value doesn't fit in 96 bits"); return uint96(value); } /** * @dev Returns the downcasted uint64 from uint256, reverting on * overflow (when the input is greater than largest uint64). * * Counterpart to Solidity's `uint64` operator. * * Requirements: * * - input must fit into 64 bits */ function toUint64(uint256 value) internal pure returns (uint64) { require(value <= type(uint64).max, "SafeCast: value doesn't fit in 64 bits"); return uint64(value); } /** * @dev Returns the downcasted uint32 from uint256, reverting on * overflow (when the input is greater than largest uint32). * * Counterpart to Solidity's `uint32` operator. * * Requirements: * * - input must fit into 32 bits */ function toUint32(uint256 value) internal pure returns (uint32) { require(value <= type(uint32).max, "SafeCast: value doesn't fit in 32 bits"); return uint32(value); } /** * @dev Returns the downcasted uint16 from uint256, reverting on * overflow (when the input is greater than largest uint16). * * Counterpart to Solidity's `uint16` operator. * * Requirements: * * - input must fit into 16 bits */ function toUint16(uint256 value) internal pure returns (uint16) { require(value <= type(uint16).max, "SafeCast: value doesn't fit in 16 bits"); return uint16(value); } /** * @dev Returns the downcasted uint8 from uint256, reverting on * overflow (when the input is greater than largest uint8). * * Counterpart to Solidity's `uint8` operator. * * Requirements: * * - input must fit into 8 bits. */ function toUint8(uint256 value) internal pure returns (uint8) { require(value <= type(uint8).max, "SafeCast: value doesn't fit in 8 bits"); return uint8(value); } /** * @dev Converts a signed int256 into an unsigned uint256. * * Requirements: * * - input must be greater than or equal to 0. */ function toUint256(int256 value) internal pure returns (uint256) { require(value >= 0, "SafeCast: value must be positive"); return uint256(value); } /** * @dev Returns the downcasted int128 from int256, reverting on * overflow (when the input is less than smallest int128 or * greater than largest int128). * * Counterpart to Solidity's `int128` operator. * * Requirements: * * - input must fit into 128 bits * * _Available since v3.1._ */ function toInt128(int256 value) internal pure returns (int128) { require(value >= type(int128).min && value <= type(int128).max, "SafeCast: value doesn't fit in 128 bits"); return int128(value); } /** * @dev Returns the downcasted int64 from int256, reverting on * overflow (when the input is less than smallest int64 or * greater than largest int64). * * Counterpart to Solidity's `int64` operator. * * Requirements: * * - input must fit into 64 bits * * _Available since v3.1._ */ function toInt64(int256 value) internal pure returns (int64) { require(value >= type(int64).min && value <= type(int64).max, "SafeCast: value doesn't fit in 64 bits"); return int64(value); } /** * @dev Returns the downcasted int32 from int256, reverting on * overflow (when the input is less than smallest int32 or * greater than largest int32). * * Counterpart to Solidity's `int32` operator. * * Requirements: * * - input must fit into 32 bits * * _Available since v3.1._ */ function toInt32(int256 value) internal pure returns (int32) { require(value >= type(int32).min && value <= type(int32).max, "SafeCast: value doesn't fit in 32 bits"); return int32(value); } /** * @dev Returns the downcasted int16 from int256, reverting on * overflow (when the input is less than smallest int16 or * greater than largest int16). * * Counterpart to Solidity's `int16` operator. * * Requirements: * * - input must fit into 16 bits * * _Available since v3.1._ */ function toInt16(int256 value) internal pure returns (int16) { require(value >= type(int16).min && value <= type(int16).max, "SafeCast: value doesn't fit in 16 bits"); return int16(value); } /** * @dev Returns the downcasted int8 from int256, reverting on * overflow (when the input is less than smallest int8 or * greater than largest int8). * * Counterpart to Solidity's `int8` operator. * * Requirements: * * - input must fit into 8 bits. * * _Available since v3.1._ */ function toInt8(int256 value) internal pure returns (int8) { require(value >= type(int8).min && value <= type(int8).max, "SafeCast: value doesn't fit in 8 bits"); return int8(value); } /** * @dev Converts an unsigned uint256 into a signed int256. * * Requirements: * * - input must be less than or equal to maxInt256. */ function toInt256(uint256 value) internal pure returns (int256) { // Note: Unsafe cast below is okay because `type(int256).max` is guaranteed to be positive require(value <= uint256(type(int256).max), "SafeCast: value doesn't fit in an int256"); return int256(value); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Library for managing * https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive * types. * * Sets have the following properties: * * - Elements are added, removed, and checked for existence in constant time * (O(1)). * - Elements are enumerated in O(n). No guarantees are made on the ordering. * * ``` * contract Example { * // Add the library methods * using EnumerableSet for EnumerableSet.AddressSet; * * // Declare a set state variable * EnumerableSet.AddressSet private mySet; * } * ``` * * As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`) * and `uint256` (`UintSet`) are supported. */ library EnumerableSet { // To implement this library for multiple types with as little code // repetition as possible, we write it in terms of a generic Set type with // bytes32 values. // The Set implementation uses private functions, and user-facing // implementations (such as AddressSet) are just wrappers around the // underlying Set. // This means that we can only create new EnumerableSets for types that fit // in bytes32. struct Set { // Storage of set values bytes32[] _values; // Position of the value in the `values` array, plus 1 because index 0 // means a value is not in the set. mapping(bytes32 => uint256) _indexes; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function _add(Set storage set, bytes32 value) private returns (bool) { if (!_contains(set, value)) { set._values.push(value); // The value is stored at length-1, but we add 1 to all indexes // and use 0 as a sentinel value set._indexes[value] = set._values.length; return true; } else { return false; } } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function _remove(Set storage set, bytes32 value) private returns (bool) { // We read and store the value's index to prevent multiple reads from the same storage slot uint256 valueIndex = set._indexes[value]; if (valueIndex != 0) { // Equivalent to contains(set, value) // To delete an element from the _values array in O(1), we swap the element to delete with the last one in // the array, and then remove the last element (sometimes called as 'swap and pop'). // This modifies the order of the array, as noted in {at}. uint256 toDeleteIndex = valueIndex - 1; uint256 lastIndex = set._values.length - 1; if (lastIndex != toDeleteIndex) { bytes32 lastvalue = set._values[lastIndex]; // Move the last value to the index where the value to delete is set._values[toDeleteIndex] = lastvalue; // Update the index for the moved value set._indexes[lastvalue] = valueIndex; // Replace lastvalue's index to valueIndex } // Delete the slot where the moved value was stored set._values.pop(); // Delete the index for the deleted slot delete set._indexes[value]; return true; } else { return false; } } /** * @dev Returns true if the value is in the set. O(1). */ function _contains(Set storage set, bytes32 value) private view returns (bool) { return set._indexes[value] != 0; } /** * @dev Returns the number of values on the set. O(1). */ function _length(Set storage set) private view returns (uint256) { return set._values.length; } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function _at(Set storage set, uint256 index) private view returns (bytes32) { return set._values[index]; } // Bytes32Set struct Bytes32Set { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _add(set._inner, value); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _remove(set._inner, value); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) { return _contains(set._inner, value); } /** * @dev Returns the number of values in the set. O(1). */ function length(Bytes32Set storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) { return _at(set._inner, index); } // AddressSet struct AddressSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(AddressSet storage set, address value) internal returns (bool) { return _add(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(AddressSet storage set, address value) internal returns (bool) { return _remove(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(AddressSet storage set, address value) internal view returns (bool) { return _contains(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Returns the number of values in the set. O(1). */ function length(AddressSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(AddressSet storage set, uint256 index) internal view returns (address) { return address(uint160(uint256(_at(set._inner, index)))); } // UintSet struct UintSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(UintSet storage set, uint256 value) internal returns (bool) { return _add(set._inner, bytes32(value)); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(UintSet storage set, uint256 value) internal returns (bool) { return _remove(set._inner, bytes32(value)); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(UintSet storage set, uint256 value) internal view returns (bool) { return _contains(set._inner, bytes32(value)); } /** * @dev Returns the number of values on the set. O(1). */ function length(UintSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(UintSet storage set, uint256 index) internal view returns (uint256) { return uint256(_at(set._inner, index)); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Contract module that helps prevent reentrant calls to a function. * * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier * available, which can be applied to functions to make sure there are no nested * (reentrant) calls to them. * * Note that because there is a single `nonReentrant` guard, functions marked as * `nonReentrant` may not call one another. This can be worked around by making * those functions `private`, and then adding `external` `nonReentrant` entry * points to them. * * TIP: If you would like to learn more about reentrancy and alternative ways * to protect against it, check out our blog post * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul]. */ abstract contract ReentrancyGuard { // Booleans are more expensive than uint256 or any type that takes up a full // word because each write operation emits an extra SLOAD to first read the // slot's contents, replace the bits taken up by the boolean, and then write // back. This is the compiler's defense against contract upgrades and // pointer aliasing, and it cannot be disabled. // The values being non-zero value makes deployment a bit more expensive, // but in exchange the refund on every call to nonReentrant will be lower in // amount. Since refunds are capped to a percentage of the total // transaction's gas, it is best to keep them low in cases like this one, to // increase the likelihood of the full refund coming into effect. uint256 private constant _NOT_ENTERED = 1; uint256 private constant _ENTERED = 2; uint256 private _status; constructor() { _status = _NOT_ENTERED; } /** * @dev Prevents a contract from calling itself, directly or indirectly. * Calling a `nonReentrant` function from another `nonReentrant` * function is not supported. It is possible to prevent this from happening * by making the `nonReentrant` function external, and make it call a * `private` function that does the actual work. */ modifier nonReentrant() { // On the first call to nonReentrant, _notEntered will be true require(_status != _ENTERED, "ReentrancyGuard: reentrant call"); // Any calls to nonReentrant after this point will fail _status = _ENTERED; _; // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) _status = _NOT_ENTERED; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import {Ownable} from "@openzeppelin/contracts/access/Ownable.sol"; import {EnumerableSet} from "@openzeppelin/contracts/utils/structs/EnumerableSet.sol"; contract Operators is Ownable { using EnumerableSet for EnumerableSet.AddressSet; EnumerableSet.AddressSet operators; event OperatorsAdded(address[] _operators); event OperatorsRemoved(address[] _operators); constructor() {} modifier onlyOperator() { require( isOperator(_msgSender()) || (owner() == _msgSender()), "caller is not operator" ); _; } function addOperators(address[] calldata _operators) public onlyOwner { for (uint256 i = 0; i < _operators.length; i++) { operators.add(_operators[i]); } emit OperatorsAdded(_operators); } function removeOperators(address[] calldata _operators) public onlyOwner { for (uint256 i = 0; i < _operators.length; i++) { operators.remove(_operators[i]); } emit OperatorsRemoved(_operators); } function isOperator(address _operator) public view returns (bool) { return operators.contains(_operator); } function numberOperators() public view returns (uint256) { return operators.length(); } function operatorAt(uint256 i) public view returns (address) { return operators.at(i); } function getAllOperators() public view returns (address[] memory _operators) { _operators = new address[](operators.length()); for (uint256 i = 0; i < _operators.length; i++) { _operators[i] = operators.at(i); } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); (bool success, bytes memory returndata) = target.delegatecall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) private pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; 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; /* * @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; } }
Update the given pool's reward allocation point. Can only be called by the operators. _pid id of the pool _allocPoint the allocation point of the pool, used when calculating total reward the whole pool will receive each block _delayDuration the time user need to wait when withdraw/
function allocSetPool( uint256 _pid, uint64 _allocPoint, uint256 _delayDuration, uint256 _lockDuration ) external onlyOperator allocValidatePoolById(_pid) { require( _delayDuration <= ALLOC_MAXIMUM_DELAY_DURATION, "AllocStakingPool: delay duration is too long" ); allocMassUpdatePools(); allocPoolInfo[_pid].allocPoint = _allocPoint; allocPoolInfo[_pid].delayDuration = _delayDuration; allocPoolInfo[_pid].lockDuration = _lockDuration; }
266,571
/** * @author Sushant Kumar * @title CampaignFactory * @section DESCRIPTION * This smart contract is an implementation of Kickstarter using Solidity. * It is used to create Campaigns to raise funds and then request the backers of * the Campagin to approve the usage of the raised funds for various purposes. * Additional features include withdrawal before deadline, refund initiated by Campaign manager * and rating of campaigns. * Follows a Factory design pattern wherein the CampaignFactory creates instances of the Campaign */ pragma solidity ^0.4.24; import "./SafeMath.sol"; import "./Ownable.sol"; import "./Pausable.sol"; import "./Campaign.sol"; contract CampaignFactory is Ownable, Pausable { using SafeMath for uint256; event NewCampaign(address campaignAddress, string name, uint minimum, address creator, uint deadline, uint goal, string details); struct CampaignStatus { address addrOfCampaign; uint deadline; } mapping(address => CampaignStatus[]) public campaignCreatorsList; mapping(address => CampaignStatus[]) public backersList; CampaignStatus[] public deployedCampaigns; /** * @dev Create a new Campaign with the required parameters * @param name Name of the campaign * @param minimum Minimum contribution for the campaign * @param _deadline Deadline for the campaign * @param _goal Funding goal of the campaign * @param details Additional details for the campaign */ function createCampaign(string name, uint minimum, uint _deadline, uint _goal, string details) public whenNotPaused { address newCampaign = new Campaign(name, minimum, msg.sender, _deadline, _goal, details); CampaignStatus memory newAddition = CampaignStatus({addrOfCampaign: newCampaign, deadline: _deadline }); deployedCampaigns.push(newAddition); emit NewCampaign(newCampaign, name, minimum, msg.sender, _deadline, _goal, details); } /** * @dev To retrieve list of campaigns. Uses filterCampaigns() to filter * @param user address of the user * @param code If 0 -> shows a general list. 1 -> Filters through campaign creators list. 2 -> Filters through campaign backers list * @return ongoingCampaigns List of addresses of Ongoing Campaigns * @return completedCampaigns List of addresses of Completed Campaigns */ function getCampaigns(address user, uint code) public view returns(address[] ongoingCampaigns, address[] completedCampaigns) { CampaignStatus[] memory listOfCampaigns; if(code == 0) { listOfCampaigns = deployedCampaigns; } else if(code == 1) { listOfCampaigns = campaignCreatorsList[user]; } else if(code == 2) { listOfCampaigns = backersList[user]; } return(filterCampaigns(listOfCampaigns)); } /** * @dev Filters campaigns based on current block.timestamp into ongoing and completed * @param campaigns List of CampaignStatus from getCampaigns() to filtered upon * @return ongoingCampaigns List of addresses of Ongoing Campaigns * @return completedCampaigns List of addresses of Completed Campaigns */ function filterCampaigns(CampaignStatus[] campaigns) internal view returns(address[] ongoingCampaigns, address[] completedCampaigns) { uint indexOfOngoing; uint indexOfCompleted; uint numberOfCampaigns = campaigns.length; ongoingCampaigns = new address[](numberOfCampaigns); completedCampaigns = new address[](numberOfCampaigns); for(uint i = 0; i < numberOfCampaigns; i = i.add(1)) { CampaignStatus memory campaign = campaigns[i]; // Ongoing Campaigns if(block.timestamp <= campaign.deadline ) { ongoingCampaigns[indexOfOngoing] = campaign.addrOfCampaign; indexOfOngoing = indexOfOngoing.add(1); } // Completed Campaigns else { completedCampaigns[indexOfCompleted] = campaign.addrOfCampaign; indexOfCompleted = indexOfCompleted.add(1); } } return (ongoingCampaigns, completedCampaigns); } /** * @dev Adds user to the lists campaignCreatorsList and backersList for all campaigns created * @param user address of user to be added to campaignCreatorsList/backersList * @param creatorOrBacker flag for a campaign creator/backer * @param _deadline Deadline of campaign acts as an additional parameter to filter for user profiles */ function addToList(address user, uint creatorOrBacker, uint _deadline) public { CampaignStatus memory newAddition = CampaignStatus({addrOfCampaign: msg.sender, deadline: _deadline}); bool notPresent = true; if(creatorOrBacker == 1) { CampaignStatus[] storage creatorCampaigns = campaignCreatorsList[user]; for(uint i = 0; i < creatorCampaigns.length; i++) { CampaignStatus memory tempCampaign = creatorCampaigns[i]; if(newAddition.addrOfCampaign == tempCampaign.addrOfCampaign) { notPresent = false; } } if(notPresent == true) { creatorCampaigns.push(newAddition); campaignCreatorsList[user] = creatorCampaigns; } } else if(creatorOrBacker == 2) { CampaignStatus[] storage backerCampaigns = backersList[user]; for(uint j = 0; j < backerCampaigns.length; j++) { CampaignStatus memory tempoCampaign = backerCampaigns[j]; if(newAddition.addrOfCampaign == tempoCampaign.addrOfCampaign) { notPresent = false; } } if(notPresent == true) { backerCampaigns.push(newAddition); backersList[user] = backerCampaigns; } } } /** * @dev Deletes users from the list backersList if a user withdrew their funds * @param user address of the user */ function deleteFromList(address user) public { CampaignStatus[] storage listOfCampaigns = backersList[user]; for(uint index = 0; index < listOfCampaigns.length; index = index.add(1)) { CampaignStatus memory campaign = listOfCampaigns[index]; if(msg.sender == campaign.addrOfCampaign) { delete listOfCampaigns[index]; } } backersList[user] = listOfCampaigns; } }
Filters campaigns based on current block.timestamp into ongoing and completed campaigns List of CampaignStatus from getCampaigns() to filtered upon return ongoingCampaigns List of addresses of Ongoing Campaigns return completedCampaigns List of addresses of Completed Campaigns/ Ongoing Campaigns Completed Campaigns
function filterCampaigns(CampaignStatus[] campaigns) internal view returns(address[] ongoingCampaigns, address[] completedCampaigns) { uint indexOfOngoing; uint indexOfCompleted; uint numberOfCampaigns = campaigns.length; ongoingCampaigns = new address[](numberOfCampaigns); completedCampaigns = new address[](numberOfCampaigns); for(uint i = 0; i < numberOfCampaigns; i = i.add(1)) { CampaignStatus memory campaign = campaigns[i]; if(block.timestamp <= campaign.deadline ) { ongoingCampaigns[indexOfOngoing] = campaign.addrOfCampaign; indexOfOngoing = indexOfOngoing.add(1); } else { completedCampaigns[indexOfCompleted] = campaign.addrOfCampaign; indexOfCompleted = indexOfCompleted.add(1); } } return (ongoingCampaigns, completedCampaigns); }
12,737,812
// File: @openzeppelin/contracts/utils/Strings.sol // OpenZeppelin Contracts v4.4.1 (utils/Strings.sol) pragma solidity ^0.8.0; /** * @dev String operations. */ library Strings { bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef"; /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0x00"; } uint256 temp = value; uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return toHexString(value, length); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = _HEX_SYMBOLS[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } } // File: @openzeppelin/contracts/utils/cryptography/ECDSA.sol // OpenZeppelin Contracts v4.4.1 (utils/cryptography/ECDSA.sol) pragma solidity ^0.8.0; /** * @dev Elliptic Curve Digital Signature Algorithm (ECDSA) operations. * * These functions can be used to verify that a message was signed by the holder * of the private keys of a given address. */ library ECDSA { enum RecoverError { NoError, InvalidSignature, InvalidSignatureLength, InvalidSignatureS, InvalidSignatureV } function _throwError(RecoverError error) private pure { if (error == RecoverError.NoError) { return; // no error: do nothing } else if (error == RecoverError.InvalidSignature) { revert("ECDSA: invalid signature"); } else if (error == RecoverError.InvalidSignatureLength) { revert("ECDSA: invalid signature length"); } else if (error == RecoverError.InvalidSignatureS) { revert("ECDSA: invalid signature 's' value"); } else if (error == RecoverError.InvalidSignatureV) { revert("ECDSA: invalid signature 'v' value"); } } /** * @dev Returns the address that signed a hashed message (`hash`) with * `signature` or error string. This address can then be used for verification purposes. * * The `ecrecover` EVM opcode allows for malleable (non-unique) signatures: * this function rejects them by requiring the `s` value to be in the lower * half order, and the `v` value to be either 27 or 28. * * IMPORTANT: `hash` _must_ be the result of a hash operation for the * verification to be secure: it is possible to craft signatures that * recover to arbitrary addresses for non-hashed data. A safe way to ensure * this is by receiving a hash of the original message (which may otherwise * be too long), and then calling {toEthSignedMessageHash} on it. * * Documentation for signature generation: * - with https://web3js.readthedocs.io/en/v1.3.4/web3-eth-accounts.html#sign[Web3.js] * - with https://docs.ethers.io/v5/api/signer/#Signer-signMessage[ethers] * * _Available since v4.3._ */ function tryRecover(bytes32 hash, bytes memory signature) internal pure returns (address, RecoverError) { // Check the signature length // - case 65: r,s,v signature (standard) // - case 64: r,vs signature (cf https://eips.ethereum.org/EIPS/eip-2098) _Available since v4.1._ if (signature.length == 65) { bytes32 r; bytes32 s; uint8 v; // ecrecover takes the signature parameters, and the only way to get them // currently is to use assembly. assembly { r := mload(add(signature, 0x20)) s := mload(add(signature, 0x40)) v := byte(0, mload(add(signature, 0x60))) } return tryRecover(hash, v, r, s); } else if (signature.length == 64) { bytes32 r; bytes32 vs; // ecrecover takes the signature parameters, and the only way to get them // currently is to use assembly. assembly { r := mload(add(signature, 0x20)) vs := mload(add(signature, 0x40)) } return tryRecover(hash, r, vs); } else { return (address(0), RecoverError.InvalidSignatureLength); } } /** * @dev Returns the address that signed a hashed message (`hash`) with * `signature`. This address can then be used for verification purposes. * * The `ecrecover` EVM opcode allows for malleable (non-unique) signatures: * this function rejects them by requiring the `s` value to be in the lower * half order, and the `v` value to be either 27 or 28. * * IMPORTANT: `hash` _must_ be the result of a hash operation for the * verification to be secure: it is possible to craft signatures that * recover to arbitrary addresses for non-hashed data. A safe way to ensure * this is by receiving a hash of the original message (which may otherwise * be too long), and then calling {toEthSignedMessageHash} on it. */ function recover(bytes32 hash, bytes memory signature) internal pure returns (address) { (address recovered, RecoverError error) = tryRecover(hash, signature); _throwError(error); return recovered; } /** * @dev Overload of {ECDSA-tryRecover} that receives the `r` and `vs` short-signature fields separately. * * See https://eips.ethereum.org/EIPS/eip-2098[EIP-2098 short signatures] * * _Available since v4.3._ */ function tryRecover( bytes32 hash, bytes32 r, bytes32 vs ) internal pure returns (address, RecoverError) { bytes32 s; uint8 v; assembly { s := and(vs, 0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff) v := add(shr(255, vs), 27) } return tryRecover(hash, v, r, s); } /** * @dev Overload of {ECDSA-recover} that receives the `r and `vs` short-signature fields separately. * * _Available since v4.2._ */ function recover( bytes32 hash, bytes32 r, bytes32 vs ) internal pure returns (address) { (address recovered, RecoverError error) = tryRecover(hash, r, vs); _throwError(error); return recovered; } /** * @dev Overload of {ECDSA-tryRecover} that receives the `v`, * `r` and `s` signature fields separately. * * _Available since v4.3._ */ function tryRecover( bytes32 hash, uint8 v, bytes32 r, bytes32 s ) internal pure returns (address, RecoverError) { // EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature // unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines // the valid range for s in (301): 0 < s < secp256k1n ÷ 2 + 1, and for v in (302): v ∈ {27, 28}. Most // signatures from current libraries generate a unique signature with an s-value in the lower half order. // // If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value // with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or // vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept // these malleable signatures as well. if (uint256(s) > 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0) { return (address(0), RecoverError.InvalidSignatureS); } if (v != 27 && v != 28) { return (address(0), RecoverError.InvalidSignatureV); } // If the signature is valid (and not malleable), return the signer address address signer = ecrecover(hash, v, r, s); if (signer == address(0)) { return (address(0), RecoverError.InvalidSignature); } return (signer, RecoverError.NoError); } /** * @dev Overload of {ECDSA-recover} that receives the `v`, * `r` and `s` signature fields separately. */ function recover( bytes32 hash, uint8 v, bytes32 r, bytes32 s ) internal pure returns (address) { (address recovered, RecoverError error) = tryRecover(hash, v, r, s); _throwError(error); return recovered; } /** * @dev Returns an Ethereum Signed Message, created from a `hash`. This * produces hash corresponding to the one signed with the * https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`] * JSON-RPC method as part of EIP-191. * * See {recover}. */ function toEthSignedMessageHash(bytes32 hash) internal pure returns (bytes32) { // 32 is the length in bytes of hash, // enforced by the type signature above return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hash)); } /** * @dev Returns an Ethereum Signed Message, created from `s`. This * produces hash corresponding to the one signed with the * https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`] * JSON-RPC method as part of EIP-191. * * See {recover}. */ function toEthSignedMessageHash(bytes memory s) internal pure returns (bytes32) { return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n", Strings.toString(s.length), s)); } /** * @dev Returns an Ethereum Signed Typed Data, created from a * `domainSeparator` and a `structHash`. This produces hash corresponding * to the one signed with the * https://eips.ethereum.org/EIPS/eip-712[`eth_signTypedData`] * JSON-RPC method as part of EIP-712. * * See {recover}. */ function toTypedDataHash(bytes32 domainSeparator, bytes32 structHash) internal pure returns (bytes32) { return keccak256(abi.encodePacked("\x19\x01", domainSeparator, structHash)); } } // File: @openzeppelin/contracts/utils/Address.sol // OpenZeppelin Contracts v4.4.1 (utils/Address.sol) pragma solidity ^0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); (bool success, bytes memory returndata) = target.delegatecall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // File: @openzeppelin/contracts/token/ERC721/IERC721Receiver.sol // OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721Receiver.sol) pragma solidity ^0.8.0; /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ interface IERC721Receiver { /** * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom} * by `operator` from `from`, this function is called. * * It must return its Solidity selector to confirm the token transfer. * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted. * * The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`. */ function onERC721Received( address operator, address from, uint256 tokenId, bytes calldata data ) external returns (bytes4); } // File: @openzeppelin/contracts/utils/introspection/IERC165.sol // OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol) pragma solidity ^0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // File: @openzeppelin/contracts/utils/introspection/ERC165.sol // OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol) pragma solidity ^0.8.0; /** * @dev Implementation of the {IERC165} interface. * * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check * for the additional interface id that will be supported. For example: * * ```solidity * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId); * } * ``` * * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation. */ abstract contract ERC165 is IERC165 { /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165).interfaceId; } } // File: @openzeppelin/contracts/token/ERC721/IERC721.sol // OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721.sol) pragma solidity ^0.8.0; /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721 is IERC165 { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes calldata data ) external; } // File: @openzeppelin/contracts/token/ERC721/extensions/IERC721Enumerable.sol // OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/IERC721Enumerable.sol) pragma solidity ^0.8.0; /** * @title ERC-721 Non-Fungible Token Standard, optional enumeration extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Enumerable is IERC721 { /** * @dev Returns the total amount of tokens stored by the contract. */ function totalSupply() external view returns (uint256); /** * @dev Returns a token ID owned by `owner` at a given `index` of its token list. * Use along with {balanceOf} to enumerate all of ``owner``'s tokens. */ function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 tokenId); /** * @dev Returns a token ID at a given `index` of all the tokens stored by the contract. * Use along with {totalSupply} to enumerate all tokens. */ function tokenByIndex(uint256 index) external view returns (uint256); } // File: @openzeppelin/contracts/token/ERC721/extensions/IERC721Metadata.sol // OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/IERC721Metadata.sol) pragma solidity ^0.8.0; /** * @title ERC-721 Non-Fungible Token Standard, optional metadata extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Metadata is IERC721 { /** * @dev Returns the token collection name. */ function name() external view returns (string memory); /** * @dev Returns the token collection symbol. */ function symbol() external view returns (string memory); /** * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token. */ function tokenURI(uint256 tokenId) external view returns (string memory); } // File: @openzeppelin/contracts/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/utils/Context.sol // OpenZeppelin Contracts v4.4.1 (utils/Context.sol) pragma solidity ^0.8.0; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } // File: @openzeppelin/contracts/token/ERC721/ERC721.sol // OpenZeppelin Contracts v4.4.1 (token/ERC721/ERC721.sol) pragma solidity ^0.8.0; /** * @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including * the Metadata extension, but not including the Enumerable extension, which is available separately as * {ERC721Enumerable}. */ contract ERC721 is Context, ERC165, IERC721, IERC721Metadata { using Address for address; using Strings for uint256; // Token name string private _name; // Token symbol string private _symbol; // Mapping from token ID to owner address mapping(uint256 => address) private _owners; // Mapping owner address to token count mapping(address => uint256) private _balances; // Mapping from token ID to approved address mapping(uint256 => address) private _tokenApprovals; // Mapping from owner to operator approvals mapping(address => mapping(address => bool)) private _operatorApprovals; /** * @dev Initializes the contract by setting a `name` and a `symbol` to the token collection. */ constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { return interfaceId == type(IERC721).interfaceId || interfaceId == type(IERC721Metadata).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) public view virtual override returns (uint256) { require(owner != address(0), "ERC721: balance query for the zero address"); return _balances[owner]; } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view virtual override returns (address) { address owner = _owners[tokenId]; require(owner != address(0), "ERC721: owner query for nonexistent token"); return owner; } /** * @dev See {IERC721Metadata-name}. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev See {IERC721Metadata-symbol}. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); string memory baseURI = _baseURI(); return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : ""; } /** * @dev Base URI for computing {tokenURI}. If set, the resulting URI for each * token will be the concatenation of the `baseURI` and the `tokenId`. Empty * by default, can be overriden in child contracts. */ function _baseURI() internal view virtual returns (string memory) { return ""; } /** * @dev See {IERC721-approve}. */ function approve(address to, uint256 tokenId) public virtual override { address owner = ERC721.ownerOf(tokenId); require(to != owner, "ERC721: approval to current owner"); require( _msgSender() == owner || isApprovedForAll(owner, _msgSender()), "ERC721: approve caller is not owner nor approved for all" ); _approve(to, tokenId); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view virtual override returns (address) { require(_exists(tokenId), "ERC721: approved query for nonexistent token"); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { _setApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC721-isApprovedForAll}. */ function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev See {IERC721-transferFrom}. */ function transferFrom( address from, address to, uint256 tokenId ) public virtual override { //solhint-disable-next-line max-line-length require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _transfer(from, to, tokenId); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId ) public virtual override { safeTransferFrom(from, to, tokenId, ""); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory _data ) public virtual override { require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _safeTransfer(from, to, tokenId, _data); } /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * `_data` is additional data, it has no specified format and it is sent in call to `to`. * * This internal function is equivalent to {safeTransferFrom}, and can be used to e.g. * implement alternative mechanisms to perform token transfer, such as signature-based. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeTransfer( address from, address to, uint256 tokenId, bytes memory _data ) internal virtual { _transfer(from, to, tokenId); require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); } /** * @dev Returns whether `tokenId` exists. * * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}. * * Tokens start existing when they are minted (`_mint`), * and stop existing when they are burned (`_burn`). */ function _exists(uint256 tokenId) internal view virtual returns (bool) { return _owners[tokenId] != address(0); } /** * @dev Returns whether `spender` is allowed to manage `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) { require(_exists(tokenId), "ERC721: operator query for nonexistent token"); address owner = ERC721.ownerOf(tokenId); return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender)); } /** * @dev Safely mints `tokenId` and transfers it to `to`. * * Requirements: * * - `tokenId` must not exist. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeMint(address to, uint256 tokenId) internal virtual { _safeMint(to, tokenId, ""); } /** * @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is * forwarded in {IERC721Receiver-onERC721Received} to contract recipients. */ function _safeMint( address to, uint256 tokenId, bytes memory _data ) internal virtual { _mint(to, tokenId); require( _checkOnERC721Received(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer" ); } /** * @dev Mints `tokenId` and transfers it to `to`. * * WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible * * Requirements: * * - `tokenId` must not exist. * - `to` cannot be the zero address. * * Emits a {Transfer} event. */ function _mint(address to, uint256 tokenId) internal virtual { require(to != address(0), "ERC721: mint to the zero address"); require(!_exists(tokenId), "ERC721: token already minted"); _beforeTokenTransfer(address(0), to, tokenId); _balances[to] += 1; _owners[tokenId] = to; emit Transfer(address(0), to, tokenId); } /** * @dev Destroys `tokenId`. * The approval is cleared when the token is burned. * * Requirements: * * - `tokenId` must exist. * * Emits a {Transfer} event. */ function _burn(uint256 tokenId) internal virtual { address owner = ERC721.ownerOf(tokenId); _beforeTokenTransfer(owner, address(0), tokenId); // Clear approvals _approve(address(0), tokenId); _balances[owner] -= 1; delete _owners[tokenId]; emit Transfer(owner, address(0), tokenId); } /** * @dev Transfers `tokenId` from `from` to `to`. * As opposed to {transferFrom}, this imposes no restrictions on msg.sender. * * Requirements: * * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * * Emits a {Transfer} event. */ function _transfer( address from, address to, uint256 tokenId ) internal virtual { require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own"); require(to != address(0), "ERC721: transfer to the zero address"); _beforeTokenTransfer(from, to, tokenId); // Clear approvals from the previous owner _approve(address(0), tokenId); _balances[from] -= 1; _balances[to] += 1; _owners[tokenId] = to; emit Transfer(from, to, tokenId); } /** * @dev Approve `to` to operate on `tokenId` * * Emits a {Approval} event. */ function _approve(address to, uint256 tokenId) internal virtual { _tokenApprovals[tokenId] = to; emit Approval(ERC721.ownerOf(tokenId), to, tokenId); } /** * @dev Approve `operator` to operate on all of `owner` tokens * * Emits a {ApprovalForAll} event. */ function _setApprovalForAll( address owner, address operator, bool approved ) internal virtual { require(owner != operator, "ERC721: approve to caller"); _operatorApprovals[owner][operator] = approved; emit ApprovalForAll(owner, operator, approved); } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address. * The call is not executed if the target address is not a contract. * * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function _checkOnERC721Received( address from, address to, uint256 tokenId, bytes memory _data ) private returns (bool) { if (to.isContract()) { try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) { return retval == IERC721Receiver.onERC721Received.selector; } catch (bytes memory reason) { if (reason.length == 0) { revert("ERC721: transfer to non ERC721Receiver implementer"); } else { assembly { revert(add(32, reason), mload(reason)) } } } } else { return true; } } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual {} } // File: @openzeppelin/contracts/token/ERC721/extensions/ERC721Enumerable.sol // OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/ERC721Enumerable.sol) pragma solidity ^0.8.0; /** * @dev This implements an optional extension of {ERC721} defined in the EIP that adds * enumerability of all the token ids in the contract as well as all token ids owned by each * account. */ abstract contract ERC721Enumerable is ERC721, IERC721Enumerable { // Mapping from owner to list of owned token IDs mapping(address => mapping(uint256 => uint256)) private _ownedTokens; // Mapping from token ID to index of the owner tokens list mapping(uint256 => uint256) private _ownedTokensIndex; // Array with all token ids, used for enumeration uint256[] private _allTokens; // Mapping from token id to position in the allTokens array mapping(uint256 => uint256) private _allTokensIndex; /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(IERC165, ERC721) returns (bool) { return interfaceId == type(IERC721Enumerable).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721Enumerable-tokenOfOwnerByIndex}. */ function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual override returns (uint256) { require(index < ERC721.balanceOf(owner), "ERC721Enumerable: owner index out of bounds"); return _ownedTokens[owner][index]; } /** * @dev See {IERC721Enumerable-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _allTokens.length; } /** * @dev See {IERC721Enumerable-tokenByIndex}. */ function tokenByIndex(uint256 index) public view virtual override returns (uint256) { require(index < ERC721Enumerable.totalSupply(), "ERC721Enumerable: global index out of bounds"); return _allTokens[index]; } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` cannot be the zero address. * - `to` cannot be the zero address. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual override { super._beforeTokenTransfer(from, to, tokenId); if (from == address(0)) { _addTokenToAllTokensEnumeration(tokenId); } else if (from != to) { _removeTokenFromOwnerEnumeration(from, tokenId); } if (to == address(0)) { _removeTokenFromAllTokensEnumeration(tokenId); } else if (to != from) { _addTokenToOwnerEnumeration(to, tokenId); } } /** * @dev Private function to add a token to this extension's ownership-tracking data structures. * @param to address representing the new owner of the given token ID * @param tokenId uint256 ID of the token to be added to the tokens list of the given address */ function _addTokenToOwnerEnumeration(address to, uint256 tokenId) private { uint256 length = ERC721.balanceOf(to); _ownedTokens[to][length] = tokenId; _ownedTokensIndex[tokenId] = length; } /** * @dev Private function to add a token to this extension's token tracking data structures. * @param tokenId uint256 ID of the token to be added to the tokens list */ function _addTokenToAllTokensEnumeration(uint256 tokenId) private { _allTokensIndex[tokenId] = _allTokens.length; _allTokens.push(tokenId); } /** * @dev Private function to remove a token from this extension's ownership-tracking data structures. Note that * while the token is not assigned a new owner, the `_ownedTokensIndex` mapping is _not_ updated: this allows for * gas optimizations e.g. when performing a transfer operation (avoiding double writes). * This has O(1) time complexity, but alters the order of the _ownedTokens array. * @param from address representing the previous owner of the given token ID * @param tokenId uint256 ID of the token to be removed from the tokens list of the given address */ function _removeTokenFromOwnerEnumeration(address from, uint256 tokenId) private { // To prevent a gap in from's tokens array, we store the last token in the index of the token to delete, and // then delete the last slot (swap and pop). uint256 lastTokenIndex = ERC721.balanceOf(from) - 1; uint256 tokenIndex = _ownedTokensIndex[tokenId]; // When the token to delete is the last token, the swap operation is unnecessary if (tokenIndex != lastTokenIndex) { uint256 lastTokenId = _ownedTokens[from][lastTokenIndex]; _ownedTokens[from][tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token _ownedTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index } // This also deletes the contents at the last position of the array delete _ownedTokensIndex[tokenId]; delete _ownedTokens[from][lastTokenIndex]; } /** * @dev Private function to remove a token from this extension's token tracking data structures. * This has O(1) time complexity, but alters the order of the _allTokens array. * @param tokenId uint256 ID of the token to be removed from the tokens list */ function _removeTokenFromAllTokensEnumeration(uint256 tokenId) private { // To prevent a gap in the tokens array, we store the last token in the index of the token to delete, and // then delete the last slot (swap and pop). uint256 lastTokenIndex = _allTokens.length - 1; uint256 tokenIndex = _allTokensIndex[tokenId]; // When the token to delete is the last token, the swap operation is unnecessary. However, since this occurs so // rarely (when the last minted token is burnt) that we still do the swap here to avoid the gas cost of adding // an 'if' statement (like in _removeTokenFromOwnerEnumeration) uint256 lastTokenId = _allTokens[lastTokenIndex]; _allTokens[tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token _allTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index // This also deletes the contents at the last position of the array delete _allTokensIndex[tokenId]; _allTokens.pop(); } } // File: @openzeppelin/contracts/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: NekoZamurai.sol //Contract based on [https://docs.openzeppelin.com/contracts/3.x/erc721](https://docs.openzeppelin.com/contracts/3.x/erc721) pragma solidity ^0.8.0; /* ╔═╗ ╔╗╔═══╗╔╗╔═╗╔═══╗ ╔════╗╔═══╗╔═╗╔═╗╔╗ ╔╗╔═══╗╔═══╗╔══╗ ║║╚╗║║║╔══╝║║║╔╝║╔═╗║ ╚══╗ ║║╔═╗║║║╚╝║║║║ ║║║╔═╗║║╔═╗║╚╣╠╝ ║╔╗╚╝║║╚══╗║╚╝╝ ║║ ║║ ╔╝╔╝║║ ║║║╔╗╔╗║║║ ║║║╚═╝║║║ ║║ ║║ ║║╚╗║║║╔══╝║╔╗║ ║║ ║║ ╔╝╔╝ ║╚═╝║║║║║║║║║ ║║║╔╗╔╝║╚═╝║ ║║ ║║ ║║║║╚══╗║║║╚╗║╚═╝║ ╔╝ ╚═╗║╔═╗║║║║║║║║╚═╝║║║║╚╗║╔═╗║╔╣╠╗ ╚╝ ╚═╝╚═══╝╚╝╚═╝╚═══╝ ╚════╝╚╝ ╚╝╚╝╚╝╚╝╚═══╝╚╝╚═╝╚╝ ╚╝╚══╝ Contract made with ❤️ by NekoZamurai Socials: Opensea: TBA Twitter: https://twitter.com/NekoZamuraiNFT Website: https://nekozamurai.io/ */ contract NekoZamurai is ERC721Enumerable, Ownable { using Strings for uint256; using SafeMath for uint256; using ECDSA for bytes32; // Constant variables // ------------------------------------------------------------------------ uint public constant publicSupply = 5217; uint public constant presaleSupply = 2560; uint public constant maxSupply = presaleSupply + publicSupply; uint public constant cost = 0.14 ether; uint public constant maxMintPerTx = 5; // Mapping variables // ------------------------------------------------------------------------ mapping(address => bool) public presalerList; mapping(address => uint256) public presalerListPurchases; mapping(address => uint256) public publicListPurchases; // Public variables // ------------------------------------------------------------------------ uint256 public publicAmountMinted; uint256 public presalePurchaseLimit = 1; uint256 public publicPurchaseLimit = 5; uint256 public reservedAmountMinted; // URI variables // ------------------------------------------------------------------------ string private contractURI; string private baseTokenURI = ""; // Deployer address // ------------------------------------------------------------------------ address public constant creatorAddress = 0x8707db291A13d9585b9Bc8e2289F64EbB6f5B672; address private signerAddress = 0x8707db291A13d9585b9Bc8e2289F64EbB6f5B672; // tbd bool public saleLive; bool public presaleLive; bool public revealed = false; bool public metadataLock; // Constructor // ------------------------------------------------------------------------ constructor(string memory unrevealedBaseURI) ERC721("NekoZamurai", "NEKO") { setBaseURI(unrevealedBaseURI); // setBaseURI("ipfs://QmXTsae772LDETthjkCNR4pPrEWShJ9UbuP7gCKWi26XV6/"); // testing purposes } modifier notLocked { require(!metadataLock, "Contract metadata methods are locked"); _; } // Mint function // ------------------------------------------------------------------------ function mintPublic(uint256 mintQuantity) external payable { require(saleLive, "Sale closed"); require(!presaleLive, "Only available for presale"); require(totalSupply() < maxSupply, "Out of stock"); require(publicAmountMinted + mintQuantity <= publicSupply, "Out of public stock"); require(publicListPurchases[msg.sender] + mintQuantity <= publicPurchaseLimit, "Public mint limit exceeded"); require(mintQuantity <= maxMintPerTx, "Exceeded mint limit"); require(cost * mintQuantity <= msg.value, "Insufficient funds"); for(uint256 i = 1; i <= mintQuantity; i++) { publicAmountMinted++; publicListPurchases[msg.sender]++; _safeMint(msg.sender, totalSupply() + 1); } } // Presale mint function // ------------------------------------------------------------------------ function mintPresale(uint256 mintQuantity) external payable { uint256 callSupply = totalSupply(); require(!saleLive && presaleLive, "Presale closed"); require(presalerList[msg.sender], "Not on presale list"); require(callSupply < maxSupply, "Out of stock"); require(publicAmountMinted + mintQuantity <= publicSupply, "Out of public stock"); require(presalerListPurchases[msg.sender] + mintQuantity <= presalePurchaseLimit, "Presale mint limit exceeded"); require(cost * mintQuantity <= msg.value, "Insufficient funds"); presalerListPurchases[msg.sender] += mintQuantity; publicAmountMinted += mintQuantity; for (uint256 i = 0; i < mintQuantity; i++) { _safeMint(msg.sender, callSupply + 1); } } // Reserved mint function // ------------------------------------------------------------------------ function mintReserved(uint256 mintQuantity) external onlyOwner { require(saleLive, "Sale closed"); require(totalSupply() < maxSupply, "Out of stock"); require(reservedAmountMinted + mintQuantity <= presaleSupply, "Out of reserved stock"); for(uint256 i = 1; i <= mintQuantity; i++) { reservedAmountMinted++; _safeMint(msg.sender, totalSupply() + 1); } } // Get cost amount // ------------------------------------------------------------------------ function getCost(uint256 _count) public pure returns (uint256) { return cost.mul(_count); } // Get hash transaction // ------------------------------------------------------------------------ function hashTransaction(address sender, uint256 qty, string memory nonce) public pure returns(bytes32) { bytes32 hash = keccak256(abi.encodePacked( "\x19Ethereum Signed Message:\n32", keccak256(abi.encodePacked(sender, qty, nonce))) ); return hash; } // Get match from address signer // ------------------------------------------------------------------------ function matchAddressSigner(bytes32 hash, bytes memory signature) private view returns(bool) { return signerAddress == hash.recover(signature); } // Get total supply leftover amount // ------------------------------------------------------------------------ function getUnsoldRemaining() external view returns (uint256) { return maxSupply - totalSupply(); } // Get contract URI // ------------------------------------------------------------------------ function getContractURI() public view returns (string memory) { return contractURI; } // Get base token URI // ------------------------------------------------------------------------ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); if (!revealed) { return baseTokenURI; } return bytes(baseTokenURI).length > 0 ? string(abi.encodePacked(baseTokenURI, tokenId.toString(), ".json")): ""; } // Owner functions // Toggle reveal function (True by default) // ------------------------------------------------------------------------ function reveal() public onlyOwner { revealed = true; } // Togle lock metadata function (True by default) // ------------------------------------------------------------------------ function lockMetadata() external onlyOwner { metadataLock = true; } // Toggle presale (False by default) // ------------------------------------------------------------------------ function togglePresale() external onlyOwner { presaleLive = !presaleLive; } // Toggle sale (False by default) // ------------------------------------------------------------------------ function toggleSale() external onlyOwner { saleLive = !saleLive; } // Add address to presael list // ------------------------------------------------------------------------ function addToPresaleList(address[] calldata entries) external onlyOwner { for(uint256 i = 0; i < entries.length; i++) { address entry = entries[i]; require(entry != address(0), "Null address"); require(!presalerList[entry], "Duplicate entry"); presalerList[entry] = true; } } // Remove address from presale list // ------------------------------------------------------------------------ function removeFromPresaleList(address[] calldata entries) external onlyOwner { for(uint256 i = 0; i < entries.length; i++) { address entry = entries[i]; require(entry != address(0), "Null address"); presalerList[entry] = false; } } // Approve signer address // ------------------------------------------------------------------------ function setSignerAddress(address addr) external onlyOwner { signerAddress = addr; } // Set contract URI // ------------------------------------------------------------------------ function setContractURI(string calldata URI) external onlyOwner notLocked { contractURI = URI; } // Set base URI // ------------------------------------------------------------------------ function setBaseURI(string memory baseURI) public onlyOwner notLocked { baseTokenURI = baseURI; } // Withdrawal function // ------------------------------------------------------------------------ function withdraw() external onlyOwner { uint256 balance = address(this).balance; require(balance > 0); (bool success, ) = payable(msg.sender).call{value: address(this).balance}(""); require(success); } }
Add address to presael list ------------------------------------------------------------------------
function addToPresaleList(address[] calldata entries) external onlyOwner { for(uint256 i = 0; i < entries.length; i++) { address entry = entries[i]; require(entry != address(0), "Null address"); require(!presalerList[entry], "Duplicate entry"); presalerList[entry] = true; } }
1,685,256
./full_match/1/0x2868dD9aBF1A88D5be7025858A55180D59bb1689/sources/contracts/Muppeth.sol
Update the royalty wallet address/
function setTreasuryAddress(address payable newAddress) public onlyOwner { if (newAddress == address(0)) revert CannotSetZeroAddress(); treasuryAddress = newAddress; }
9,754,855
// SPDX-License-Identifier: GPL-3.0 /// @title The Bitstrays NFT descriptor /*********************************************************** @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@[email protected]@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@%[email protected]@@@@@@@@@@@@ [email protected]@@@@@@.............................. ./@@@@@@@@@[email protected]@@....*@@@@.......*@@@@@@@@@. ./@@@@@@@[email protected]@@@@[email protected]@@[email protected]@@@@[email protected]@@@@. @%[email protected]@[email protected]@[email protected]@@[email protected] @%**.........,**.........................................**@ @@@@##.....##(**####### ......... ,####### .......###@@@ @@@@@@[email protected]@@@# @@ @@ ......... ,@@ @@@ [email protected]@@@@@ @@@@@@[email protected]@# @@@@@@@ ......... ,@@@@@@@ [email protected]@@@@@ @@@@@@[email protected]@@@@ @@%............ [email protected]@@@@@ @@@@@@@@@..../@@@@@@@@@[email protected]@@@@@@@ @@@@@@@@@............ [email protected]@@@@@@@ @@@@@@@@@@@.......... @@@@@@@@@@@@@@% .........*@@@@@@@@@@ @@@@@@@@@@@@@%.... @@//////////////#@@ [email protected]@@@@@@@@@@@@ @@@@@@@@@@@@@@@@ @@@///////////////////@@ @@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@ ************************ @@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ ************************************************************/ pragma solidity ^0.8.6; import { Ownable } from '@openzeppelin/contracts/access/Ownable.sol'; import { Strings } from '@openzeppelin/contracts/utils/Strings.sol'; import { IBitstraysDescriptor } from './interfaces/IBitstraysDescriptor.sol'; import { IBitstraysSeeder } from './interfaces/IBitstraysSeeder.sol'; import { NFTDescriptor } from './libs/NFTDescriptor.sol'; import { MultiPartRLEToSVG } from './libs/MultiPartRLEToSVG.sol'; import { StringUtil } from './libs/StringUtil.sol'; contract BitstraysDescriptor is IBitstraysDescriptor, Ownable { using Strings for uint256; // prettier-ignore // https://creativecommons.org/publicdomain/zero/1.0/legalcode.txt bytes32 constant COPYRIGHT_CC0_1_0_UNIVERSAL_LICENSE = 0xa2010f343487d3f7618affe54f789f5487602331c0a8d03f49e9a7c547cf0499; // Whether or not new Bitstray parts can be added bool public override arePartsLocked; // Whether or not `tokenURI` should be returned as a data URI (Default: true) bool public override isDataURIEnabled = true; // Whether or not attributes should be returned in tokenURI response (Default: true) bool public override areAttributesEnabled = true; // Base URI string public override baseURI; // Bitstray Color Palettes (Index => Hex Colors) mapping(uint8 => string[]) public override palettes; // Bitstray Backgrounds (Hex Colors) string[] public override backgrounds; // Bitstray Arms (Custom RLE) bytes[] public override arms; // Bitstray Shirts (Custom RLE) bytes[] public override shirts; // Bitstray Motives (Custom RLE) bytes[] public override motives; // Bitstray Heads (Custom RLE) bytes[] public override heads; // Bitstray Eyes (Custom RLE) bytes[] public override eyes; // Bitstray Mouths (Custom RLE) bytes[] public override mouths; // Bitstary Metadata (Array of String) mapping(uint8 => string[]) public override metadata; // Bitstary Trait Names (Array of String) string[] public override traitNames; /** * @notice Require that the parts have not been locked. */ modifier whenPartsNotLocked() { require(!arePartsLocked, 'Parts are locked'); _; } /** * @notice Get the number of available Bitstray `backgrounds`. */ function backgroundCount() external view override returns (uint256) { return backgrounds.length; } /** * @notice Get the number of available Bitstray `arms`. */ function armsCount() external view override returns (uint256) { return arms.length; } /** * @notice Get the number of available Bitstray `shirts`. */ function shirtsCount() external view override returns (uint256) { return shirts.length; } /** * @notice Get the number of available Bitstray `motives`. */ function motivesCount() external view override returns (uint256) { return motives.length; } /** * @notice Get the number of available Bitstray `heads`. */ function headCount() external view override returns (uint256) { return heads.length; } /** * @notice Get the number of available Bitstray `eyes`. */ function eyesCount() external view override returns (uint256) { return eyes.length; } /** * @notice Get the number of available Bitstray `mouths`. */ function mouthsCount() external view override returns (uint256) { return mouths.length; } /** * @notice Add metadata for all parts. * @dev This function can only be called by the owner. * should container encoding details for traits [#traits, trait1, #elements, trait2, #elements, data ...] */ function addManyMetadata(string[] calldata _metadata) external override onlyOwner { require(_metadata.length >= 1, '_metadata length < 1'); uint256 _traits = StringUtil.parseInt(_metadata[0]); uint256 offset = _traits + 1; //define first real data element // traits are provided in #traits, traitname uint8 index = 0; for (uint8 i = 1; i < _traits; i+=2 ) { _addTraitName(_metadata[i]); // read trait name uint256 elements = StringUtil.parseInt(_metadata[i+1]); for (uint256 j = offset; j < (offset + elements); j++) { _addMetadata(index, _metadata[j]); } offset = offset + elements; index++; } } /** * @notice Add colors to a color palette. * @dev This function can only be called by the owner. */ function addManyColorsToPalette(uint8 paletteIndex, string[] calldata newColors) external override onlyOwner { require(palettes[paletteIndex].length + newColors.length <= 256, 'Palettes can only hold 256 colors'); for (uint256 i = 0; i < newColors.length; i++) { _addColorToPalette(paletteIndex, newColors[i]); } } /** * @notice Batch add Bitstray backgrounds. * @dev This function can only be called by the owner when not locked. */ function addManyBackgrounds(string[] calldata _backgrounds) external override onlyOwner whenPartsNotLocked { for (uint256 i = 0; i < _backgrounds.length; i++) { _addBackground(_backgrounds[i]); } } /** * @notice Batch add Bitstray arms. * @dev This function can only be called by the owner when not locked. */ function addManyArms(bytes[] calldata _arms) external override onlyOwner whenPartsNotLocked { for (uint256 i = 0; i < _arms.length; i++) { _addArms(_arms[i]); } } /** * @notice Batch add Bitstray shirts. * @dev This function can only be called by the owner when not locked. */ function addManyShirts(bytes[] calldata _shirts) external override onlyOwner whenPartsNotLocked { for (uint256 i = 0; i < _shirts.length; i++) { _addShirt(_shirts[i]); } } /** * @notice Batch add Bitstray motives. * @dev This function can only be called by the owner when not locked. */ function addManyMotives(bytes[] calldata _motives) external override onlyOwner whenPartsNotLocked { for (uint256 i = 0; i < _motives.length; i++) { _addMotive(_motives[i]); } } /** * @notice Batch add Bitstray heads. * @dev This function can only be called by the owner when not locked. */ function addManyHeads(bytes[] calldata _heads) external override onlyOwner whenPartsNotLocked { for (uint256 i = 0; i < _heads.length; i++) { _addHead(_heads[i]); } } /** * @notice Batch add Bitstray eyes. * @dev This function can only be called by the owner when not locked. */ function addManyEyes(bytes[] calldata _eyes) external override onlyOwner whenPartsNotLocked { for (uint256 i = 0; i < _eyes.length; i++) { _addEyes(_eyes[i]); } } /** * @notice Batch add Bitstray eyes. * @dev This function can only be called by the owner when not locked. */ function addManyMouths(bytes[] calldata _mouths) external override onlyOwner whenPartsNotLocked { for (uint256 i = 0; i < _mouths.length; i++) { _addMouth(_mouths[i]); } } /** * @notice Add a single color to a color palette. * @dev This function can only be called by the owner. */ function addColorToPalette(uint8 _paletteIndex, string calldata _color) external override onlyOwner { require(palettes[_paletteIndex].length <= 255, 'Palettes can only hold 256 colors'); _addColorToPalette(_paletteIndex, _color); } /** * @notice Add a Bitstray background. * @dev This function can only be called by the owner when not locked. */ function addBackground(string calldata _background) external override onlyOwner whenPartsNotLocked { _addBackground(_background); } /** * @notice Add a Bitstray arms. * @dev This function can only be called by the owner when not locked. */ function addArms(bytes calldata _arms) external override onlyOwner whenPartsNotLocked { _addArms(_arms); } /** * @notice Add a Bitstray shirt. * @dev This function can only be called by the owner when not locked. */ function addShirt(bytes calldata _shirt) external override onlyOwner whenPartsNotLocked { _addShirt(_shirt); } /** * @notice Add a Bitstray motive. * @dev This function can only be called by the owner when not locked. */ function addMotive(bytes calldata _motive) external override onlyOwner whenPartsNotLocked { _addMotive(_motive); } /** * @notice Add a Bitstray head. * @dev This function can only be called by the owner when not locked. */ function addHead(bytes calldata _head) external override onlyOwner whenPartsNotLocked { _addHead(_head); } /** * @notice Add Bitstray eyes. * @dev This function can only be called by the owner when not locked. */ function addEyes(bytes calldata _eyes) external override onlyOwner whenPartsNotLocked { _addEyes(_eyes); } /** * @notice Add Bitstray mouth. * @dev This function can only be called by the owner when not locked. */ function addMouth(bytes calldata _mouth) external override onlyOwner whenPartsNotLocked { _addMouth(_mouth); } /** * @notice Lock all Bitstray parts. * @dev This cannot be reversed and can only be called by the owner when not locked. */ function lockParts() external override onlyOwner whenPartsNotLocked { arePartsLocked = true; emit PartsLocked(); } /** * @notice Toggle a boolean value which determines if `tokenURI` returns a data URI * or an HTTP URL. * @dev This can only be called by the owner. */ function toggleAttributesEnabled() external override onlyOwner { bool enabled = !areAttributesEnabled; areAttributesEnabled = enabled; emit AttributesToggled(enabled); } /** * @notice Toggle a boolean value which determines if `tokenURI` returns a data URI * or an HTTP URL. * @dev This can only be called by the owner. */ function toggleDataURIEnabled() external override onlyOwner { bool enabled = !isDataURIEnabled; isDataURIEnabled = enabled; emit DataURIToggled(enabled); } /** * @notice Set the base URI for all token IDs. It is automatically * added as a prefix to the value returned in {tokenURI}, or to the * token ID if {tokenURI} is empty. * @dev This can only be called by the owner. */ function setBaseURI(string calldata _baseURI) external override onlyOwner { baseURI = _baseURI; emit BaseURIUpdated(_baseURI); } /** * @notice Given a token ID and seed, construct a token URI for an official Bitstrays DAO bitstray. * @dev The returned value may be a base64 encoded data URI or an API URL. */ function tokenURI(uint256 tokenId, IBitstraysSeeder.Seed memory seed) external view override returns (string memory) { if (isDataURIEnabled) { return dataURI(tokenId, seed); } return string(abi.encodePacked(baseURI, tokenId.toString())); } /** * @notice Given a token ID and seed, construct a base64 encoded data URI for an official Bitstrays DAO bitstray. */ function dataURI(uint256 tokenId, IBitstraysSeeder.Seed memory seed) public view override returns (string memory) { string memory bitstrayId = tokenId.toString(); string memory name = string(abi.encodePacked('Bitstray #', bitstrayId)); string memory description = string(abi.encodePacked('Bitstray #', bitstrayId, ' is a member of the Bitstrays DAO and on-chain citizen')); return genericDataURI(name, description, seed); } /** * @notice Given a name, description, and seed, construct a base64 encoded data URI. */ function genericDataURI( string memory name, string memory description, IBitstraysSeeder.Seed memory seed ) public view override returns (string memory) { NFTDescriptor.TokenURIParams memory params = NFTDescriptor.TokenURIParams({ name: name, description: description, attributes : _getAttributesForSeed(seed), parts: _getPartsForSeed(seed), background: backgrounds[seed.background] }); return NFTDescriptor.constructTokenURI(params, palettes); } /** * @notice Given a seed, construct a base64 encoded SVG image. */ function generateSVGImage(IBitstraysSeeder.Seed memory seed) external view override returns (string memory) { MultiPartRLEToSVG.SVGParams memory params = MultiPartRLEToSVG.SVGParams({ parts: _getPartsForSeed(seed), background: backgrounds[seed.background] }); return NFTDescriptor.generateSVGImage(params, palettes); } /** * @notice Add a single attribute to metadata. */ function _addTraitName(string calldata _traitName) internal { traitNames.push(_traitName); } /** * @notice Add a single attribute to metadata. */ function _addMetadata(uint8 _index, string calldata _metadata) internal { metadata[_index].push(_metadata); } /** * @notice Add a single color to a color palette. */ function _addColorToPalette(uint8 _paletteIndex, string calldata _color) internal { palettes[_paletteIndex].push(_color); } /** * @notice Add a Bitstray background. */ function _addBackground(string calldata _background) internal { backgrounds.push(_background); } /** * @notice Add a Bitstray arm. */ function _addArms(bytes calldata _arms) internal { arms.push(_arms); } /** * @notice Add a Bitstray shirt. */ function _addShirt(bytes calldata _shirt) internal { shirts.push(_shirt); } /** * @notice Add a Bitstray motive. */ function _addMotive(bytes calldata _motive) internal { motives.push(_motive); } /** * @notice Add a Bitstray head. */ function _addHead(bytes calldata _head) internal { heads.push(_head); } /** * @notice Add Bitstray eyes. */ function _addEyes(bytes calldata _eyes) internal { eyes.push(_eyes); } /** * @notice Add Bitstray mouths. */ function _addMouth(bytes calldata _mouth) internal { mouths.push(_mouth); } /** * @notice Get all Bitstray attributes for the passed `seed`. */ function _getAttributesForSeed(IBitstraysSeeder.Seed memory seed) internal view returns (string[] memory) { if (areAttributesEnabled) { string[] memory _attributes = new string[](14); _attributes[0] = traitNames[0]; _attributes[1] = metadata[0][seed.head]; _attributes[2] = traitNames[1]; _attributes[3] = metadata[1][seed.head]; _attributes[4] = traitNames[2]; _attributes[5] = metadata[2][seed.arms]; _attributes[6] = traitNames[3]; _attributes[7] = metadata[3][seed.shirt]; _attributes[8] = traitNames[4]; _attributes[9] = metadata[4][seed.motive]; _attributes[10] = traitNames[5]; _attributes[11] = metadata[5][seed.eyes]; _attributes[12] = traitNames[6]; _attributes[13] = metadata[6][seed.mouth]; return _attributes; } string[] memory _empty = new string[](0); return _empty; } /** * @notice Get all Bitstray parts for the passed `seed`. */ function _getPartsForSeed(IBitstraysSeeder.Seed memory seed) internal view returns (bytes[] memory) { bytes[] memory _parts = new bytes[](6); _parts[0] = arms[seed.arms]; _parts[1] = shirts[seed.shirt]; _parts[2] = motives[seed.motive]; _parts[3] = heads[seed.head]; _parts[4] = eyes[seed.eyes]; _parts[5] = mouths[seed.mouth]; return _parts; } } // 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; /** * @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: GPL-3.0 /// @title Interface for BitstraysDescriptor /*********************************************************** @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@[email protected]@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@%[email protected]@@@@@@@@@@@@ [email protected]@@@@@@.............................. ./@@@@@@@@@[email protected]@@....*@@@@.......*@@@@@@@@@. ./@@@@@@@[email protected]@@@@[email protected]@@[email protected]@@@@[email protected]@@@@. @%[email protected]@[email protected]@[email protected]@@[email protected] @%**.........,**.........................................**@ @@@@##.....##(**####### ......... ,####### .......###@@@ @@@@@@[email protected]@@@# @@ @@ ......... ,@@ @@@ [email protected]@@@@@ @@@@@@[email protected]@# @@@@@@@ ......... ,@@@@@@@ [email protected]@@@@@ @@@@@@[email protected]@@@@ @@%............ [email protected]@@@@@ @@@@@@@@@..../@@@@@@@@@[email protected]@@@@@@@ @@@@@@@@@............ [email protected]@@@@@@@ @@@@@@@@@@@.......... @@@@@@@@@@@@@@% .........*@@@@@@@@@@ @@@@@@@@@@@@@%.... @@//////////////#@@ [email protected]@@@@@@@@@@@@ @@@@@@@@@@@@@@@@ @@@///////////////////@@ @@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@ ************************ @@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ ************************************************************/ pragma solidity ^0.8.6; import { IBitstraysSeeder } from './IBitstraysSeeder.sol'; interface IBitstraysDescriptor { event PartsLocked(); event DataURIToggled(bool enabled); event AttributesToggled(bool enabled); event BaseURIUpdated(string baseURI); function arePartsLocked() external returns (bool); function areAttributesEnabled() external returns (bool); function isDataURIEnabled() external returns (bool); function baseURI() external returns (string memory); function palettes(uint8 paletteIndex, uint256 colorIndex) external view returns (string memory); function metadata(uint8 index, uint256 traitIndex) external view returns (string memory); function traitNames(uint256 index) external view returns (string memory); function backgrounds(uint256 index) external view returns (string memory); function arms(uint256 index) external view returns (bytes memory); function shirts(uint256 index) external view returns (bytes memory); function motives(uint256 index) external view returns (bytes memory); function heads(uint256 index) external view returns (bytes memory); function eyes(uint256 index) external view returns (bytes memory); function mouths(uint256 index) external view returns (bytes memory); function backgroundCount() external view returns (uint256); function armsCount() external view returns (uint256); function shirtsCount() external view returns (uint256); function motivesCount() external view returns (uint256); function headCount() external view returns (uint256); function eyesCount() external view returns (uint256); function mouthsCount() external view returns (uint256); function addManyMetadata(string[] calldata _metadata) external; function addManyColorsToPalette(uint8 paletteIndex, string[] calldata newColors) external; function addManyBackgrounds(string[] calldata backgrounds) external; function addManyArms(bytes[] calldata _arms) external; function addManyShirts(bytes[] calldata _shirts) external; function addManyMotives(bytes[] calldata _motives) external; function addManyHeads(bytes[] calldata _heads) external; function addManyEyes(bytes[] calldata _eyes) external; function addManyMouths(bytes[] calldata _mouths) external; function addColorToPalette(uint8 paletteIndex, string calldata color) external; function addBackground(string calldata background) external; function addArms(bytes calldata body) external; function addShirt(bytes calldata shirt) external; function addMotive(bytes calldata motive) external; function addHead(bytes calldata head) external; function addEyes(bytes calldata eyes) external; function addMouth(bytes calldata mouth) external; function lockParts() external; function toggleDataURIEnabled() external; function toggleAttributesEnabled() external; function setBaseURI(string calldata baseURI) external; function tokenURI(uint256 tokenId, IBitstraysSeeder.Seed memory seed) external view returns (string memory); function dataURI(uint256 tokenId, IBitstraysSeeder.Seed memory seed) external view returns (string memory); function genericDataURI( string calldata name, string calldata description, IBitstraysSeeder.Seed memory seed ) external view returns (string memory); function generateSVGImage(IBitstraysSeeder.Seed memory seed) external view returns (string memory); } // SPDX-License-Identifier: GPL-3.0 /// @title Interface for BitstraysSeeder /*********************************************************** @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@[email protected]@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@%[email protected]@@@@@@@@@@@@ [email protected]@@@@@@.............................. ./@@@@@@@@@[email protected]@@....*@@@@.......*@@@@@@@@@. ./@@@@@@@[email protected]@@@@[email protected]@@[email protected]@@@@[email protected]@@@@. @%[email protected]@[email protected]@[email protected]@@[email protected] @%**.........,**.........................................**@ @@@@##.....##(**####### ......... ,####### .......###@@@ @@@@@@[email protected]@@@# @@ @@ ......... ,@@ @@@ [email protected]@@@@@ @@@@@@[email protected]@# @@@@@@@ ......... ,@@@@@@@ [email protected]@@@@@ @@@@@@[email protected]@@@@ @@%............ [email protected]@@@@@ @@@@@@@@@..../@@@@@@@@@[email protected]@@@@@@@ @@@@@@@@@............ [email protected]@@@@@@@ @@@@@@@@@@@.......... @@@@@@@@@@@@@@% .........*@@@@@@@@@@ @@@@@@@@@@@@@%.... @@//////////////#@@ [email protected]@@@@@@@@@@@@ @@@@@@@@@@@@@@@@ @@@///////////////////@@ @@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@ ************************ @@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ ************************************************************/ pragma solidity ^0.8.6; import { IBitstraysDescriptor } from './IBitstraysDescriptor.sol'; interface IBitstraysSeeder { struct Seed { uint48 background; uint48 arms; uint48 shirt; uint48 motive; uint48 head; uint48 eyes; uint48 mouth; } function generateSeed(uint256 bitstrayId, IBitstraysDescriptor descriptor) external view returns (Seed memory); } // SPDX-License-Identifier: GPL-3.0 /// @title A library used to construct ERC721 token URIs and SVG images /*********************************************************** @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@[email protected]@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@%[email protected]@@@@@@@@@@@@ [email protected]@@@@@@.............................. ./@@@@@@@@@[email protected]@@....*@@@@.......*@@@@@@@@@. ./@@@@@@@[email protected]@@@@[email protected]@@[email protected]@@@@[email protected]@@@@. @%[email protected]@[email protected]@[email protected]@@[email protected] @%**.........,**.........................................**@ @@@@##.....##(**####### ......... ,####### .......###@@@ @@@@@@[email protected]@@@# @@ @@ ......... ,@@ @@@ [email protected]@@@@@ @@@@@@[email protected]@# @@@@@@@ ......... ,@@@@@@@ [email protected]@@@@@ @@@@@@[email protected]@@@@ @@%............ [email protected]@@@@@ @@@@@@@@@..../@@@@@@@@@[email protected]@@@@@@@ @@@@@@@@@............ [email protected]@@@@@@@ @@@@@@@@@@@.......... @@@@@@@@@@@@@@% .........*@@@@@@@@@@ @@@@@@@@@@@@@%.... @@//////////////#@@ [email protected]@@@@@@@@@@@@ @@@@@@@@@@@@@@@@ @@@///////////////////@@ @@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@ ************************ @@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ ************************************************************/ pragma solidity ^0.8.6; import { Base64 } from 'base64-sol/base64.sol'; import { MultiPartRLEToSVG } from './MultiPartRLEToSVG.sol'; library NFTDescriptor { struct TokenURIParams { string name; string description; string[] attributes; bytes[] parts; string background; } /** * @notice Construct an ERC721 token attributes. */ function _generateAttributes(TokenURIParams memory params) internal pure returns (string memory attributes) { string memory _attributes = "["; if (params.attributes.length >0) { string [] memory att = params.attributes; for (uint256 i = 0; i < att.length && i + 1 < att.length; i += 2) { if (i == 0) { _attributes = string(abi.encodePacked(_attributes,'{"trait_type":"',att[i],'","value":"',att[i+1],'"}')); } else { _attributes = string(abi.encodePacked(_attributes, ',{"trait_type":"',att[i],'","value":"',att[i+1],'"}')); } } _attributes = string(abi.encodePacked(_attributes, "]")); return _attributes; } // empty array return string(abi.encodePacked(_attributes, "]")); } /** * @notice Construct an ERC721 token URI. */ function constructTokenURI(TokenURIParams memory params, mapping(uint8 => string[]) storage palettes) public view returns (string memory) { string memory image = generateSVGImage( MultiPartRLEToSVG.SVGParams({ parts: params.parts, background: params.background }), palettes ); string memory attributes = _generateAttributes(params); // prettier-ignore return string( abi.encodePacked( 'data:application/json;base64,', Base64.encode( bytes( abi.encodePacked( '{"name":"', params.name, '","description":"', params.description, '","attributes":',attributes,',"image": "', 'data:image/svg+xml;base64,', image, '"}') ) ) ) ); } /** * @notice Generate an SVG image for use in the ERC721 token URI. */ function generateSVGImage(MultiPartRLEToSVG.SVGParams memory params, mapping(uint8 => string[]) storage palettes) public view returns (string memory svg) { return Base64.encode(bytes(MultiPartRLEToSVG.generateSVG(params, palettes))); } } // SPDX-License-Identifier: GPL-3.0 /// @title A library used to convert multi-part RLE compressed images to SVG /*********************************************************** @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@[email protected]@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@%[email protected]@@@@@@@@@@@@ [email protected]@@@@@@.............................. ./@@@@@@@@@[email protected]@@....*@@@@.......*@@@@@@@@@. ./@@@@@@@[email protected]@@@@[email protected]@@[email protected]@@@@[email protected]@@@@. @%[email protected]@[email protected]@[email protected]@@[email protected] @%**.........,**.........................................**@ @@@@##.....##(**####### ......... ,####### .......###@@@ @@@@@@[email protected]@@@# @@ @@ ......... ,@@ @@@ [email protected]@@@@@ @@@@@@[email protected]@# @@@@@@@ ......... ,@@@@@@@ [email protected]@@@@@ @@@@@@[email protected]@@@@ @@%............ [email protected]@@@@@ @@@@@@@@@..../@@@@@@@@@[email protected]@@@@@@@ @@@@@@@@@............ [email protected]@@@@@@@ @@@@@@@@@@@.......... @@@@@@@@@@@@@@% .........*@@@@@@@@@@ @@@@@@@@@@@@@%.... @@//////////////#@@ [email protected]@@@@@@@@@@@@ @@@@@@@@@@@@@@@@ @@@///////////////////@@ @@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@ ************************ @@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ ************************************************************/ pragma solidity ^0.8.6; library MultiPartRLEToSVG { struct SVGParams { bytes[] parts; string background; } struct ContentBounds { uint8 top; uint8 right; uint8 bottom; uint8 left; } struct Rect { uint8 length; uint8 colorIndex; } struct DecodedImage { uint8 paletteIndex; ContentBounds bounds; Rect[] rects; } /** * @notice Given RLE image parts and color palettes, merge to generate a single SVG image. */ function generateSVG(SVGParams memory params, mapping(uint8 => string[]) storage palettes) internal view returns (string memory svg) { // prettier-ignore return string( abi.encodePacked( '<svg width="320" height="320" viewBox="0 0 320 320" xmlns="http://www.w3.org/2000/svg" shape-rendering="crispEdges">', '<rect width="100%" height="100%" fill="#', params.background, '" />', _generateSVGRects(params, palettes), '</svg>' ) ); } /** * @notice Given RLE image parts and color palettes, generate SVG rects. */ // prettier-ignore function _generateSVGRects(SVGParams memory params, mapping(uint8 => string[]) storage palettes) private view returns (string memory svg) { string[33] memory lookup = [ '0', '10', '20', '30', '40', '50', '60', '70', '80', '90', '100', '110', '120', '130', '140', '150', '160', '170', '180', '190', '200', '210', '220', '230', '240', '250', '260', '270', '280', '290', '300', '310', '320' ]; string memory rects; for (uint8 p = 0; p < params.parts.length; p++) { DecodedImage memory image = _decodeRLEImage(params.parts[p]); string[] storage palette = palettes[image.paletteIndex]; uint256 currentX = image.bounds.left; uint256 currentY = image.bounds.top; uint256 cursor; string[16] memory buffer; string memory part; for (uint256 i = 0; i < image.rects.length; i++) { Rect memory rect = image.rects[i]; if (rect.colorIndex != 0) { buffer[cursor] = lookup[rect.length]; // width buffer[cursor + 1] = lookup[currentX]; // x buffer[cursor + 2] = lookup[currentY]; // y buffer[cursor + 3] = palette[rect.colorIndex]; // color cursor += 4; if (cursor >= 16) { part = string(abi.encodePacked(part, _getChunk(cursor, buffer))); cursor = 0; } } currentX += rect.length; if (currentX == image.bounds.right) { currentX = image.bounds.left; currentY++; } } if (cursor != 0) { part = string(abi.encodePacked(part, _getChunk(cursor, buffer))); } rects = string(abi.encodePacked(rects, part)); } return rects; } /** * @notice Return a string that consists of all rects in the provided `buffer`. */ // prettier-ignore function _getChunk(uint256 cursor, string[16] memory buffer) private pure returns (string memory) { string memory chunk; for (uint256 i = 0; i < cursor; i += 4) { chunk = string( abi.encodePacked( chunk, '<rect width="', buffer[i], '" height="10" x="', buffer[i + 1], '" y="', buffer[i + 2], '" fill="#', buffer[i + 3], '" />' ) ); } return chunk; } /** * @notice Decode a single RLE compressed image into a `DecodedImage`. */ function _decodeRLEImage(bytes memory image) private pure returns (DecodedImage memory) { uint8 paletteIndex = uint8(image[0]); ContentBounds memory bounds = ContentBounds({ top: uint8(image[1]), right: uint8(image[2]), bottom: uint8(image[3]), left: uint8(image[4]) }); uint256 cursor; Rect[] memory rects = new Rect[]((image.length - 5) / 2); for (uint256 i = 5; i < image.length; i += 2) { rects[cursor] = Rect({ length: uint8(image[i]), colorIndex: uint8(image[i + 1]) }); cursor++; } return DecodedImage({ paletteIndex: paletteIndex, bounds: bounds, rects: rects }); } } // SPDX-License-Identifier: GPL-3.0 /// @title A library used to convert string to int /*********************************************************** @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@[email protected]@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@%[email protected]@@@@@@@@@@@@ [email protected]@@@@@@.............................. ./@@@@@@@@@[email protected]@@....*@@@@.......*@@@@@@@@@. ./@@@@@@@[email protected]@@@@[email protected]@@[email protected]@@@@[email protected]@@@@. @%[email protected]@[email protected]@[email protected]@@[email protected] @%**.........,**.........................................**@ @@@@##.....##(**####### ......... ,####### .......###@@@ @@@@@@[email protected]@@@# @@ @@ ......... ,@@ @@@ [email protected]@@@@@ @@@@@@[email protected]@# @@@@@@@ ......... ,@@@@@@@ [email protected]@@@@@ @@@@@@[email protected]@@@@ @@%............ [email protected]@@@@@ @@@@@@@@@..../@@@@@@@@@[email protected]@@@@@@@ @@@@@@@@@............ [email protected]@@@@@@@ @@@@@@@@@@@.......... @@@@@@@@@@@@@@% .........*@@@@@@@@@@ @@@@@@@@@@@@@%.... @@//////////////#@@ [email protected]@@@@@@@@@@@@ @@@@@@@@@@@@@@@@ @@@///////////////////@@ @@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@ ************************ @@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ ************************************************************/ pragma solidity ^0.8.6; library StringUtil { function parseInt(string memory _a) internal pure returns (uint _parsedInt) { return parseInt(_a, 0); } /** * @notice parse string to uint */ function parseInt(string memory _a, uint _b) internal pure returns (uint _parsedInt) { bytes memory bresult = bytes(_a); uint mint = 0; bool decimals = false; for (uint i = 0; i < bresult.length; i++) { if ((uint(uint8(bresult[i])) >= 48) && (uint(uint8(bresult[i])) <= 57)) { if (decimals) { if (_b == 0) { break; } else { _b--; } } mint *= 10; mint += uint(uint8(bresult[i])) - 48; } else if (uint(uint8(bresult[i])) == 46) { decimals = true; } } if (_b > 0) { mint *= 10 ** _b; } return mint; } } // 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 /// @title Base64 /// @author Brecht Devos - <[email protected]> /// @notice Provides a function for encoding some bytes in base64 library Base64 { string internal constant TABLE = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'; function encode(bytes memory data) internal pure returns (string memory) { if (data.length == 0) return ''; // load the table into memory string memory table = TABLE; // multiply by 4/3 rounded up uint256 encodedLen = 4 * ((data.length + 2) / 3); // add some extra buffer at the end required for the writing string memory result = new string(encodedLen + 32); assembly { // set the actual output length mstore(result, encodedLen) // prepare the lookup table let tablePtr := add(table, 1) // input ptr let dataPtr := data let endPtr := add(dataPtr, mload(data)) // result ptr, jump over length let resultPtr := add(result, 32) // run over the input, 3 bytes at a time for {} lt(dataPtr, endPtr) {} { dataPtr := add(dataPtr, 3) // read 3 bytes let input := mload(dataPtr) // write 4 characters mstore(resultPtr, shl(248, mload(add(tablePtr, and(shr(18, input), 0x3F))))) resultPtr := add(resultPtr, 1) mstore(resultPtr, shl(248, mload(add(tablePtr, and(shr(12, input), 0x3F))))) resultPtr := add(resultPtr, 1) mstore(resultPtr, shl(248, mload(add(tablePtr, and(shr( 6, input), 0x3F))))) resultPtr := add(resultPtr, 1) mstore(resultPtr, shl(248, mload(add(tablePtr, and( input, 0x3F))))) resultPtr := add(resultPtr, 1) } // padding with '=' 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; } }
Lock all Bitstray parts. This cannot be reversed and can only be called by the owner when not locked./
function lockParts() external override onlyOwner whenPartsNotLocked { arePartsLocked = true; emit PartsLocked(); }
11,850,179
pragma solidity >=0.4.0 <0.7.0; // Version 1.1 // Date: 08/14/19 /** * @dev Interace taken from OpenZeppelin template: * Standard interface that allows any tokens on Ethereum to be re-used by * other applications: from wallets to decentralized exchanges. * see link for OpenZeppelin Solidity contract below: * * https://github.com/OpenZeppelin/openzeppelin-contracts/contracts/token/ERC20/IERC20.sol * */ interface IERC20 { // Returns the total token supply. function totalSupply() external view returns (uint256); // Returns the account balance of another account with address `owner`. function balanceOf(address who) external view returns (uint256); // Returns the amount which `spender` is stil allowed to withdraw from `owner` function allowance(address owner, address spender) external view returns (uint256); /** * @dev Transfers `value` amount of tokens to address `to`, and MUST * fire the `Transfer` event. The function SHOULD `throw` if the * message caller's account balance does not have enough tokens to spend. * NOTE: Transfers of 0 values MUST be treated as normal transfers * and fire the `Transfer` */ function transfer(address to, uint256 value) external returns (bool); /** * @dev Allows `spender` to withdraw from your account multiple * times, up to the `value` amount. * If this function is called again it overwrites the current allowance * with `value` */ function approve(address spender, uint256 value) external returns (bool); /** * @dev Transfers `value` amount of tokens from address `from` * to address `to`, and MUST fire the `Transfer` event. * The `transferFrom` method is used for a withdraw workflow, * allowing contracts to transfer tokens+ on your behalf. * This can be used for example to allow a contract to transfer * tokens on your behalf and/or to charge fees in sub-currencies. * The function SHOULD `throw` unless the `from` account has deliberately * authorized the sender of the message via some mechanism. * NOTE: Transfers of 0 values MUST be treated as normal Transfers * and fire the `Transfer` event. */ function transferFrom(address from, address to, uint256) external returns (bool); /** * @dev MUST trigger when tokens are transferred, including * zero value transfers. A token contract which creates new * tokens SHOULD trigger a Transfer event with the `from` * address set to `0x0` when tokens are created. */ event Transfer( address indexed from, address indexed to, uint256 value ); /** * @dev MUST trigger on any successful call to * `approve(address spender, uint256 value)`. */ event Approval( address indexed owner, address indexed spender, uint256 value ); } /** * @dev see link for OpenZeppelin Solidity contract below: * * https://github.com/OpenZeppelin/openzeppelin-contracts/contracts/math/SafeMath.sol * */ library SafeMath { /** * @dev Multiplies two numbers, reverts 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, reverts * on division by zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0); // Solidity only automatically asserts when dividing by 0 uint256 c = a / b; // assert (a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Subtracts two numbers, reverts overflow (i.e. if subtragend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a); uint256 c = a - b; return c; } /** * @dev Adds two numbers, reverts on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } /** * @dev First division of `d` by `m`, then multiplying result by `m`. */ function ceil(uint256 a, uint256 m) internal pure returns (uint256) { uint256 c = add(a, m); uint256 d = sub(c, 1); return mul(div(d, m), m); } } /** * @dev The decimals are only for visualization purposes. * All the operations are done using the smallest and indivisible token unit, * just as on Ethereum all the operations are done in wei. * For reference, see: * * https://github.com/OpenZeppelin/openzeppelin-contracts/contracts/token/ERC20/ERC20Detailed.sol * */ contract ERC20Detailed is IERC20 { string private _name; string private _symbol; uint8 private _decimals; constructor(string memory name, string memory symbol, uint8 decimals) public { _name = name; _symbol = symbol; _decimals = decimals; } /** * @return the name of the token. */ function name() public view returns (string memory) { return _name; } /** * @return the symbol of the token. */ function symbol() public view returns (string memory) { return _symbol; } /** * @return the number of decimals of the token. */ function decimals() public view returns (uint8) { return _decimals; } } /** * @dev Boilerplate taken from `BOMBv3.sol`. * for reference, see link for Solidity contract below: * * https://etherscan.io/address/0x1C95b093d6C236d3EF7c796fE33f9CC6b8606714#code * */ contract UIUC_Token is ERC20Detailed { /** * @dev see `Using For` section under: * * https://solidity.readthedocs.io/en/v0.4.21/contracts.html#inheritance * * The directive `using A for B;` can be used to attach library functions * (from the library `A`) to any type (`B`). * These functions will receive the object they are called on as their * first parameter (like the `self` variable in Python). * * The effect of `using A for *;` is that the functions from the * library `A` are attached to any type. * * In both situations, all functions, even those where the type of * the first parameter does not match the type of the object, are * attached. * The type is checked at the point the function is called and function * overload resolution is performed. */ using SafeMath for uint256; // Using `mapping` to map `address` type to `uint256` type with name // `_balances`. mapping (address => uint256) private _balances; // Using `mapping` to map `address` type to the mapping of `address` // type to `uint256` type with name `_allowed`. mapping (address => mapping (address => uint256)) private _allowed; string constant tokenName = "UIUC_Token"; string constant tokenSymbol = "UIUC_Token"; uint8 constant tokenDecimals = 0; uint256 _totalSupply = 2090000; // Total initial percent for deflation calculations. uint256 public basePercent = 100; constructor() public payable ERC20Detailed(tokenName, tokenSymbol, tokenDecimals) { // Miniting new tokens _mint(msg.sender, _totalSupply); } // Queries... function totalSupply() public view returns (uint256) { return _totalSupply; } // Queries the balance of owner of tokens function balanceOf(address owner) public view returns (uint256) { return _balances[owner]; } function allowance(address owner, address spender) public view returns (uint256) { return _allowed[owner][spender]; } /** * @dev Changed calculation to find 0.5 percent instead of 1 percent of * total supply (calcuation as follows: 2090000 * 0.05 = 10450) */ function findHalfPercent(uint256 value) public view returns (uint256) { uint256 roundValue = value.ceil(basePercent); uint256 halfPercent = roundValue.mul(basePercent).div(10450); return halfPercent; } /** * @dev REVIEW and comment on this `transfer` function */ function transfer(address to, uint256 value) public returns (bool) { require(value <= _balances[msg.sender]); require(to != address(0)); uint256 tokensToBurn = findHalfPercent(value); uint256 tokensToTransfer = value.sub(tokensToBurn); _balances[msg.sender] = _balances[msg.sender].sub(value); _balances[to] = _balances[to].add(tokensToTransfer); _totalSupply = _totalSupply.sub(tokensToBurn); emit Transfer(msg.sender, to, tokensToTransfer); emit Transfer(msg.sender, address(0), tokensToBurn); return true; } /** * @dev REVIEW and comment on this `multiTransfer` function */ function multiTransfer(address[] memory receivers, uint256[] memory amounts) public { for (uint256 i = 0; i < receivers.length; i++) { transfer(receivers[i], amounts[i]); } } /** * @dev REVIEW and comment on this `approve` function */ function approve(address spender, uint256 value) public returns (bool) { require(spender != address(0)); _allowed[msg.sender][spender] = value; emit Approval(msg.sender, spender, value); return true; } /** * @dev REVIEW and comment on this `transferFrom` function */ function transferFrom(address from, address to, uint256 value) public returns (bool) { require(value <= _balances[from]); require(value <= _allowed[from][msg.sender]); require(to != address(0)); _balances[from] = _balances[from].sub(value); uint256 tokensToBurn = findHalfPercent(value); uint256 tokensToTransfer = value.sub(tokensToBurn); _balances[to] = _balances[to].add(tokensToTransfer); _totalSupply = _totalSupply.sub(tokensToBurn); _allowed[from][msg.sender] = _allowed[from][msg.sender].sub(value); emit Transfer(from, to, tokensToTransfer); emit Transfer(from, address(0), tokensToBurn); return true; } /** * @dev REVIEW and comment on this `increaseAllowance` function */ function increaseAllowance(address spender, uint256 addedValue) public returns (bool) { require(spender != address(0)); _allowed[msg.sender][spender] = (_allowed[msg.sender][spender].add(addedValue)); emit Approval(msg.sender, spender, _allowed[msg.sender][spender]); return true; } /** * @dev REVIEW and comment on this `decreaseAllowance` function */ function decreaseAllowance(address spender, uint256 subtractedValue) public returns (bool) { require(spender != address(0)); _allowed[msg.sender][spender] = (_allowed[msg.sender][spender].sub(subtractedValue)); emit Approval(msg.sender, spender, _allowed[msg.sender][spender]); return true; } /** * @dev REVIEW Minting of new tokens by ...... account */ function _mint(address account, uint256 amount) internal { require(amount != 0); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } /** * @dev REVIEW and comment on this `burn` function */ function burn(uint256 amount) external { _burn(msg.sender, amount); } /** * @dev REVIEW and comment on this `_burn` function */ function _burn(address account, uint256 amount) internal { require(amount != 0); require(amount <= _balances[account]); _totalSupply = _totalSupply.sub(amount); _balances[account] = _balances[account].sub(amount); emit Transfer(account, address(0), amount); } /** * @dev REVIEW and comment on this `burnFrom` function */ function burnFrom(address account, uint256 amount) external { require(amount <= _allowed[account][msg.sender]); _allowed[account][msg.sender] = _allowed[account][msg.sender].sub(amount); _burn(account, amount); } } ///////////////////////////////////////////////////////////////////////////////// /** * @dev Old code from 08/06/19 * * REVIEW if needed */ // // Adding fixed supply for ERC20 token/cryptocurrency // constructor() public { // // Using the internal function `_mint` to implement fixed token supply of... // // in our case this is 20.9 Million -- this is excluding the effect of the // // deflation rate. // // Where is this supply stored?? // // Need to be able to call the address where the supply is stored to // // later burn. // _mint(msg.sender, 2090000); // 2.09 Million fixed total token supply // } // // Intuition: // // Encapsulating state (like done above) makes it safer to extend contracts. // // For instance, manually keeping `totalSupply` in sync with modified // // balances is easy to forget. // // In fact, the `Transfer` is an event required by the standard and is also // // easily forgetten, `Transfer` is also an event relied on by some clients. // // Note how the internal `_mint()` function takes care of these functions. // // The internal `_mint` is the key building block that allows us to write // // ERC20 extensions that implement a supply mechansim. // // The mechanism we will implement is a token reward for the miners that // // produce Ethereum blocks. // // In Solidity, we can access the address of the current block's miner in // // the global variable `block.coinbase`. // // function mintMinerReward() public { // // _mint(block.coinbase, 1999); // // } // } // // This contract `MinerRewardMinter` below, when initialized with an // // `ERC20Mintable` instance, will result in exactly the same behaviour // // implemented in the above `UIUC_Token` contract. // contract MinerRewardMinter { // ERC20Mintable _token; // constructor(ERC20Mintable token) public { // _token = token; // } // // In Solidity we can access the address of the current block's miner in // // the global variable `block.coinbase` -- thus, we are minting a new token // // reward to this `block.coinbase` address whenever someon calls the function // // `mintMinerReward` on our token. // function mintMinerReward() public { // // `block.coinbase` is a constantly changing address based on whoever mined // // the last TX in the previous block and now begins the next block with // // the coinbase. // _token.mint(block.coinbase, 1999); // } // } // // ToDo: // // What is interesting about using `ERC20Mintable` is that we can easily // // combine multiple supply mechanisms by assigning the role to multiple // // contracts, and we can do this dynamically (DEFLATION!). // contract DeflationMinter is ERC20Burnable, ERC20Detailed { // ERC20Mintable _token; // constructor(ERC20Mintable token) public { // _token = token; // } // function burnTokens() public { // // Burn 5% of total supply after every transaction // _burn(msg.sender, 199); // Burning fixed supply of 199 tokens // } // }
Integer division of two numbers truncating the quotient, reverts on division by zero./ assert (a == b c + a % b); There is no case in which this doesn't hold
function div(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a / b; return c; }
1,806,716
./full_match/56/0x0b0D3e03E7d49F8b82bFeB2Aee3386F5fE274527/sources/project_/contracts/Ownable.sol
Event OwnershipTransferred is used to log that a ownership change of the token has occured/ Modifier We create our own function modifier called onlyOwner, it will Require the current owner to be the same as msg.sender/ This _; is not a TYPO, It is important for the compiler;
modifier onlyOwner() { require( _owner == msg.sender, "Ownable: only owner can call this function" ); _; }
3,249,672
./full_match/1/0x990f58570b4C7b8b7ae3Bc28EFEB2724bE111545/sources/contracts/utils/WadRayMath.sol
Multiplies two ray, rounding half up to the nearest ray. x Ray. y Ray. return z The result of x y, in ray. Let y > 0 Overflow if (x y + HALF_RAY) > type(uint256).max <=> x y > type(uint256).max - HALF_RAY <=> x > (type(uint256).max - HALF_RAY) / y
function rayMul(uint256 x, uint256 y) internal pure returns (uint256 z) { assembly { if mul(y, gt(x, div(MAX_UINT256_MINUS_HALF_RAY, y))) { revert(0, 0) } z := div(add(mul(x, y), HALF_RAY), RAY) } }
17,128,488
./partial_match/1/0x08E1451D4f34cD67E9b4647bCcb251483EeeC6D7/sources/MultiSigStub.sol
Web3 call functions/
function tokenBalances(address tokenAddress) public constant delegated returns (uint) { }
9,309,955
// to test issue with nodes breaking with large clients over WS // fixed in web3 with fragmentationThreshold: 8192 pragma solidity ^0.4.17; contract BigFreakingContract { event Transfer(address indexed from, address indexed to, uint value); event Approval( address indexed owner, address indexed spender, uint value); mapping( address => uint ) _balances; mapping( address => mapping( address => uint ) ) _approvals; uint public _supply; constructor( uint initial_balance ) public { _balances[msg.sender] = initial_balance; _supply = initial_balance; } function totalSupply() public constant returns (uint supply) { return _supply; } function balanceOf( address who ) public constant returns (uint value) { return _balances[who]; } function transfer( address to, uint value) public returns (bool ok) { if( _balances[msg.sender] < value ) { revert(); } if( !safeToAdd(_balances[to], value) ) { revert(); } _balances[msg.sender] -= value; _balances[to] += value; emit Transfer( msg.sender, to, value ); return true; } function transferFrom( address from, address to, uint value) public returns (bool ok) { // if you don't have enough balance, throw if( _balances[from] < value ) { revert(); } // if you don't have approval, throw if( _approvals[from][msg.sender] < value ) { revert(); } if( !safeToAdd(_balances[to], value) ) { revert(); } // transfer and return true _approvals[from][msg.sender] -= value; _balances[from] -= value; _balances[to] += value; emit Transfer( from, to, value ); return true; } function approve(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function allowance(address owner, address spender) public constant returns (uint _allowance) { return _approvals[owner][spender]; } function safeToAdd(uint a, uint b) internal pure returns (bool) { return (a + b >= a); } function isAvailable() public pure returns (bool) { return false; } function approve_1(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_2(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_3(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_4(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_5(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_6(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_7(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_8(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_9(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_10(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_11(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_12(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_13(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_14(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_15(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_16(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_17(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_18(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_19(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_20(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_21(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_22(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_23(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_24(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_25(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_26(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_27(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_28(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_29(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_30(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_31(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_32(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_33(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_34(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_35(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_36(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_37(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_38(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_39(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_40(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_41(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_42(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_43(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_44(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_45(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_46(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_47(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_48(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_49(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_50(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_51(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_52(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_53(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_54(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_55(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_56(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_57(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_58(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_59(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_60(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_61(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_62(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_63(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_64(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_65(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_66(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_67(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_68(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_69(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_70(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_71(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_72(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_73(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_74(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_75(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_76(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_77(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_78(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_79(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_80(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_81(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_82(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_83(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_84(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_85(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_86(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_87(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_88(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_89(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_90(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_91(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_92(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_93(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_94(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_95(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_96(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_97(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_98(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_99(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_100(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_101(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_102(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_103(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_104(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_105(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_106(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_107(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_108(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_109(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_110(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_111(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_112(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_113(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_114(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_115(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_116(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_117(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_118(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_119(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_120(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_121(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_122(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_123(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_124(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_125(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_126(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_127(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_128(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_129(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_130(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_131(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_132(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_133(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_134(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_135(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_136(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_137(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_138(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_139(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_140(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_141(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_142(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_143(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_144(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_145(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_146(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_147(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_148(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_149(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_150(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_151(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_152(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_153(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_154(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_155(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_156(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_157(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_158(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_159(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_160(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_161(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_162(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_163(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_164(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_165(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_166(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_167(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_168(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_169(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_170(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_171(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_172(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_173(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_174(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_175(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_176(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_177(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_178(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_179(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_180(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_181(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_182(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_183(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_184(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_185(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_186(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_187(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_188(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_189(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_190(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_191(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_192(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_193(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_194(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_195(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_196(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_197(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_198(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_199(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_200(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_201(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_202(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_203(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_204(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_205(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_206(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_207(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_208(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_209(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_210(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_211(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_212(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_213(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_214(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_215(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_216(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_217(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_218(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_219(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_220(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_221(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_222(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_223(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_224(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_225(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_226(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_227(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_228(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_229(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_230(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_231(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_232(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_233(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_234(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_235(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_236(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_237(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_238(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_239(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_240(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_241(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_242(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_243(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_244(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_245(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_246(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_247(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_248(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_249(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_250(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_251(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_252(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_253(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_254(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_255(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_256(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_257(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_258(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_259(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_260(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_261(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_262(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_263(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_264(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_265(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_266(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_267(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_268(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_269(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_270(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_271(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_272(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_273(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_274(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_275(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_276(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_277(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_278(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_279(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_280(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_281(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_282(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_283(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_284(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_285(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_286(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_287(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_288(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_289(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_290(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_291(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_292(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_293(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_294(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_295(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_296(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_297(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_298(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_299(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_300(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_301(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_302(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_303(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_304(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_305(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_306(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_307(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_308(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_309(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_310(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_311(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_312(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_313(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_314(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_315(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_316(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_317(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_318(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_319(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_320(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_321(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_322(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_323(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_324(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_325(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_326(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_327(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_328(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_329(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_330(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_331(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_332(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_333(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_334(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_335(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_336(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_337(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_338(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_339(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_340(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_341(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_342(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_343(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_344(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_345(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_346(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_347(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_348(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_349(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_350(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_351(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_352(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_353(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_354(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_355(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_356(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_357(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_358(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_359(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_360(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_361(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_362(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_363(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_364(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_365(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_366(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_367(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_368(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_369(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_370(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_371(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_372(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_373(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_374(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_375(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_376(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_377(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_378(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_379(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_380(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_381(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_382(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_383(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_384(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_385(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_386(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_387(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_388(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_389(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_390(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_391(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_392(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_393(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_394(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_395(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_396(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_397(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_398(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_399(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_400(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_401(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_402(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_403(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_404(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_405(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_406(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_407(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_408(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_409(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_410(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_411(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_412(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_413(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_414(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_415(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_416(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_417(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_418(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_419(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_420(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_421(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_422(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_423(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_424(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_425(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_426(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_427(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_428(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_429(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_430(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_431(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_432(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_433(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_434(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_435(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_436(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_437(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_438(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_439(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_440(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_441(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_442(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_443(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_444(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_445(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_446(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_447(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_448(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_449(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_450(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_451(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_452(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_453(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_454(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_455(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_456(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_457(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_458(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_459(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_460(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_461(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_462(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_463(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_464(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_465(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_466(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_467(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_468(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_469(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_470(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_471(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_472(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_473(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_474(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_475(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_476(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_477(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_478(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_479(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_480(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_481(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_482(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_483(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_484(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_485(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_486(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_487(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_488(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_489(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_490(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_491(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_492(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_493(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_494(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_495(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_496(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_497(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_498(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_499(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_500(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_501(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_502(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_503(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_504(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_505(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_506(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_507(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_508(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_509(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_510(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_511(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_512(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_513(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_514(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_515(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_516(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_517(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_518(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_519(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_520(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_521(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_522(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_523(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_524(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_525(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_526(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_527(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_528(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_529(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_530(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_531(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_532(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_533(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_534(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_535(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_536(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_537(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_538(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_539(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_540(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_541(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_542(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_543(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_544(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_545(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_546(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_547(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_548(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_549(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_550(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_551(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_552(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_553(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_554(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_555(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_556(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_557(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_558(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_559(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_560(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_561(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_562(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_563(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_564(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_565(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_566(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_567(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_568(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_569(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_570(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_571(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_572(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_573(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_574(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_575(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_576(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_577(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_578(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_579(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_580(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_581(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_582(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_583(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_584(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_585(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_586(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_587(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_588(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_589(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_590(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_591(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_592(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_593(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_594(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_595(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_596(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_597(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_598(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_599(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_600(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_601(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_602(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_603(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_604(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_605(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_606(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_607(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_608(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_609(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_610(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_611(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_612(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_613(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_614(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_615(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_616(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_617(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_618(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_619(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_620(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_621(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_622(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_623(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_624(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_625(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_626(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_627(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_628(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_629(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_630(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_631(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_632(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_633(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_634(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_635(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_636(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_637(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_638(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_639(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_640(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_641(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_642(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_643(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_644(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_645(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_646(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_647(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_648(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_649(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_650(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_651(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_652(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_653(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_654(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_655(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_656(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_657(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_658(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_659(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_660(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_661(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_662(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_663(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_664(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_665(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_666(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_667(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_668(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_669(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_670(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_671(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_672(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_673(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_674(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_675(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_676(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_677(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_678(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_679(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_680(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_681(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_682(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_683(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_684(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_685(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_686(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_687(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_688(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_689(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_690(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_691(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_692(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_693(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_694(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_695(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_696(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_697(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_698(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_699(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_700(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_701(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_702(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_703(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_704(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_705(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_706(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_707(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_708(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_709(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_710(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_711(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_712(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_713(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_714(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_715(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_716(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_717(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_718(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_719(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_720(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_721(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_722(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_723(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_724(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_725(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_726(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_727(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_728(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_729(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_730(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_731(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_732(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_733(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_734(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_735(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_736(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_737(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_738(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_739(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_740(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_741(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_742(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_743(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_744(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_745(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_746(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_747(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_748(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_749(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_750(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_751(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_752(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_753(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_754(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_755(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_756(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_757(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_758(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_759(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_760(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_761(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_762(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_763(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_764(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_765(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_766(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_767(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_768(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_769(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_770(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_771(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_772(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_773(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_774(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_775(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_776(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_777(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_778(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_779(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_780(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_781(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_782(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_783(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_784(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_785(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_786(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_787(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_788(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_789(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_790(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_791(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_792(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_793(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_794(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_795(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_796(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_797(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_798(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_799(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_800(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_801(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_802(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_803(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_804(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_805(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_806(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_807(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_808(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_809(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_810(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_811(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_812(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_813(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_814(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_815(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_816(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_817(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_818(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_819(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_820(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_821(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_822(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_823(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_824(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_825(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_826(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_827(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_828(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_829(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_830(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_831(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_832(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_833(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_834(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_835(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_836(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_837(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_838(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_839(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_840(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_841(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_842(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_843(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_844(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_845(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_846(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_847(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_848(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_849(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_850(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_851(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_852(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_853(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_854(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_855(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_856(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_857(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_858(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_859(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_860(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_861(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_862(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_863(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_864(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_865(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_866(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_867(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_868(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_869(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_870(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_871(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_872(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_873(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_874(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_875(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_876(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_877(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_878(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_879(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_880(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_881(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_882(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_883(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_884(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_885(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_886(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_887(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_888(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_889(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_890(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_891(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_892(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_893(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_894(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_895(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_896(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_897(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_898(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_899(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_900(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_901(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } }
TODO: should increase instead
function approve_180(address spender, uint value) public returns (bool ok) { _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; }
6,453,893
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "hardhat/console.sol"; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; //import "@openzeppelin/contracts-upgradeable/token/ERC20/ERC20Upgradeable.sol"; contract DogCoin is ERC20 //ERC20Upgradeable { event AddedHolder(address indexed account); event RemovedHolder(address indexed account); mapping(address => uint256) public holderIndexes; //Holder#1, Holder#2 (index starts at 1) address[] public holders; //TODO rename to holderAccounts constructor() ERC20("dogcoin", "DOG") { _mint(msg.sender, 1000); // holder is new, should subscribe to array holders.push(msg.sender); holderIndexes[msg.sender] = holders.length; emit AddedHolder(msg.sender); } /* function initialize() public initializer { __ERC20_init("dogcoin", "DOG"); _mint(msg.sender, 1000); // holder is new, should subscribe to array holders.push(msg.sender); holderIndexes[msg.sender] = holders.length; emit AddedHolder(msg.sender); } */ function transfer(address to, uint256 amount) public override returns (bool) { super.transfer(to, amount); if (holderIndexes[to] == 0) { // holder is new, should subscribe to array holders.push(to); holderIndexes[to] = holders.length; emit AddedHolder(to); } if (balanceOf(msg.sender) == 0) { // sender is broke, should remove it from holder lists uint256 freeIndex = holderIndexes[msg.sender]; holders[freeIndex - 1] = holders[holders.length - 1]; //relocate last holder to now-free slot holders.pop(); // delete previous holder from tail (ensures no duplicate) holderIndexes[to] = freeIndex; //store new index of relocated holder emit RemovedHolder(msg.sender); } console.log("Transferred to: ", to); return true; } /* function mint(address account, uint256 amount) public onlyOwner returns (bool) { _mint(account, amount); if (holderIndexes[account] == 0) { // holder is new, should subscribe to array holders.push(account); holderIndexes[account] = holders.length; emit AddedHolder(account); } return true; } */ function getTotalHolders() public view returns (uint256) { return holders.length; } function getHolderIndexOf(address account) public view returns (uint256) { return holderIndexes[account]; } }
holder is new, should subscribe to array
function mint(address account, uint256 amount) public onlyOwner returns (bool) { _mint(account, amount); if (holderIndexes[account] == 0) { holders.push(account); holderIndexes[account] = holders.length; emit AddedHolder(account); } return true; }
1,000,929