file_name
stringlengths
71
779k
comments
stringlengths
0
29.4k
code_string
stringlengths
20
7.69M
__index_level_0__
int64
2
17.2M
./full_match/1/0xAef3d07C724CFa27Cd57C5e0a49cE372dA766413/sources/contracts/alloyx/interfaces/IRibbonDesk.sol
IRibbonDesk AlloyX/
interface IRibbonDesk { function getRibbonWalletUsdcValue(address _alloyxVault) external view returns (uint256); function getRibbonUsdcValueOfVault(address _vaultAddress, address _ribbonVault) external view returns (uint256); function deposit( address _vaultAddress, address _ribbonVault, uint256 _amount ) external; function initiateWithdraw( address _vaultAddress, address _ribbonVault, uint256 _numShares ) external; function completeWithdraw(address _vaultAddress, address _poolAddress) external; function withdrawInstantly( address _vaultAddress, address _ribbonVault, uint256 _amount ) external; function getRibbonVaultAddressesForAlloyxVault(address _vaultAddress) external view returns (address[] memory); function getRibbonVaultShareForAlloyxVault(address _vaultAddress, address _ribbonVault) external view returns (uint256); pragma solidity ^0.8.7; }
3,134,213
pragma solidity >=0.5.2; // ---------------------------------------------------------------------------- // Borrowed from BokkyPooBah's Fixed Supply Token 👊 + Factory v1.10 // https://github.com/bokkypoobah/FixedSupplyTokenFactory // // // // Snappframes Factory Contract // // Enjoy. (c) BokkyPooBah / Bok Consulting Pty Ltd 2019. The MIT Licence. // ---------------------------------------------------------------------------- import "./dependencies/SafeMath.sol"; import "./dependencies/Owned.sol"; // import "./Snappframes.sol"; // import "../circuits/verifier.sol"; contract MiMC{ function MiMCpe7(uint,uint) public pure returns (uint) {} } contract EdDSA{ function Verify( uint256[2] memory, uint256, uint256[2] memory, uint256 ) public view returns (bool) {} } contract Snappframes is Owned, EdDSA, MiMC { using SafeMath for uint; using SafeMath for uint256; string public symbol; string public name; uint256 public totalSupply; uint256 public dataHash; uint256 public stateHash; address public operator; uint256 public pricePerFrame; address[4] depositQueueAddresses; mapping(address => uint) depositQueue; mapping(address => uint256[2]) public ecdsaToEddsa; uint8 DEPOSIT_QUEUE_MAX = 4; uint8 depositQueueLength = 0; uint public TREE_DEPTH = 6; uint PRICE_PER_FRAME = 1000; // Verifier verifier; MiMC mimc; EdDSA eddsa; event Deposit(address _depositor, uint _index); event DepositsProcessed(address _firstDepositor, address _lastDepositor); function init(address tokenOwner, string memory _symbol, string memory _name, uint256 _totalSupply, uint256 _dataHash, uint256 _stateHash, address _mimcAddr, address _eddsaAddr) public { super.init(tokenOwner); symbol = _symbol; name = _name; totalSupply = _totalSupply; dataHash = _dataHash; stateHash = _stateHash; mimc = MiMC(_mimcAddr); eddsa = EdDSA(_eddsaAddr); } // performs state transition function update() public onlyOwner { // TODO: wait for Geoff's verifier circuit } // creates accounts for people who deposit Ether // @dev _from and _to are index ranges for movie frames function deposit(uint256 _index, uint256[2] memory _eddsaPubKey) public payable { require(depositQueueLength <= DEPOSIT_QUEUE_MAX); require(msg.value >= PRICE_PER_FRAME); depositQueueLength++; depositQueueAddresses[depositQueueLength - 1] = msg.sender; depositQueue[msg.sender] = _index; ecdsaToEddsa[msg.sender] = _eddsaPubKey; emit Deposit(msg.sender, _index); } // operator updates merkle tree with deposits function processDepositQueue() public onlyOwner { emit DepositsProcessed( depositQueueAddresses[0], depositQueueAddresses[DEPOSIT_QUEUE_MAX]); depositQueueLength = 0; } // allows withdraw of ERC721 token to Ethereum address function withdraw( uint256 asset, uint256[2] memory pubkey, //EdDSA pubKey_x and pubKey_y uint256[7] memory proof, uint256[7] memory proof_pos, uint256 root // uint256 hashed_msg, //hash of msg.sender and leaf // uint256[2] memory R, //EdDSA signature field // uint256 s //EdDSA signature field ) public view { uint256[2] memory eddsaPubKey = ecdsaToEddsa[msg.sender]; require(eddsaPubKey[0] == pubkey[0] && eddsaPubKey[1] == pubkey[1]); // // verify EdDSA signature // require(EdDSA.Verify(pubkey, hashed_msg, R, s)); // verify hashed msg sends leaf to msg.sender uint256 leaf = mimc.MiMCpe7(mimc.MiMCpe7(pubkey[0], pubkey[1]), asset); require(verifyMerkleProof(leaf, proof, proof_pos, root)); // require(mimc.MiMCpe7(msg.sender, leaf) == hashed_msg); // generate ERC721 token // bytes32 tokenId = keccak256(abi.encodePacked(pubkey[0],pubkey[1])); //_mint(msg.sender, bytes32ToUint256(tokenId)); // send token to depositor on Ethereum } function verifyMerkleProof( uint256 _leafHash, uint256[7] memory _merkleProof, uint256[7] memory _merklePos, uint256 _root ) public view returns(bool){ uint256[7] memory root; uint256 left = _leafHash - _merklePos[0]*(_leafHash - _merkleProof[0]); uint256 right = _merkleProof[0] - _merklePos[0]*(_merkleProof[0] - _leafHash); root[0] = mimc.MiMCpe7(left, right); for (uint i = 1; i < 3; i++) { left = root[i-1] - _merklePos[i]*(root[i-1] - _merkleProof[0]); right = _merkleProof[0] - _merklePos[i]*(_merkleProof[0] - root[i-1]); root[i] = mimc.MiMCpe7(left, right); } return(root[2] == _root); } // helpers // https://ethereum.stackexchange.com/questions/6498/how-to-convert-a-uint256-type-integer-into-a-bytes32 function bytes32ToUint256(bytes32 n) internal pure returns (uint256) { return uint256(n); } } // ---------------------------------------------------------------------------- // // ---------------------------------------------------------------------------- contract SnappframesFactory is Owned { using SafeMath for uint; address public newAddress; uint public minimumFee = 0.1 ether; mapping(address => bool) public isChild; address[] public children; event FactoryDeprecated(address _newAddress); event MinimumFeeUpdated(uint oldFee, uint newFee); event TokenDeployed(address indexed owner, address indexed token, string symbol, string name, uint256 totalSupply, uint256 dataHash, uint256 stateHash); constructor () public { super.init(msg.sender); } function numberOfChildren() public view returns (uint) { return children.length; } function deprecateFactory(address _newAddress) public onlyOwner { require(newAddress == address(0)); emit FactoryDeprecated(_newAddress); newAddress = _newAddress; } function setMinimumFee(uint _minimumFee) public onlyOwner { emit MinimumFeeUpdated(minimumFee, _minimumFee); minimumFee = _minimumFee; } function deployTokenContract(string memory symbol, string memory name, uint256 totalSupply, uint256 dataHash, uint256 stateHash,address mimcAddr, address eddsaAddr) public payable returns (Snappframes token) { require(msg.value >= minimumFee); require(totalSupply > 0); token = new Snappframes(); token.init(msg.sender, symbol, name, totalSupply, dataHash, stateHash, mimcAddr, eddsaAddr ); isChild[address(token)] = true; children.push(address(token)); if (msg.value > 0) { owner.transfer(msg.value); } emit TokenDeployed(owner, address(token), symbol, name, totalSupply, dataHash, stateHash); } function () external payable { revert(); } }
allows withdraw of ERC721 token to Ethereum address uint256 hashed_msg, hash of msg.sender and leaf uint256[2] memory R, EdDSA signature field uint256 s EdDSA signature field verify EdDSA signature require(EdDSA.Verify(pubkey, hashed_msg, R, s)); verify hashed msg sends leaf to msg.sender require(mimc.MiMCpe7(msg.sender, leaf) == hashed_msg); generate ERC721 token bytes32 tokenId = keccak256(abi.encodePacked(pubkey[0],pubkey[1]));_mint(msg.sender, bytes32ToUint256(tokenId)); send token to depositor on Ethereum
function withdraw( uint256 asset, uint256[7] memory proof, uint256[7] memory proof_pos, uint256 root ) public view { uint256[2] memory eddsaPubKey = ecdsaToEddsa[msg.sender]; require(eddsaPubKey[0] == pubkey[0] && eddsaPubKey[1] == pubkey[1]); uint256 leaf = mimc.MiMCpe7(mimc.MiMCpe7(pubkey[0], pubkey[1]), asset); require(verifyMerkleProof(leaf, proof, proof_pos, root)); }
966,296
./partial_match/1/0x1075b82974490c604B76c49fFE91728595767ea1/sources/PrometheumProdigy.sol
Calculates the current reflection supply and token supply, considering excluded addresses. return The current reflection supply and token supply./
function _getCurrentSupply() private view returns(uint256, uint256) { uint256 rSupply = _rTotal; uint256 tSupply = _tTotal; uint256 len = _excluded.length; for (uint256 i = 0; i < len; 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); }
9,309,224
./full_match/43113/0x1Db514148505888ac19Fd70EA1fF4DBfBE2a3933/sources/contracts/MasterChef.sol
Deposit LP tokens to MasterChef for DCAU allocation. We are considering tokens which takes accounts fees when trasnsferring such like reflect finance We split this fee to feeAddress and Dragon Nest supporters - 90% 10%
function deposit(uint256 _pid, uint256 _amount) external nonReentrant { require(_pid < poolInfo.length, "Dragon: Non-existent pool"); PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; updatePool(_pid); if (user.amount > 0) { uint256 pending = ((user.amount * pool.accDCAUPerShare) / 1e12) - user.rewardDebt; if (pending > 0) { safeDcauTransfer(msg.sender, pending); } } if (_amount > 0) { IERC20 _lpToken = pool.lpToken; { uint256 balanceBefore = _lpToken.balanceOf(address(this)); _lpToken.safeTransferFrom(address(msg.sender), address(this), _amount); _amount = _lpToken.balanceOf(address(this)) - balanceBefore; require(_amount > 0, "We only accept amount > 0"); } if (pool.depositFeeBP > 0) { uint256 depositFee = (_amount * pool.depositFeeBP) / 10000; _lpToken.safeTransfer(FEEADDRESS, (depositFee * 9000) / 10000); poolDragonNestInfo[_pid].pendingDepFee += (depositFee * 1000) / 10000; user.amount = user.amount + _amount - depositFee; pool.lpSupply = pool.lpSupply + _amount - depositFee; user.amount = user.amount + _amount; pool.lpSupply = pool.lpSupply + _amount; } } user.rewardDebt = (user.amount * pool.accDCAUPerShare) / 1e12; emit Deposit(msg.sender, _pid, _amount); }
13,190,970
pragma solidity ^0.4.2; // @title Interface for contracts conforming to ERC-721: Non-Fungible Tokens // @author Dieter Shirley <[email protected]> (https://github.com/dete) contract ERC721 { // Required methods function approve(address _to, uint256 _tokenId) public; function balanceOf(address _owner) public view returns (uint256 balance); function implementsERC721() public pure returns (bool); function ownerOf(uint256 _tokenId) public view returns (address addr); function takeOwnership(uint256 _tokenId) public; function totalSupply() public view returns (uint256 total); function transferFrom(address _from, address _to, uint256 _tokenId) public; function transfer(address _to, uint256 _tokenId) public; event Transfer(address indexed from, address indexed to, uint256 tokenId); event Approval(address indexed owner, address indexed approved, uint256 tokenId); } contract Elements is ERC721 { /*** EVENTS ***/ // @dev The Birth event is fired whenever a new element comes into existence. event Birth(uint256 tokenId, string name, address owner); // @dev The TokenSold event is fired whenever a token is sold. event TokenSold(uint256 tokenId, uint256 oldPrice, uint256 newPrice, address prevOwner, address winner, string name); // @dev Transfer event as defined in current draft of ERC721. Ownership is assigned, including births. event Transfer(address from, address to, uint256 tokenId); /*** CONSTANTS, VARIABLES ***/ // @notice Name and symbol of the non fungible token, as defined in ERC721. string public constant NAME = "CryptoElements"; // solhint-disable-line string public constant SYMBOL = "CREL"; // solhint-disable-line uint256 private periodicStartingPrice = 5 ether; uint256 private elementStartingPrice = 0.005 ether; uint256 private scientistStartingPrice = 0.1 ether; uint256 private specialStartingPrice = 0.05 ether; uint256 private firstStepLimit = 0.05 ether; uint256 private secondStepLimit = 0.75 ether; uint256 private thirdStepLimit = 3 ether; bool private periodicTableExists = false; uint256 private elementCTR = 0; uint256 private scientistCTR = 0; uint256 private specialCTR = 0; uint256 private constant elementSTART = 1; uint256 private constant scientistSTART = 1000; uint256 private constant specialSTART = 10000; uint256 private constant specialLIMIT = 5000; /*** STORAGE ***/ // @dev A mapping from element IDs to the address that owns them. All elements have // some valid owner address. mapping (uint256 => address) public elementIndexToOwner; // @dev A mapping from owner address to count of tokens that address owns. // Used internally inside balanceOf() to resolve ownership count. mapping (address => uint256) private ownershipTokenCount; // @dev A mapping from ElementIDs to an address that has been approved to call // transferFrom(). Each Element can only have one approved address for transfer // at any time. A zero value means no approval is outstanding. mapping (uint256 => address) public elementIndexToApproved; // @dev A mapping from ElementIDs to the price of the token. mapping (uint256 => uint256) private elementIndexToPrice; // The addresses of the accounts (or contracts) that can execute actions within each roles. address public ceoAddress; address public cooAddress; /*** DATATYPES ***/ struct Element { uint256 tokenId; string name; uint256 scientistId; } mapping(uint256 => Element) elements; uint256[] tokens; /*** ACCESS MODIFIERS ***/ // @dev Access modifier for CEO-only functionality modifier onlyCEO() { require(msg.sender == ceoAddress); _; } // @dev Access modifier for COO-only functionality modifier onlyCOO() { require(msg.sender == cooAddress); _; } // Access modifier for contract owner only functionality modifier onlyCLevel() { require( msg.sender == ceoAddress || msg.sender == cooAddress ); _; } /*** CONSTRUCTOR ***/ function Elements() public { ceoAddress = msg.sender; cooAddress = msg.sender; createContractPeriodicTable("Periodic"); } /*** PUBLIC FUNCTIONS ***/ // @notice Grant another address the right to transfer token via takeOwnership() and transferFrom(). // @param _to The address to be granted transfer approval. Pass address(0) to // clear all approvals. // @param _tokenId The ID of the Token that can be transferred if this call succeeds. // @dev Required for ERC-721 compliance. function approve(address _to, uint256 _tokenId) public { // Caller must own token. require(_owns(msg.sender, _tokenId)); elementIndexToApproved[_tokenId] = _to; Approval(msg.sender, _to, _tokenId); } // For querying balance of a particular account // @param _owner The address for balance query // @dev Required for ERC-721 compliance. function balanceOf(address _owner) public view returns (uint256 balance) { return ownershipTokenCount[_owner]; } // @notice Returns all the relevant information about a specific element. // @param _tokenId The tokenId of the element of interest. function getElement(uint256 _tokenId) public view returns ( uint256 tokenId, string elementName, uint256 sellingPrice, address owner, uint256 scientistId ) { Element storage element = elements[_tokenId]; tokenId = element.tokenId; elementName = element.name; sellingPrice = elementIndexToPrice[_tokenId]; owner = elementIndexToOwner[_tokenId]; scientistId = element.scientistId; } function implementsERC721() public pure returns (bool) { return true; } // For querying owner of token // @param _tokenId The tokenID for owner inquiry // @dev Required for ERC-721 compliance. function ownerOf(uint256 _tokenId) public view returns (address owner) { owner = elementIndexToOwner[_tokenId]; require(owner != address(0)); } function payout(address _to) public onlyCLevel { _payout(_to); } // Allows someone to send ether and obtain the token function purchase(uint256 _tokenId) public payable { address oldOwner = elementIndexToOwner[_tokenId]; address newOwner = msg.sender; uint256 sellingPrice = elementIndexToPrice[_tokenId]; // Making sure token owner is not sending to self require(oldOwner != newOwner); require(sellingPrice > 0); // Safety check to prevent against an unexpected 0x0 default. require(_addressNotNull(newOwner)); // Making sure sent amount is greater than or equal to the sellingPrice require(msg.value >= sellingPrice); uint256 ownerPayout = SafeMath.mul(SafeMath.div(sellingPrice, 100), 96); uint256 purchaseExcess = SafeMath.sub(msg.value, sellingPrice); uint256 feeOnce = SafeMath.div(SafeMath.sub(sellingPrice, ownerPayout), 4); uint256 fee_for_dev = SafeMath.mul(feeOnce, 2); // Pay previous tokenOwner if owner is not contract // and if previous price is not 0 if (oldOwner != address(this)) { // old owner gets entire initial payment back oldOwner.transfer(ownerPayout); } else { fee_for_dev = SafeMath.add(fee_for_dev, ownerPayout); } // Taxes for Periodic Table owner if (elementIndexToOwner[0] != address(this)) { elementIndexToOwner[0].transfer(feeOnce); } else { fee_for_dev = SafeMath.add(fee_for_dev, feeOnce); } // Taxes for Scientist Owner for given Element uint256 scientistId = elements[_tokenId].scientistId; if ( scientistId != scientistSTART ) { if (elementIndexToOwner[scientistId] != address(this)) { elementIndexToOwner[scientistId].transfer(feeOnce); } else { fee_for_dev = SafeMath.add(fee_for_dev, feeOnce); } } else { fee_for_dev = SafeMath.add(fee_for_dev, feeOnce); } if (purchaseExcess > 0) { msg.sender.transfer(purchaseExcess); } ceoAddress.transfer(fee_for_dev); _transfer(oldOwner, newOwner, _tokenId); //TokenSold(_tokenId, sellingPrice, elementIndexToPrice[_tokenId], oldOwner, newOwner, elements[_tokenId].name); // Update prices if (sellingPrice < firstStepLimit) { // first stage elementIndexToPrice[_tokenId] = SafeMath.div(SafeMath.mul(sellingPrice, 200), 100); } else if (sellingPrice < secondStepLimit) { // second stage elementIndexToPrice[_tokenId] = SafeMath.div(SafeMath.mul(sellingPrice, 150), 100); } else if (sellingPrice < thirdStepLimit) { // third stage elementIndexToPrice[_tokenId] = SafeMath.div(SafeMath.mul(sellingPrice, 130), 100); } else { // fourth stage elementIndexToPrice[_tokenId] = SafeMath.div(SafeMath.mul(sellingPrice, 115), 100); } } function priceOf(uint256 _tokenId) public view returns (uint256 price) { return elementIndexToPrice[_tokenId]; } // @dev Assigns a new address to act as the CEO. Only available to the current CEO. // @param _newCEO The address of the new CEO function setCEO(address _newCEO) public onlyCEO { require(_newCEO != address(0)); ceoAddress = _newCEO; } // @dev Assigns a new address to act as the COO. Only available to the current COO. // @param _newCOO The address of the new COO function setCOO(address _newCOO) public onlyCEO { require(_newCOO != address(0)); cooAddress = _newCOO; } // @notice Allow pre-approved user to take ownership of a token // @param _tokenId The ID of the Token that can be transferred if this call succeeds. // @dev Required for ERC-721 compliance. function takeOwnership(uint256 _tokenId) public { address newOwner = msg.sender; address oldOwner = elementIndexToOwner[_tokenId]; // Safety check to prevent against an unexpected 0x0 default. require(_addressNotNull(newOwner)); // Making sure transfer is approved require(_approved(newOwner, _tokenId)); _transfer(oldOwner, newOwner, _tokenId); } // @param _owner The owner whose element tokens we are interested in. // @dev This method MUST NEVER be called by smart contract code. First, it's fairly // expensive (it walks the entire Elements array looking for elements belonging to owner), // but it also returns a dynamic array, which is only supported for web3 calls, and // not contract-to-contract calls. function tokensOfOwner(address _owner) public view returns(uint256[] ownerTokens) { uint256 tokenCount = balanceOf(_owner); if (tokenCount == 0) { // Return an empty array return new uint256[](0); } else { uint256[] memory result = new uint256[](tokenCount); uint256 totalElements = totalSupply(); uint256 resultIndex = 0; uint256 elementId; for (elementId = 0; elementId < totalElements; elementId++) { uint256 tokenId = tokens[elementId]; if (elementIndexToOwner[tokenId] == _owner) { result[resultIndex] = tokenId; resultIndex++; } } return result; } } // For querying totalSupply of token // @dev Required for ERC-721 compliance. function totalSupply() public view returns (uint256 total) { return tokens.length; } // Owner initates the transfer of the token to another account // @param _to The address for the token to be transferred to. // @param _tokenId The ID of the Token that can be transferred if this call succeeds. // @dev Required for ERC-721 compliance. function transfer( address _to, uint256 _tokenId ) public { require(_owns(msg.sender, _tokenId)); require(_addressNotNull(_to)); _transfer(msg.sender, _to, _tokenId); } // Third-party initiates transfer of token from address _from to address _to // @param _from The address for the token to be transferred from. // @param _to The address for the token to be transferred to. // @param _tokenId The ID of the Token that can be transferred if this call succeeds. // @dev Required for ERC-721 compliance. function transferFrom( address _from, address _to, uint256 _tokenId) public { require(_owns(_from, _tokenId)); require(_approved(_to, _tokenId)); require(_addressNotNull(_to)); _transfer(_from, _to, _tokenId); } /*** PRIVATE FUNCTIONS ***/ // Safety check on _to address to prevent against an unexpected 0x0 default. function _addressNotNull(address _to) private pure returns (bool) { return _to != address(0); } // For checking approval of transfer for address _to function _approved(address _to, uint256 _tokenId) private view returns (bool) { return elementIndexToApproved[_tokenId] == _to; } // Private method for creating Element function _createElement(uint256 _id, string _name, address _owner, uint256 _price, uint256 _scientistId) private returns (string) { uint256 newElementId = _id; // It's probably never going to happen, 4 billion tokens are A LOT, but // let's just be 100% sure we never let this happen. require(newElementId == uint256(uint32(newElementId))); elements[_id] = Element(_id, _name, _scientistId); Birth(newElementId, _name, _owner); elementIndexToPrice[newElementId] = _price; // This will assign ownership, and also emit the Transfer event as // per ERC721 draft _transfer(address(0), _owner, newElementId); tokens.push(_id); return _name; } // @dev Creates Periodic Table as first element function createContractPeriodicTable(string _name) public onlyCEO { require(periodicTableExists == false); _createElement(0, _name, address(this), periodicStartingPrice, scientistSTART); periodicTableExists = true; } // @dev Creates a new Element with the given name and Id function createContractElement(string _name, uint256 _scientistId) public onlyCEO { require(periodicTableExists == true); uint256 _id = SafeMath.add(elementCTR, elementSTART); uint256 _scientistIdProcessed = SafeMath.add(_scientistId, scientistSTART); _createElement(_id, _name, address(this), elementStartingPrice, _scientistIdProcessed); elementCTR = SafeMath.add(elementCTR, 1); } // @dev Creates a new Scientist with the given name Id function createContractScientist(string _name) public onlyCEO { require(periodicTableExists == true); // to start from 1001 scientistCTR = SafeMath.add(scientistCTR, 1); uint256 _id = SafeMath.add(scientistCTR, scientistSTART); _createElement(_id, _name, address(this), scientistStartingPrice, scientistSTART); } // @dev Creates a new Special Card with the given name Id function createContractSpecial(string _name) public onlyCEO { require(periodicTableExists == true); require(specialCTR <= specialLIMIT); // to start from 10001 specialCTR = SafeMath.add(specialCTR, 1); uint256 _id = SafeMath.add(specialCTR, specialSTART); _createElement(_id, _name, address(this), specialStartingPrice, scientistSTART); } // Check for token ownership function _owns(address claimant, uint256 _tokenId) private view returns (bool) { return claimant == elementIndexToOwner[_tokenId]; } //**** HELPERS for checking elements, scientists and special cards function checkPeriodic() public view returns (bool) { return periodicTableExists; } function getTotalElements() public view returns (uint256) { return elementCTR; } function getTotalScientists() public view returns (uint256) { return scientistCTR; } function getTotalSpecials() public view returns (uint256) { return specialCTR; } //**** HELPERS for changing prices limits and steps if it would be bad, community would like different function changeStartingPricesLimits(uint256 _elementStartPrice, uint256 _scientistStartPrice, uint256 _specialStartPrice) public onlyCEO { elementStartingPrice = _elementStartPrice; scientistStartingPrice = _scientistStartPrice; specialStartingPrice = _specialStartPrice; } function changeStepPricesLimits(uint256 _first, uint256 _second, uint256 _third) public onlyCEO { firstStepLimit = _first; secondStepLimit = _second; thirdStepLimit = _third; } // in case of error when assigning scientist to given element function changeScientistForElement(uint256 _tokenId, uint256 _scientistId) public onlyCEO { Element storage element = elements[_tokenId]; element.scientistId = SafeMath.add(_scientistId, scientistSTART); } function changeElementName(uint256 _tokenId, string _name) public onlyCEO { Element storage element = elements[_tokenId]; element.name = _name; } // This function can be used by the owner of a token to modify the current price function modifyTokenPrice(uint256 _tokenId, uint256 _newPrice) public payable { require(_newPrice > elementStartingPrice); require(elementIndexToOwner[_tokenId] == msg.sender); require(_newPrice < elementIndexToPrice[_tokenId]); if ( _tokenId == 0) { require(_newPrice > periodicStartingPrice); } else if ( _tokenId < 1000) { require(_newPrice > elementStartingPrice); } else if ( _tokenId < 10000 ) { require(_newPrice > scientistStartingPrice); } else { require(_newPrice > specialStartingPrice); } elementIndexToPrice[_tokenId] = _newPrice; } // For paying out balance on contract function _payout(address _to) private { if (_to == address(0)) { ceoAddress.transfer(this.balance); } else { _to.transfer(this.balance); } } // @dev Assigns ownership of a specific Element to an address. function _transfer(address _from, address _to, uint256 _tokenId) private { // Since the number of elements is capped to 2^32 we can't overflow this ownershipTokenCount[_to]++; //transfer ownership elementIndexToOwner[_tokenId] = _to; // When creating new elements _from is 0x0, but we can't account that address. if (_from != address(0)) { ownershipTokenCount[_from]--; // clear any previously approved ownership exchange delete elementIndexToApproved[_tokenId]; } // Emit the transfer event. Transfer(_from, _to, _tokenId); } } 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; } }
HELPERS for changing prices limits and steps if it would be bad, community would like different
function changeStartingPricesLimits(uint256 _elementStartPrice, uint256 _scientistStartPrice, uint256 _specialStartPrice) public onlyCEO { elementStartingPrice = _elementStartPrice; scientistStartingPrice = _scientistStartPrice; specialStartingPrice = _specialStartPrice; }
5,503,544
// SPDX-License-Identifier: UNLICENSED pragma solidity 0.8.10; import "forge-std/Test.sol"; contract ComplicatedContractTest is Test { function testDepositERC20() public pure { // waste some gas for display purposes for (uint256 i = 1000; i > 0; i--) {} } function testDepositETH() public pure { // waste some gas for display purposes for (uint256 i = 600; i > 0; i--) {} } }
waste some gas for display purposes
function testDepositERC20() public pure { }
6,355,768
pragma solidity 0.5.17; /* ____ __ __ __ _ / __/__ __ ___ / /_ / / ___ / /_ (_)__ __ _\ \ / // // _ \/ __// _ \/ -_)/ __// / \ \ / /___/ \_, //_//_/\__//_//_/\__/ \__//_/ /_\_\ /___/ * Synthetix: StakingRewards.sol * * Docs: https://docs.synthetix.io/ * * * MIT License * =========== * * Copyright (c) 2020 Synthetix * * 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 */ library Address { /** * @dev Returns true if `account` is a contract. * * This test is non-exhaustive, and there may be false-negatives: during the * execution of a contract's constructor, its address will be reported as * not containing a contract. * * > It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. */ function isContract(address account) internal view returns (bool) { // This method relies in extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } } 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); } interface IStakingRewards { // Views function lastTimeRewardApplicable() external view returns (uint256); function rewardPerToken() external view returns (uint256); function earned(address account) external view returns (uint256); function getRewardForDuration() external view returns (uint256); function totalSupply() external view returns (uint256); function balanceOf(address account) external view returns (uint256); // Mutative function stake(uint256 amount) external; function withdraw(uint256 amount) external; function getReward() external; function exit() external; } 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); } } contract Owned { address public owner; address public nominatedOwner; constructor(address _owner) public { require(_owner != address(0), "Owner address cannot be 0"); owner = _owner; emit OwnerChanged(address(0), _owner); } function nominateNewOwner(address _owner) external onlyOwner { nominatedOwner = _owner; emit OwnerNominated(_owner); } function acceptOwnership() external { require(msg.sender == nominatedOwner, "You must be nominated before you can accept ownership"); emit OwnerChanged(owner, nominatedOwner); owner = nominatedOwner; nominatedOwner = address(0); } modifier onlyOwner { _onlyOwner(); _; } function _onlyOwner() private view { require(msg.sender == owner, "Only the contract owner may perform this action"); } event OwnerNominated(address newOwner); event OwnerChanged(address oldOwner, address newOwner); } contract Pausable is Owned { uint public lastPauseTime; bool public paused; constructor() internal { // This contract is abstract, and thus cannot be instantiated directly require(owner != address(0), "Owner must be set"); // Paused will be false, and lastPauseTime will be 0 upon initialisation } /** * @notice Change the paused state of the contract * @dev Only the contract owner may call this. */ function setPaused(bool _paused) external onlyOwner { // Ensure we're actually changing the state before we do anything if (_paused == paused) { return; } // Set our paused state. paused = _paused; // If applicable, set the last pause time. if (paused) { lastPauseTime = now; } // Let everyone know that our pause state has changed. emit PauseChanged(paused); } event PauseChanged(bool isPaused); modifier notPaused { require(!paused, "This action cannot be performed while the contract is paused"); _; } } contract ReentrancyGuard { /// @dev 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"); } } contract RewardsDistributionRecipient is Owned { address public rewardsDistribution; function notifyRewardAmount(uint256 reward) external; modifier onlyRewardsDistribution() { require(msg.sender == rewardsDistribution, "Caller is not RewardsDistribution contract"); _; } function setRewardsDistribution(address _rewardsDistribution) external onlyOwner { rewardsDistribution = _rewardsDistribution; } } library SafeERC20 { using SafeMath for uint256; using Address for address; function safeTransfer(IERC20 token, address to, uint256 value) internal { callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal { callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } function safeApprove(IERC20 token, address spender, uint256 value) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' // solhint-disable-next-line max-line-length require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).add(value); callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).sub(value); callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. // A Solidity high level call has three parts: // 1. The target address is checked to verify it contains contract code // 2. The call itself is made, and success asserted // 3. The return value is decoded, which in turn checks the size of the returned data. // solhint-disable-next-line max-line-length require(address(token).isContract(), "SafeERC20: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = address(token).call(data); require(success, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } library 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; } } contract StakingRewards is IStakingRewards, RewardsDistributionRecipient, ReentrancyGuard, Pausable { using SafeMath for uint256; using SafeERC20 for IERC20; /* ========== STATE VARIABLES ========== */ IERC20 public rewardsToken; IERC20 public stakingToken; uint256 public periodFinish = 0; uint256 public rewardRate = 0; uint256 public rewardsDuration; uint256 public lastUpdateTime; uint256 public rewardPerTokenStored; mapping(address => uint256) public userRewardPerTokenPaid; mapping(address => uint256) public rewards; uint256 private _totalSupply; mapping(address => uint256) private _balances; /* ========== CONSTRUCTOR ========== */ constructor( address _owner, address _rewardsDistribution, address _rewardsToken, address _stakingToken, uint256 _rewardsDuration ) public Owned(_owner) { rewardsToken = IERC20(_rewardsToken); stakingToken = IERC20(_stakingToken); rewardsDistribution = _rewardsDistribution; rewardsDuration = _rewardsDuration; } /* ========== VIEWS ========== */ function totalSupply() external view returns (uint256) { return _totalSupply; } function balanceOf(address account) external view returns (uint256) { return _balances[account]; } function lastTimeRewardApplicable() public view returns (uint256) { return Math.min(block.timestamp, periodFinish); } function rewardPerToken() public view returns (uint256) { if (_totalSupply == 0) { return rewardPerTokenStored; } return rewardPerTokenStored.add( lastTimeRewardApplicable().sub(lastUpdateTime).mul(rewardRate).mul(1e18).div(_totalSupply) ); } function earned(address account) public view returns (uint256) { return _balances[account].mul(rewardPerToken().sub(userRewardPerTokenPaid[account])).div(1e18).add(rewards[account]); } function getRewardForDuration() external view returns (uint256) { return rewardRate.mul(rewardsDuration); } /* ========== MUTATIVE FUNCTIONS ========== */ function stake(uint256 amount) external nonReentrant notPaused updateReward(msg.sender) { require(amount > 0, "Cannot stake 0"); _totalSupply = _totalSupply.add(amount); _balances[msg.sender] = _balances[msg.sender].add(amount); stakingToken.safeTransferFrom(msg.sender, address(this), amount); emit Staked(msg.sender, amount); } function withdraw(uint256 amount) public nonReentrant updateReward(msg.sender) { require(amount > 0, "Cannot withdraw 0"); _totalSupply = _totalSupply.sub(amount); _balances[msg.sender] = _balances[msg.sender].sub(amount); stakingToken.safeTransfer(msg.sender, amount); emit Withdrawn(msg.sender, amount); } function getReward() public nonReentrant updateReward(msg.sender) { uint256 reward = rewards[msg.sender]; if (reward > 0) { rewards[msg.sender] = 0; rewardsToken.safeTransfer(msg.sender, reward); emit RewardPaid(msg.sender, reward); } } function exit() external { withdraw(_balances[msg.sender]); getReward(); } /* ========== RESTRICTED FUNCTIONS ========== */ function notifyRewardAmount(uint256 reward) external onlyRewardsDistribution updateReward(address(0)) { // handle the transfer of reward tokens via `transferFrom` to reduce the number // of transactions required and ensure correctness of the reward amount rewardsToken.safeTransferFrom(msg.sender, address(this), reward); if (block.timestamp >= periodFinish) { rewardRate = reward.div(rewardsDuration); } else { uint256 remaining = periodFinish.sub(block.timestamp); uint256 leftover = remaining.mul(rewardRate); rewardRate = reward.add(leftover).div(rewardsDuration); } lastUpdateTime = block.timestamp; periodFinish = block.timestamp.add(rewardsDuration); emit RewardAdded(reward); } // Added to support recovering LP Rewards from other systems such as BAL to be distributed to holders function recoverERC20(address tokenAddress, uint256 tokenAmount) external onlyOwner { require(tokenAddress != address(stakingToken), "Cannot withdraw the staking token"); IERC20(tokenAddress).safeTransfer(owner, tokenAmount); emit Recovered(tokenAddress, tokenAmount); } function setRewardsDuration(uint256 _rewardsDuration) external onlyOwner { require( block.timestamp > periodFinish, "Previous rewards period must be complete before changing the duration for the new period" ); rewardsDuration = _rewardsDuration; emit RewardsDurationUpdated(rewardsDuration); } /* ========== MODIFIERS ========== */ modifier updateReward(address account) { rewardPerTokenStored = rewardPerToken(); lastUpdateTime = lastTimeRewardApplicable(); if (account != address(0)) { rewards[account] = earned(account); userRewardPerTokenPaid[account] = rewardPerTokenStored; } _; } /* ========== EVENTS ========== */ event RewardAdded(uint256 reward); event Staked(address indexed user, uint256 amount); event Withdrawn(address indexed user, uint256 amount); event RewardPaid(address indexed user, uint256 reward); event RewardsDurationUpdated(uint256 newDuration); event Recovered(address token, uint256 amount); } /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be aplied to your functions to restrict their use to * the owner. */ contract Ownable { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor () internal { _owner = msg.sender; emit OwnershipTransferred(address(0), _owner); } /** * @dev Returns the address of the current owner. */ function owner() public view returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(isOwner(), "Ownable: caller is not the owner"); _; } /** * @dev Returns true if the caller is the current owner. */ function isOwner() public view returns (bool) { return msg.sender == _owner; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * > Note: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public onlyOwner { _transferOwnership(newOwner); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). */ function _transferOwnership(address newOwner) internal { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } contract StakingRewardsFactory is Ownable { // the staking tokens for which the rewards contract has been deployed address[] public stakingTokens; // info about rewards for a particular staking token struct StakingRewardsInfo { address stakingRewards; address rewardsToken; } // rewards info by staking token mapping(address => StakingRewardsInfo) public stakingRewardsInfoByStakingToken; constructor() Ownable() public {} // deploy a staking reward contract for the staking token, and store the reward amount // the reward will be distributed to the staking reward contract no sooner than the genesis function deploy(address stakingToken, address rewardsToken, uint256 rewardsDuration) public onlyOwner { require(rewardsToken != address(0), 'StakingRewardsFactory::deploy: RewardToken address cannot be ZERO'); StakingRewardsInfo storage info = stakingRewardsInfoByStakingToken[stakingToken]; require(info.stakingRewards == address(0), 'StakingRewardsFactory::deploy: already deployed'); // Args on the StakingRewards // address _owner, // address _rewardsDistribution, // address _rewardsToken, // address _stakingToken, // uint256 _rewardsDuration info.rewardsToken = rewardsToken; info.stakingRewards = address(new StakingRewards(owner(), address(this), rewardsToken, stakingToken, rewardsDuration)); stakingTokens.push(stakingToken); } // notify reward amount for an individual staking token. // this is a fallback in case the notifyRewardAmounts costs too much gas to call for all contracts function notifyRewardAmount(address stakingToken, uint256 rewardAmount) public { require(rewardAmount > 0, 'StakingRewardsFactory::notifyRewardAmount: amount can not be ZERO'); StakingRewardsInfo storage info = stakingRewardsInfoByStakingToken[stakingToken]; require(info.stakingRewards != address(0), 'StakingRewardsFactory::notifyRewardAmount: not deployed'); IERC20(info.rewardsToken).approve(info.stakingRewards, rewardAmount); StakingRewards(info.stakingRewards).notifyRewardAmount(rewardAmount); } }
notify reward amount for an individual staking token. this is a fallback in case the notifyRewardAmounts costs too much gas to call for all contracts
function notifyRewardAmount(address stakingToken, uint256 rewardAmount) public { require(rewardAmount > 0, 'StakingRewardsFactory::notifyRewardAmount: amount can not be ZERO'); StakingRewardsInfo storage info = stakingRewardsInfoByStakingToken[stakingToken]; require(info.stakingRewards != address(0), 'StakingRewardsFactory::notifyRewardAmount: not deployed'); IERC20(info.rewardsToken).approve(info.stakingRewards, rewardAmount); StakingRewards(info.stakingRewards).notifyRewardAmount(rewardAmount); }
1,154,886
// SPDX-License-Identifier: GPL-2.0-or-later pragma solidity ^0.8.0; import "../BaseLogic.sol"; import "../vendor/ISwapRouter.sol"; /// @notice Trading assets on Uniswap V3 and 1Inch V4 DEXs contract Swap is BaseLogic { address immutable public uniswapRouter; address immutable public oneInch; /// @notice Params for Uniswap V3 exact input trade on a single pool /// @param subAccountIdIn subaccount id to trade from /// @param subAccountIdOut subaccount id to trade to /// @param underlyingIn sold token address /// @param underlyingOut bought token address /// @param amountIn amount of token to sell /// @param amountOutMinimum minimum amount of bought token /// @param deadline trade must complete before this timestamp /// @param fee uniswap pool fee to use /// @param sqrtPriceLimitX96 maximum acceptable price struct SwapUniExactInputSingleParams { uint subAccountIdIn; uint subAccountIdOut; address underlyingIn; address underlyingOut; uint amountIn; uint amountOutMinimum; uint deadline; uint24 fee; uint160 sqrtPriceLimitX96; } /// @notice Params for Uniswap V3 exact input trade routed through multiple pools /// @param subAccountIdIn subaccount id to trade from /// @param subAccountIdOut subaccount id to trade to /// @param underlyingIn sold token address /// @param underlyingOut bought token address /// @param amountIn amount of token to sell /// @param amountOutMinimum minimum amount of bought token /// @param deadline trade must complete before this timestamp /// @param path list of pools to use for the trade struct SwapUniExactInputParams { uint subAccountIdIn; uint subAccountIdOut; uint amountIn; uint amountOutMinimum; uint deadline; bytes path; // list of pools to hop - constructed with uni SDK } /// @notice Params for Uniswap V3 exact output trade on a single pool /// @param subAccountIdIn subaccount id to trade from /// @param subAccountIdOut subaccount id to trade to /// @param underlyingIn sold token address /// @param underlyingOut bought token address /// @param amountOut amount of token to buy /// @param amountInMaximum maximum amount of sold token /// @param deadline trade must complete before this timestamp /// @param fee uniswap pool fee to use /// @param sqrtPriceLimitX96 maximum acceptable price struct SwapUniExactOutputSingleParams { uint subAccountIdIn; uint subAccountIdOut; address underlyingIn; address underlyingOut; uint amountOut; uint amountInMaximum; uint deadline; uint24 fee; uint160 sqrtPriceLimitX96; } /// @notice Params for Uniswap V3 exact output trade routed through multiple pools /// @param subAccountIdIn subaccount id to trade from /// @param subAccountIdOut subaccount id to trade to /// @param underlyingIn sold token address /// @param underlyingOut bought token address /// @param amountOut amount of token to buy /// @param amountInMaximum maximum amount of sold token /// @param deadline trade must complete before this timestamp /// @param path list of pools to use for the trade struct SwapUniExactOutputParams { uint subAccountIdIn; uint subAccountIdOut; uint amountOut; uint amountInMaximum; uint deadline; bytes path; } /// @notice Params for 1Inch trade /// @param subAccountIdIn subaccount id to trade from /// @param subAccountIdOut subaccount id to trade to /// @param underlyingIn sold token address /// @param underlyingOut bought token address /// @param amount amount of token to sell /// @param amountOutMinimum minimum amount of bought token /// @param payload call data passed to 1Inch contract struct Swap1InchParams { uint subAccountIdIn; uint subAccountIdOut; address underlyingIn; address underlyingOut; uint amount; uint amountOutMinimum; bytes payload; } struct SwapCache { address accountIn; address accountOut; address eTokenIn; address eTokenOut; AssetCache assetCacheIn; AssetCache assetCacheOut; uint balanceIn; uint balanceOut; uint amountIn; uint amountOut; uint amountInternalIn; } constructor(bytes32 moduleGitCommit_, address uniswapRouter_, address oneInch_) BaseLogic(MODULEID__SWAP, moduleGitCommit_) { uniswapRouter = uniswapRouter_; oneInch = oneInch_; } /// @notice Execute Uniswap V3 exact input trade on a single pool /// @param params struct defining trade parameters function swapUniExactInputSingle(SwapUniExactInputSingleParams memory params) external nonReentrant { SwapCache memory swap = initSwap( params.underlyingIn, params.underlyingOut, params.amountIn, params.subAccountIdIn, params.subAccountIdOut, SWAP_TYPE__UNI_EXACT_INPUT_SINGLE ); setWithdrawAmounts(swap, params.amountIn); Utils.safeApprove(params.underlyingIn, uniswapRouter, swap.amountIn); swap.amountOut = ISwapRouter(uniswapRouter).exactInputSingle( ISwapRouter.ExactInputSingleParams({ tokenIn: params.underlyingIn, tokenOut: params.underlyingOut, fee: params.fee, recipient: address(this), deadline: params.deadline > 0 ? params.deadline : block.timestamp, amountIn: swap.amountIn, amountOutMinimum: params.amountOutMinimum, sqrtPriceLimitX96: params.sqrtPriceLimitX96 }) ); finalizeSwap(swap); } /// @notice Execute Uniswap V3 exact input trade routed through multiple pools /// @param params struct defining trade parameters function swapUniExactInput(SwapUniExactInputParams memory params) external nonReentrant { (address underlyingIn, address underlyingOut) = decodeUniPath(params.path, false); SwapCache memory swap = initSwap( underlyingIn, underlyingOut, params.amountIn, params.subAccountIdIn, params.subAccountIdOut, SWAP_TYPE__UNI_EXACT_INPUT ); setWithdrawAmounts(swap, params.amountIn); Utils.safeApprove(underlyingIn, uniswapRouter, swap.amountIn); swap.amountOut = ISwapRouter(uniswapRouter).exactInput( ISwapRouter.ExactInputParams({ path: params.path, recipient: address(this), deadline: params.deadline > 0 ? params.deadline : block.timestamp, amountIn: swap.amountIn, amountOutMinimum: params.amountOutMinimum }) ); finalizeSwap(swap); } /// @notice Execute Uniswap V3 exact output trade on a single pool /// @param params struct defining trade parameters function swapUniExactOutputSingle(SwapUniExactOutputSingleParams memory params) external nonReentrant { SwapCache memory swap = initSwap( params.underlyingIn, params.underlyingOut, params.amountOut, params.subAccountIdIn, params.subAccountIdOut, SWAP_TYPE__UNI_EXACT_OUTPUT_SINGLE ); swap.amountOut = params.amountOut; doSwapUniExactOutputSingle(swap, params); finalizeSwap(swap); } /// @notice Execute Uniswap V3 exact output trade routed through multiple pools /// @param params struct defining trade parameters function swapUniExactOutput(SwapUniExactOutputParams memory params) external nonReentrant { (address underlyingIn, address underlyingOut) = decodeUniPath(params.path, true); SwapCache memory swap = initSwap( underlyingIn, underlyingOut, params.amountOut, params.subAccountIdIn, params.subAccountIdOut, SWAP_TYPE__UNI_EXACT_OUTPUT ); swap.amountOut = params.amountOut; doSwapUniExactOutput(swap, params, underlyingIn); finalizeSwap(swap); } /// @notice Trade on Uniswap V3 single pool and repay debt with bought asset /// @param params struct defining trade parameters (amountOut is ignored) /// @param targetDebt amount of debt that is expected to remain after trade and repay (0 to repay full debt) function swapAndRepayUniSingle(SwapUniExactOutputSingleParams memory params, uint targetDebt) external nonReentrant { SwapCache memory swap = initSwap( params.underlyingIn, params.underlyingOut, targetDebt, params.subAccountIdIn, params.subAccountIdOut, SWAP_TYPE__UNI_EXACT_OUTPUT_SINGLE_REPAY ); swap.amountOut = getRepayAmount(swap, targetDebt); doSwapUniExactOutputSingle(swap, params); finalizeSwapAndRepay(swap); } /// @notice Trade on Uniswap V3 through multiple pools pool and repay debt with bought asset /// @param params struct defining trade parameters (amountOut is ignored) /// @param targetDebt amount of debt that is expected to remain after trade and repay (0 to repay full debt) function swapAndRepayUni(SwapUniExactOutputParams memory params, uint targetDebt) external nonReentrant { (address underlyingIn, address underlyingOut) = decodeUniPath(params.path, true); SwapCache memory swap = initSwap( underlyingIn, underlyingOut, targetDebt, params.subAccountIdIn, params.subAccountIdOut, SWAP_TYPE__UNI_EXACT_OUTPUT_REPAY ); swap.amountOut = getRepayAmount(swap, targetDebt); doSwapUniExactOutput(swap, params, underlyingIn); finalizeSwapAndRepay(swap); } /// @notice Execute 1Inch V4 trade /// @param params struct defining trade parameters function swap1Inch(Swap1InchParams memory params) external nonReentrant { SwapCache memory swap = initSwap( params.underlyingIn, params.underlyingOut, params.amount, params.subAccountIdIn, params.subAccountIdOut, SWAP_TYPE__1INCH ); setWithdrawAmounts(swap, params.amount); Utils.safeApprove(params.underlyingIn, oneInch, swap.amountIn); (bool success, bytes memory result) = oneInch.call(params.payload); if (!success) revertBytes(result); swap.amountOut = abi.decode(result, (uint)); require(swap.amountOut >= params.amountOutMinimum, "e/swap/min-amount-out"); finalizeSwap(swap); } function initSwap( address underlyingIn, address underlyingOut, uint amount, uint subAccountIdIn, uint subAccountIdOut, uint swapType ) private returns (SwapCache memory swap) { require(underlyingIn != underlyingOut, "e/swap/same"); address msgSender = unpackTrailingParamMsgSender(); swap.accountIn = getSubAccount(msgSender, subAccountIdIn); swap.accountOut = getSubAccount(msgSender, subAccountIdOut); updateAverageLiquidity(swap.accountIn); if (swap.accountIn != swap.accountOut) updateAverageLiquidity(swap.accountOut); emit RequestSwap( swap.accountIn, swap.accountOut, underlyingIn, underlyingOut, amount, swapType ); swap.eTokenIn = underlyingLookup[underlyingIn].eTokenAddress; swap.eTokenOut = underlyingLookup[underlyingOut].eTokenAddress; AssetStorage storage assetStorageIn = eTokenLookup[swap.eTokenIn]; AssetStorage storage assetStorageOut = eTokenLookup[swap.eTokenOut]; require(swap.eTokenIn != address(0), "e/swap/in-market-not-activated"); require(swap.eTokenOut != address(0), "e/swap/out-market-not-activated"); swap.assetCacheIn = loadAssetCache(underlyingIn, assetStorageIn); swap.assetCacheOut = loadAssetCache(underlyingOut, assetStorageOut); swap.balanceIn = callBalanceOf(swap.assetCacheIn, address(this)) ; swap.balanceOut = callBalanceOf(swap.assetCacheOut, address(this)); } function doSwapUniExactOutputSingle(SwapCache memory swap, SwapUniExactOutputSingleParams memory params) private { Utils.safeApprove(params.underlyingIn, uniswapRouter, params.amountInMaximum); uint pulledAmountIn = ISwapRouter(uniswapRouter).exactOutputSingle( ISwapRouter.ExactOutputSingleParams({ tokenIn: params.underlyingIn, tokenOut: params.underlyingOut, fee: params.fee, recipient: address(this), deadline: params.deadline > 0 ? params.deadline : block.timestamp, amountOut: swap.amountOut, amountInMaximum: params.amountInMaximum, sqrtPriceLimitX96: params.sqrtPriceLimitX96 }) ); require(pulledAmountIn != type(uint).max, "e/swap/exact-out-amount-in"); setWithdrawAmounts(swap, pulledAmountIn); if (swap.amountIn < params.amountInMaximum) { Utils.safeApprove(params.underlyingIn, uniswapRouter, 0); } } function doSwapUniExactOutput(SwapCache memory swap, SwapUniExactOutputParams memory params, address underlyingIn) private { Utils.safeApprove(underlyingIn, uniswapRouter, params.amountInMaximum); uint pulledAmountIn = ISwapRouter(uniswapRouter).exactOutput( ISwapRouter.ExactOutputParams({ path: params.path, recipient: address(this), deadline: params.deadline > 0 ? params.deadline : block.timestamp, amountOut: swap.amountOut, amountInMaximum: params.amountInMaximum }) ); require(pulledAmountIn != type(uint).max, "e/swap/exact-out-amount-in"); setWithdrawAmounts(swap, pulledAmountIn); if (swap.amountIn < params.amountInMaximum) { Utils.safeApprove(underlyingIn, uniswapRouter, 0); } } function setWithdrawAmounts(SwapCache memory swap, uint amount) private view { (amount, swap.amountInternalIn) = withdrawAmounts(eTokenLookup[swap.eTokenIn], swap.assetCacheIn, swap.accountIn, amount); require(swap.assetCacheIn.poolSize >= amount, "e/swap/insufficient-pool-size"); swap.amountIn = amount / swap.assetCacheIn.underlyingDecimalsScaler; } function finalizeSwap(SwapCache memory swap) private { uint balanceIn = checkBalances(swap); processWithdraw(eTokenLookup[swap.eTokenIn], swap.assetCacheIn, swap.eTokenIn, swap.accountIn, swap.amountInternalIn, balanceIn); processDeposit(eTokenLookup[swap.eTokenOut], swap.assetCacheOut, swap.eTokenOut, swap.accountOut, swap.amountOut); // only checking outgoing account, deposit can't lower health score checkLiquidity(swap.accountIn); } function finalizeSwapAndRepay(SwapCache memory swap) private { uint balanceIn = checkBalances(swap); processWithdraw(eTokenLookup[swap.eTokenIn], swap.assetCacheIn, swap.eTokenIn, swap.accountIn, swap.amountInternalIn, balanceIn); processRepay(eTokenLookup[swap.eTokenOut], swap.assetCacheOut, swap.accountOut, swap.amountOut); // only checking outgoing account, repay can't lower health score checkLiquidity(swap.accountIn); } function processWithdraw(AssetStorage storage assetStorage, AssetCache memory assetCache, address eTokenAddress, address account, uint amountInternal, uint balanceIn) private { assetCache.poolSize = decodeExternalAmount(assetCache, balanceIn); decreaseBalance(assetStorage, assetCache, eTokenAddress, account, amountInternal); logAssetStatus(assetCache); } function processDeposit(AssetStorage storage assetStorage, AssetCache memory assetCache, address eTokenAddress, address account, uint amount) private { uint amountDecoded = decodeExternalAmount(assetCache, amount); uint amountInternal = underlyingAmountToBalance(assetCache, amountDecoded); assetCache.poolSize += amountDecoded; increaseBalance(assetStorage, assetCache, eTokenAddress, account, amountInternal); logAssetStatus(assetCache); } function processRepay(AssetStorage storage assetStorage, AssetCache memory assetCache, address account, uint amount) private { decreaseBorrow(assetStorage, assetCache, assetStorage.dTokenAddress, account, decodeExternalAmount(assetCache, amount)); logAssetStatus(assetCache); } function checkBalances(SwapCache memory swap) private view returns (uint) { uint balanceIn = callBalanceOf(swap.assetCacheIn, address(this)); require(balanceIn == swap.balanceIn - swap.amountIn, "e/swap/balance-in"); require(callBalanceOf(swap.assetCacheOut, address(this)) == swap.balanceOut + swap.amountOut, "e/swap/balance-out"); return balanceIn; } function decodeUniPath(bytes memory path, bool isExactOutput) private pure returns (address, address) { require(path.length >= 20 + 3 + 20, "e/swap/uni-path-length"); require((path.length - 20) % 23 == 0, "e/swap/uni-path-format"); address token0 = toAddress(path, 0); address token1 = toAddress(path, path.length - 20); return isExactOutput ? (token1, token0) : (token0, token1); } function getRepayAmount(SwapCache memory swap, uint targetDebt) private view returns (uint) { uint owed = getCurrentOwed(eTokenLookup[swap.eTokenOut], swap.assetCacheOut, swap.accountOut) / swap.assetCacheOut.underlyingDecimalsScaler; require (owed > targetDebt, "e/swap/target-debt"); return owed - targetDebt; } function toAddress(bytes memory data, uint start) private pure returns (address result) { // assuming data length is already validated assembly { // borrowed from BytesLib https://github.com/GNSPS/solidity-bytes-utils/blob/master/contracts/BytesLib.sol result := div(mload(add(add(data, 0x20), start)), 0x1000000000000000000000000) } } } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity ^0.8.0; import "./BaseModule.sol"; import "./BaseIRM.sol"; import "./Interfaces.sol"; import "./Utils.sol"; import "./vendor/RPow.sol"; import "./IRiskManager.sol"; abstract contract BaseLogic is BaseModule { constructor(uint moduleId_, bytes32 moduleGitCommit_) BaseModule(moduleId_, moduleGitCommit_) {} // Account auth function getSubAccount(address primary, uint subAccountId) internal pure returns (address) { require(subAccountId < 256, "e/sub-account-id-too-big"); return address(uint160(primary) ^ uint160(subAccountId)); } function isSubAccountOf(address primary, address subAccount) internal pure returns (bool) { return (uint160(primary) | 0xFF) == (uint160(subAccount) | 0xFF); } // Entered markets array function getEnteredMarketsArray(address account) internal view returns (address[] memory) { uint32 numMarketsEntered = accountLookup[account].numMarketsEntered; address firstMarketEntered = accountLookup[account].firstMarketEntered; address[] memory output = new address[](numMarketsEntered); if (numMarketsEntered == 0) return output; address[MAX_POSSIBLE_ENTERED_MARKETS] storage markets = marketsEntered[account]; output[0] = firstMarketEntered; for (uint i = 1; i < numMarketsEntered; ++i) { output[i] = markets[i]; } return output; } function isEnteredInMarket(address account, address underlying) internal view returns (bool) { uint32 numMarketsEntered = accountLookup[account].numMarketsEntered; address firstMarketEntered = accountLookup[account].firstMarketEntered; if (numMarketsEntered == 0) return false; if (firstMarketEntered == underlying) return true; address[MAX_POSSIBLE_ENTERED_MARKETS] storage markets = marketsEntered[account]; for (uint i = 1; i < numMarketsEntered; ++i) { if (markets[i] == underlying) return true; } return false; } function doEnterMarket(address account, address underlying) internal { AccountStorage storage accountStorage = accountLookup[account]; uint32 numMarketsEntered = accountStorage.numMarketsEntered; address[MAX_POSSIBLE_ENTERED_MARKETS] storage markets = marketsEntered[account]; if (numMarketsEntered != 0) { if (accountStorage.firstMarketEntered == underlying) return; // already entered for (uint i = 1; i < numMarketsEntered; i++) { if (markets[i] == underlying) return; // already entered } } require(numMarketsEntered < MAX_ENTERED_MARKETS, "e/too-many-entered-markets"); if (numMarketsEntered == 0) accountStorage.firstMarketEntered = underlying; else markets[numMarketsEntered] = underlying; accountStorage.numMarketsEntered = numMarketsEntered + 1; emit EnterMarket(underlying, account); } // Liquidity check must be done by caller after calling this function doExitMarket(address account, address underlying) internal { AccountStorage storage accountStorage = accountLookup[account]; uint32 numMarketsEntered = accountStorage.numMarketsEntered; address[MAX_POSSIBLE_ENTERED_MARKETS] storage markets = marketsEntered[account]; uint searchIndex = type(uint).max; if (numMarketsEntered == 0) return; // already exited if (accountStorage.firstMarketEntered == underlying) { searchIndex = 0; } else { for (uint i = 1; i < numMarketsEntered; i++) { if (markets[i] == underlying) { searchIndex = i; break; } } if (searchIndex == type(uint).max) return; // already exited } uint lastMarketIndex = numMarketsEntered - 1; if (searchIndex != lastMarketIndex) { if (searchIndex == 0) accountStorage.firstMarketEntered = markets[lastMarketIndex]; else markets[searchIndex] = markets[lastMarketIndex]; } accountStorage.numMarketsEntered = uint32(lastMarketIndex); if (lastMarketIndex != 0) markets[lastMarketIndex] = address(0); // zero out for storage refund emit ExitMarket(underlying, account); } // AssetConfig function resolveAssetConfig(address underlying) internal view returns (AssetConfig memory) { AssetConfig memory config = underlyingLookup[underlying]; require(config.eTokenAddress != address(0), "e/market-not-activated"); if (config.borrowFactor == type(uint32).max) config.borrowFactor = DEFAULT_BORROW_FACTOR; if (config.twapWindow == type(uint24).max) config.twapWindow = DEFAULT_TWAP_WINDOW_SECONDS; return config; } // AssetCache struct AssetCache { address underlying; uint112 totalBalances; uint144 totalBorrows; uint96 reserveBalance; uint interestAccumulator; uint40 lastInterestAccumulatorUpdate; uint8 underlyingDecimals; uint32 interestRateModel; int96 interestRate; uint32 reserveFee; uint16 pricingType; uint32 pricingParameters; uint poolSize; // result of calling balanceOf on underlying (in external units) uint underlyingDecimalsScaler; uint maxExternalAmount; } function initAssetCache(address underlying, AssetStorage storage assetStorage, AssetCache memory assetCache) internal view returns (bool dirty) { dirty = false; assetCache.underlying = underlying; // Storage loads assetCache.lastInterestAccumulatorUpdate = assetStorage.lastInterestAccumulatorUpdate; uint8 underlyingDecimals = assetCache.underlyingDecimals = assetStorage.underlyingDecimals; assetCache.interestRateModel = assetStorage.interestRateModel; assetCache.interestRate = assetStorage.interestRate; assetCache.reserveFee = assetStorage.reserveFee; assetCache.pricingType = assetStorage.pricingType; assetCache.pricingParameters = assetStorage.pricingParameters; assetCache.reserveBalance = assetStorage.reserveBalance; assetCache.totalBalances = assetStorage.totalBalances; assetCache.totalBorrows = assetStorage.totalBorrows; assetCache.interestAccumulator = assetStorage.interestAccumulator; // Derived state unchecked { assetCache.underlyingDecimalsScaler = 10**(18 - underlyingDecimals); assetCache.maxExternalAmount = MAX_SANE_AMOUNT / assetCache.underlyingDecimalsScaler; } uint poolSize = callBalanceOf(assetCache, address(this)); if (poolSize <= assetCache.maxExternalAmount) { unchecked { assetCache.poolSize = poolSize * assetCache.underlyingDecimalsScaler; } } else { assetCache.poolSize = 0; } // Update interest accumulator and reserves if (block.timestamp != assetCache.lastInterestAccumulatorUpdate) { dirty = true; uint deltaT = block.timestamp - assetCache.lastInterestAccumulatorUpdate; // Compute new values uint newInterestAccumulator = (RPow.rpow(uint(int(assetCache.interestRate) + 1e27), deltaT, 1e27) * assetCache.interestAccumulator) / 1e27; uint newTotalBorrows = assetCache.totalBorrows * newInterestAccumulator / assetCache.interestAccumulator; uint newReserveBalance = assetCache.reserveBalance; uint newTotalBalances = assetCache.totalBalances; uint feeAmount = (newTotalBorrows - assetCache.totalBorrows) * (assetCache.reserveFee == type(uint32).max ? DEFAULT_RESERVE_FEE : assetCache.reserveFee) / (RESERVE_FEE_SCALE * INTERNAL_DEBT_PRECISION); if (feeAmount != 0) { uint poolAssets = assetCache.poolSize + (newTotalBorrows / INTERNAL_DEBT_PRECISION); newTotalBalances = poolAssets * newTotalBalances / (poolAssets - feeAmount); newReserveBalance += newTotalBalances - assetCache.totalBalances; } // Store new values in assetCache, only if no overflows will occur if (newTotalBalances <= MAX_SANE_AMOUNT && newTotalBorrows <= MAX_SANE_DEBT_AMOUNT) { assetCache.totalBorrows = encodeDebtAmount(newTotalBorrows); assetCache.interestAccumulator = newInterestAccumulator; assetCache.lastInterestAccumulatorUpdate = uint40(block.timestamp); if (newTotalBalances != assetCache.totalBalances) { assetCache.reserveBalance = encodeSmallAmount(newReserveBalance); assetCache.totalBalances = encodeAmount(newTotalBalances); } } } } function loadAssetCache(address underlying, AssetStorage storage assetStorage) internal returns (AssetCache memory assetCache) { if (initAssetCache(underlying, assetStorage, assetCache)) { assetStorage.lastInterestAccumulatorUpdate = assetCache.lastInterestAccumulatorUpdate; assetStorage.underlying = assetCache.underlying; // avoid an SLOAD of this slot assetStorage.reserveBalance = assetCache.reserveBalance; assetStorage.totalBalances = assetCache.totalBalances; assetStorage.totalBorrows = assetCache.totalBorrows; assetStorage.interestAccumulator = assetCache.interestAccumulator; } } function loadAssetCacheRO(address underlying, AssetStorage storage assetStorage) internal view returns (AssetCache memory assetCache) { initAssetCache(underlying, assetStorage, assetCache); } // Utils function decodeExternalAmount(AssetCache memory assetCache, uint externalAmount) internal pure returns (uint scaledAmount) { require(externalAmount <= assetCache.maxExternalAmount, "e/amount-too-large"); unchecked { scaledAmount = externalAmount * assetCache.underlyingDecimalsScaler; } } function encodeAmount(uint amount) internal pure returns (uint112) { require(amount <= MAX_SANE_AMOUNT, "e/amount-too-large-to-encode"); return uint112(amount); } function encodeSmallAmount(uint amount) internal pure returns (uint96) { require(amount <= MAX_SANE_SMALL_AMOUNT, "e/small-amount-too-large-to-encode"); return uint96(amount); } function encodeDebtAmount(uint amount) internal pure returns (uint144) { require(amount <= MAX_SANE_DEBT_AMOUNT, "e/debt-amount-too-large-to-encode"); return uint144(amount); } function computeExchangeRate(AssetCache memory assetCache) private pure returns (uint) { if (assetCache.totalBalances == 0) return 1e18; return (assetCache.poolSize + (assetCache.totalBorrows / INTERNAL_DEBT_PRECISION)) * 1e18 / assetCache.totalBalances; } function underlyingAmountToBalance(AssetCache memory assetCache, uint amount) internal pure returns (uint) { uint exchangeRate = computeExchangeRate(assetCache); return amount * 1e18 / exchangeRate; } function underlyingAmountToBalanceRoundUp(AssetCache memory assetCache, uint amount) internal pure returns (uint) { uint exchangeRate = computeExchangeRate(assetCache); return (amount * 1e18 + (exchangeRate - 1)) / exchangeRate; } function balanceToUnderlyingAmount(AssetCache memory assetCache, uint amount) internal pure returns (uint) { uint exchangeRate = computeExchangeRate(assetCache); return amount * exchangeRate / 1e18; } function callBalanceOf(AssetCache memory assetCache, address account) internal view FREEMEM returns (uint) { // We set a gas limit so that a malicious token can't eat up all gas and cause a liquidity check to fail. (bool success, bytes memory data) = assetCache.underlying.staticcall{gas: 20000}(abi.encodeWithSelector(IERC20.balanceOf.selector, account)); // If token's balanceOf() call fails for any reason, return 0. This prevents malicious tokens from causing liquidity checks to fail. // If the contract doesn't exist (maybe because selfdestructed), then data.length will be 0 and we will return 0. // Data length > 32 is allowed because some legitimate tokens append extra data that can be safely ignored. if (!success || data.length < 32) return 0; return abi.decode(data, (uint256)); } function updateInterestRate(AssetStorage storage assetStorage, AssetCache memory assetCache) internal { uint32 utilisation; { uint totalBorrows = assetCache.totalBorrows / INTERNAL_DEBT_PRECISION; uint poolAssets = assetCache.poolSize + totalBorrows; if (poolAssets == 0) utilisation = 0; // empty pool arbitrarily given utilisation of 0 else utilisation = uint32(totalBorrows * (uint(type(uint32).max) * 1e18) / poolAssets / 1e18); } bytes memory result = callInternalModule(assetCache.interestRateModel, abi.encodeWithSelector(BaseIRM.computeInterestRate.selector, assetCache.underlying, utilisation)); (int96 newInterestRate) = abi.decode(result, (int96)); assetStorage.interestRate = assetCache.interestRate = newInterestRate; } function logAssetStatus(AssetCache memory a) internal { emit AssetStatus(a.underlying, a.totalBalances, a.totalBorrows / INTERNAL_DEBT_PRECISION, a.reserveBalance, a.poolSize, a.interestAccumulator, a.interestRate, block.timestamp); } // Balances function increaseBalance(AssetStorage storage assetStorage, AssetCache memory assetCache, address eTokenAddress, address account, uint amount) internal { assetStorage.users[account].balance = encodeAmount(assetStorage.users[account].balance + amount); assetStorage.totalBalances = assetCache.totalBalances = encodeAmount(uint(assetCache.totalBalances) + amount); updateInterestRate(assetStorage, assetCache); emit Deposit(assetCache.underlying, account, amount); emitViaProxy_Transfer(eTokenAddress, address(0), account, amount); } function decreaseBalance(AssetStorage storage assetStorage, AssetCache memory assetCache, address eTokenAddress, address account, uint amount) internal { uint origBalance = assetStorage.users[account].balance; require(origBalance >= amount, "e/insufficient-balance"); assetStorage.users[account].balance = encodeAmount(origBalance - amount); assetStorage.totalBalances = assetCache.totalBalances = encodeAmount(assetCache.totalBalances - amount); updateInterestRate(assetStorage, assetCache); emit Withdraw(assetCache.underlying, account, amount); emitViaProxy_Transfer(eTokenAddress, account, address(0), amount); } function transferBalance(AssetStorage storage assetStorage, AssetCache memory assetCache, address eTokenAddress, address from, address to, uint amount) internal { uint origFromBalance = assetStorage.users[from].balance; require(origFromBalance >= amount, "e/insufficient-balance"); uint newFromBalance; unchecked { newFromBalance = origFromBalance - amount; } assetStorage.users[from].balance = encodeAmount(newFromBalance); assetStorage.users[to].balance = encodeAmount(assetStorage.users[to].balance + amount); emit Withdraw(assetCache.underlying, from, amount); emit Deposit(assetCache.underlying, to, amount); emitViaProxy_Transfer(eTokenAddress, from, to, amount); } function withdrawAmounts(AssetStorage storage assetStorage, AssetCache memory assetCache, address account, uint amount) internal view returns (uint, uint) { uint amountInternal; if (amount == type(uint).max) { amountInternal = assetStorage.users[account].balance; amount = balanceToUnderlyingAmount(assetCache, amountInternal); } else { amount = decodeExternalAmount(assetCache, amount); amountInternal = underlyingAmountToBalanceRoundUp(assetCache, amount); } return (amount, amountInternal); } // Borrows // Returns internal precision function getCurrentOwedExact(AssetStorage storage assetStorage, AssetCache memory assetCache, address account, uint owed) internal view returns (uint) { // Don't bother loading the user's accumulator if (owed == 0) return 0; // Can't divide by 0 here: If owed is non-zero, we must've initialised the user's interestAccumulator return owed * assetCache.interestAccumulator / assetStorage.users[account].interestAccumulator; } // When non-zero, we round *up* to the smallest external unit so that outstanding dust in a loan can be repaid. // unchecked is OK here since owed is always loaded from storage, so we know it fits into a uint144 (pre-interest accural) // Takes and returns 27 decimals precision. function roundUpOwed(AssetCache memory assetCache, uint owed) private pure returns (uint) { if (owed == 0) return 0; unchecked { uint scale = INTERNAL_DEBT_PRECISION * assetCache.underlyingDecimalsScaler; return (owed + scale - 1) / scale * scale; } } // Returns 18-decimals precision (debt amount is rounded up) function getCurrentOwed(AssetStorage storage assetStorage, AssetCache memory assetCache, address account) internal view returns (uint) { return roundUpOwed(assetCache, getCurrentOwedExact(assetStorage, assetCache, account, assetStorage.users[account].owed)) / INTERNAL_DEBT_PRECISION; } function updateUserBorrow(AssetStorage storage assetStorage, AssetCache memory assetCache, address account) private returns (uint newOwedExact, uint prevOwedExact) { prevOwedExact = assetStorage.users[account].owed; newOwedExact = getCurrentOwedExact(assetStorage, assetCache, account, prevOwedExact); assetStorage.users[account].owed = encodeDebtAmount(newOwedExact); assetStorage.users[account].interestAccumulator = assetCache.interestAccumulator; } function logBorrowChange(AssetCache memory assetCache, address dTokenAddress, address account, uint prevOwed, uint owed) private { prevOwed = roundUpOwed(assetCache, prevOwed) / INTERNAL_DEBT_PRECISION; owed = roundUpOwed(assetCache, owed) / INTERNAL_DEBT_PRECISION; if (owed > prevOwed) { uint change = owed - prevOwed; emit Borrow(assetCache.underlying, account, change); emitViaProxy_Transfer(dTokenAddress, address(0), account, change); } else if (prevOwed > owed) { uint change = prevOwed - owed; emit Repay(assetCache.underlying, account, change); emitViaProxy_Transfer(dTokenAddress, account, address(0), change); } } function increaseBorrow(AssetStorage storage assetStorage, AssetCache memory assetCache, address dTokenAddress, address account, uint amount) internal { amount *= INTERNAL_DEBT_PRECISION; require(assetCache.pricingType != PRICINGTYPE__FORWARDED || pTokenLookup[assetCache.underlying] == address(0), "e/borrow-not-supported"); (uint owed, uint prevOwed) = updateUserBorrow(assetStorage, assetCache, account); if (owed == 0) doEnterMarket(account, assetCache.underlying); owed += amount; assetStorage.users[account].owed = encodeDebtAmount(owed); assetStorage.totalBorrows = assetCache.totalBorrows = encodeDebtAmount(assetCache.totalBorrows + amount); updateInterestRate(assetStorage, assetCache); logBorrowChange(assetCache, dTokenAddress, account, prevOwed, owed); } function decreaseBorrow(AssetStorage storage assetStorage, AssetCache memory assetCache, address dTokenAddress, address account, uint origAmount) internal { uint amount = origAmount * INTERNAL_DEBT_PRECISION; (uint owed, uint prevOwed) = updateUserBorrow(assetStorage, assetCache, account); uint owedRoundedUp = roundUpOwed(assetCache, owed); require(amount <= owedRoundedUp, "e/repay-too-much"); uint owedRemaining; unchecked { owedRemaining = owedRoundedUp - amount; } if (owed > assetCache.totalBorrows) owed = assetCache.totalBorrows; assetStorage.users[account].owed = encodeDebtAmount(owedRemaining); assetStorage.totalBorrows = assetCache.totalBorrows = encodeDebtAmount(assetCache.totalBorrows - owed + owedRemaining); updateInterestRate(assetStorage, assetCache); logBorrowChange(assetCache, dTokenAddress, account, prevOwed, owedRemaining); } function transferBorrow(AssetStorage storage assetStorage, AssetCache memory assetCache, address dTokenAddress, address from, address to, uint origAmount) internal { uint amount = origAmount * INTERNAL_DEBT_PRECISION; (uint fromOwed, uint fromOwedPrev) = updateUserBorrow(assetStorage, assetCache, from); (uint toOwed, uint toOwedPrev) = updateUserBorrow(assetStorage, assetCache, to); if (toOwed == 0) doEnterMarket(to, assetCache.underlying); // If amount was rounded up, transfer exact amount owed if (amount > fromOwed && amount - fromOwed < INTERNAL_DEBT_PRECISION * assetCache.underlyingDecimalsScaler) amount = fromOwed; require(fromOwed >= amount, "e/insufficient-balance"); unchecked { fromOwed -= amount; } // Transfer any residual dust if (fromOwed < INTERNAL_DEBT_PRECISION) { amount += fromOwed; fromOwed = 0; } toOwed += amount; assetStorage.users[from].owed = encodeDebtAmount(fromOwed); assetStorage.users[to].owed = encodeDebtAmount(toOwed); logBorrowChange(assetCache, dTokenAddress, from, fromOwedPrev, fromOwed); logBorrowChange(assetCache, dTokenAddress, to, toOwedPrev, toOwed); } // Reserves function increaseReserves(AssetStorage storage assetStorage, AssetCache memory assetCache, uint amount) internal { assetStorage.reserveBalance = assetCache.reserveBalance = encodeSmallAmount(assetCache.reserveBalance + amount); assetStorage.totalBalances = assetCache.totalBalances = encodeAmount(assetCache.totalBalances + amount); } // Token asset transfers // amounts are in underlying units function pullTokens(AssetCache memory assetCache, address from, uint amount) internal returns (uint amountTransferred) { uint poolSizeBefore = assetCache.poolSize; Utils.safeTransferFrom(assetCache.underlying, from, address(this), amount / assetCache.underlyingDecimalsScaler); uint poolSizeAfter = assetCache.poolSize = decodeExternalAmount(assetCache, callBalanceOf(assetCache, address(this))); require(poolSizeAfter >= poolSizeBefore, "e/negative-transfer-amount"); unchecked { amountTransferred = poolSizeAfter - poolSizeBefore; } } function pushTokens(AssetCache memory assetCache, address to, uint amount) internal returns (uint amountTransferred) { uint poolSizeBefore = assetCache.poolSize; Utils.safeTransfer(assetCache.underlying, to, amount / assetCache.underlyingDecimalsScaler); uint poolSizeAfter = assetCache.poolSize = decodeExternalAmount(assetCache, callBalanceOf(assetCache, address(this))); require(poolSizeBefore >= poolSizeAfter, "e/negative-transfer-amount"); unchecked { amountTransferred = poolSizeBefore - poolSizeAfter; } } // Liquidity function getAssetPrice(address asset) internal returns (uint) { bytes memory result = callInternalModule(MODULEID__RISK_MANAGER, abi.encodeWithSelector(IRiskManager.getPrice.selector, asset)); return abi.decode(result, (uint)); } function getAccountLiquidity(address account) internal returns (uint collateralValue, uint liabilityValue) { bytes memory result = callInternalModule(MODULEID__RISK_MANAGER, abi.encodeWithSelector(IRiskManager.computeLiquidity.selector, account)); (IRiskManager.LiquidityStatus memory status) = abi.decode(result, (IRiskManager.LiquidityStatus)); collateralValue = status.collateralValue; liabilityValue = status.liabilityValue; } function checkLiquidity(address account) internal { uint8 status = accountLookup[account].deferLiquidityStatus; if (status == DEFERLIQUIDITY__NONE) { callInternalModule(MODULEID__RISK_MANAGER, abi.encodeWithSelector(IRiskManager.requireLiquidity.selector, account)); } else if (status == DEFERLIQUIDITY__CLEAN) { accountLookup[account].deferLiquidityStatus = DEFERLIQUIDITY__DIRTY; } } // Optional average liquidity tracking function computeNewAverageLiquidity(address account, uint deltaT) private returns (uint) { uint currDuration = deltaT >= AVERAGE_LIQUIDITY_PERIOD ? AVERAGE_LIQUIDITY_PERIOD : deltaT; uint prevDuration = AVERAGE_LIQUIDITY_PERIOD - currDuration; uint currAverageLiquidity; { (uint collateralValue, uint liabilityValue) = getAccountLiquidity(account); currAverageLiquidity = collateralValue > liabilityValue ? collateralValue - liabilityValue : 0; } return (accountLookup[account].averageLiquidity * prevDuration / AVERAGE_LIQUIDITY_PERIOD) + (currAverageLiquidity * currDuration / AVERAGE_LIQUIDITY_PERIOD); } function getUpdatedAverageLiquidity(address account) internal returns (uint) { uint lastAverageLiquidityUpdate = accountLookup[account].lastAverageLiquidityUpdate; if (lastAverageLiquidityUpdate == 0) return 0; uint deltaT = block.timestamp - lastAverageLiquidityUpdate; if (deltaT == 0) return accountLookup[account].averageLiquidity; return computeNewAverageLiquidity(account, deltaT); } function getUpdatedAverageLiquidityWithDelegate(address account) internal returns (uint) { address delegate = accountLookup[account].averageLiquidityDelegate; return delegate != address(0) && accountLookup[delegate].averageLiquidityDelegate == account ? getUpdatedAverageLiquidity(delegate) : getUpdatedAverageLiquidity(account); } function updateAverageLiquidity(address account) internal { uint lastAverageLiquidityUpdate = accountLookup[account].lastAverageLiquidityUpdate; if (lastAverageLiquidityUpdate == 0) return; uint deltaT = block.timestamp - lastAverageLiquidityUpdate; if (deltaT == 0) return; accountLookup[account].lastAverageLiquidityUpdate = uint40(block.timestamp); accountLookup[account].averageLiquidity = computeNewAverageLiquidity(account, deltaT); } } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.7.5; pragma abicoder v2; import './IUniswapV3SwapCallback.sol'; /// @title Router token swapping functionality /// @notice Functions for swapping tokens via Uniswap V3 interface ISwapRouter is IUniswapV3SwapCallback { struct ExactInputSingleParams { address tokenIn; address tokenOut; uint24 fee; address recipient; uint256 deadline; uint256 amountIn; uint256 amountOutMinimum; uint160 sqrtPriceLimitX96; } /// @notice Swaps `amountIn` of one token for as much as possible of another token /// @param params The parameters necessary for the swap, encoded as `ExactInputSingleParams` in calldata /// @return amountOut The amount of the received token function exactInputSingle(ExactInputSingleParams calldata params) external payable returns (uint256 amountOut); struct ExactInputParams { bytes path; address recipient; uint256 deadline; uint256 amountIn; uint256 amountOutMinimum; } /// @notice Swaps `amountIn` of one token for as much as possible of another along the specified path /// @param params The parameters necessary for the multi-hop swap, encoded as `ExactInputParams` in calldata /// @return amountOut The amount of the received token function exactInput(ExactInputParams calldata params) external payable returns (uint256 amountOut); struct ExactOutputSingleParams { address tokenIn; address tokenOut; uint24 fee; address recipient; uint256 deadline; uint256 amountOut; uint256 amountInMaximum; uint160 sqrtPriceLimitX96; } /// @notice Swaps as little as possible of one token for `amountOut` of another token /// @param params The parameters necessary for the swap, encoded as `ExactOutputSingleParams` in calldata /// @return amountIn The amount of the input token function exactOutputSingle(ExactOutputSingleParams calldata params) external payable returns (uint256 amountIn); struct ExactOutputParams { bytes path; address recipient; uint256 deadline; uint256 amountOut; uint256 amountInMaximum; } /// @notice Swaps as little as possible of one token for `amountOut` of another along the specified path (reversed) /// @param params The parameters necessary for the multi-hop swap, encoded as `ExactOutputParams` in calldata /// @return amountIn The amount of the input token function exactOutput(ExactOutputParams calldata params) external payable returns (uint256 amountIn); } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity ^0.8.0; import "./Base.sol"; abstract contract BaseModule is Base { // Construction // public accessors common to all modules uint immutable public moduleId; bytes32 immutable public moduleGitCommit; constructor(uint moduleId_, bytes32 moduleGitCommit_) { moduleId = moduleId_; moduleGitCommit = moduleGitCommit_; } // Accessing parameters function unpackTrailingParamMsgSender() internal pure returns (address msgSender) { assembly { msgSender := shr(96, calldataload(sub(calldatasize(), 40))) } } function unpackTrailingParams() internal pure returns (address msgSender, address proxyAddr) { assembly { msgSender := shr(96, calldataload(sub(calldatasize(), 40))) proxyAddr := shr(96, calldataload(sub(calldatasize(), 20))) } } // Emit logs via proxies function emitViaProxy_Transfer(address proxyAddr, address from, address to, uint value) internal FREEMEM { (bool success,) = proxyAddr.call(abi.encodePacked( uint8(3), keccak256(bytes('Transfer(address,address,uint256)')), bytes32(uint(uint160(from))), bytes32(uint(uint160(to))), value )); require(success, "e/log-proxy-fail"); } function emitViaProxy_Approval(address proxyAddr, address owner, address spender, uint value) internal FREEMEM { (bool success,) = proxyAddr.call(abi.encodePacked( uint8(3), keccak256(bytes('Approval(address,address,uint256)')), bytes32(uint(uint160(owner))), bytes32(uint(uint160(spender))), value )); require(success, "e/log-proxy-fail"); } } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity ^0.8.0; import "./BaseModule.sol"; abstract contract BaseIRM is BaseModule { constructor(uint moduleId_, bytes32 moduleGitCommit_) BaseModule(moduleId_, moduleGitCommit_) {} int96 internal constant MAX_ALLOWED_INTEREST_RATE = int96(int(uint(5 * 1e27) / SECONDS_PER_YEAR)); // 500% APR int96 internal constant MIN_ALLOWED_INTEREST_RATE = 0; function computeInterestRateImpl(address, uint32) internal virtual returns (int96); function computeInterestRate(address underlying, uint32 utilisation) external returns (int96) { int96 rate = computeInterestRateImpl(underlying, utilisation); if (rate > MAX_ALLOWED_INTEREST_RATE) rate = MAX_ALLOWED_INTEREST_RATE; else if (rate < MIN_ALLOWED_INTEREST_RATE) rate = MIN_ALLOWED_INTEREST_RATE; return rate; } function reset(address underlying, bytes calldata resetParams) external virtual {} } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity ^0.8.0; interface IERC20 { event Approval(address indexed owner, address indexed spender, uint value); event Transfer(address indexed from, address indexed to, uint value); function name() external view returns (string memory); function symbol() external view returns (string memory); function decimals() external view returns (uint8); function totalSupply() external view returns (uint); function balanceOf(address owner) external view returns (uint); function allowance(address owner, address spender) external view returns (uint); function approve(address spender, uint value) external returns (bool); function transfer(address to, uint value) external returns (bool); function transferFrom(address from, address to, uint value) external returns (bool); } interface IERC20Permit { function permit(address owner, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) external; function permit(address holder, address spender, uint256 nonce, uint256 expiry, bool allowed, uint8 v, bytes32 r, bytes32 s) external; function permit(address owner, address spender, uint value, uint deadline, bytes calldata signature) external; } interface IERC3156FlashBorrower { function onFlashLoan(address initiator, address token, uint256 amount, uint256 fee, bytes calldata data) external returns (bytes32); } interface IERC3156FlashLender { function maxFlashLoan(address token) external view returns (uint256); function flashFee(address token, uint256 amount) external view returns (uint256); function flashLoan(IERC3156FlashBorrower receiver, address token, uint256 amount, bytes calldata data) external returns (bool); } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity ^0.8.0; import "./Interfaces.sol"; library Utils { function safeTransferFrom(address token, address from, address to, uint value) internal { (bool success, bytes memory data) = token.call(abi.encodeWithSelector(IERC20.transferFrom.selector, from, to, value)); require(success && (data.length == 0 || abi.decode(data, (bool))), string(data)); } function safeTransfer(address token, address to, uint value) internal { (bool success, bytes memory data) = token.call(abi.encodeWithSelector(IERC20.transfer.selector, to, value)); require(success && (data.length == 0 || abi.decode(data, (bool))), string(data)); } function safeApprove(address token, address to, uint value) internal { (bool success, bytes memory data) = token.call(abi.encodeWithSelector(IERC20.approve.selector, to, value)); require(success && (data.length == 0 || abi.decode(data, (bool))), string(data)); } } // SPDX-License-Identifier: AGPL-3.0-or-later // From MakerDAO DSS // Copyright (C) 2018 Rain <[email protected]> // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU Affero General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU Affero General Public License for more details. // // You should have received a copy of the GNU Affero General Public License // along with this program. If not, see <https://www.gnu.org/licenses/>. pragma solidity ^0.8.0; library RPow { function rpow(uint x, uint n, uint base) internal pure returns (uint z) { assembly { switch x case 0 {switch n case 0 {z := base} default {z := 0}} default { switch mod(n, 2) case 0 { z := base } default { z := x } let half := div(base, 2) // for rounding. for { n := div(n, 2) } n { n := div(n,2) } { let xx := mul(x, x) if iszero(eq(div(xx, x), x)) { revert(0,0) } let xxRound := add(xx, half) if lt(xxRound, xx) { revert(0,0) } x := div(xxRound, base) if mod(n,2) { let zx := mul(z, x) if and(iszero(iszero(x)), iszero(eq(div(zx, x), z))) { revert(0,0) } let zxRound := add(zx, half) if lt(zxRound, zx) { revert(0,0) } z := div(zxRound, base) } } } } } } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity ^0.8.0; import "./Storage.sol"; // This interface is used to avoid a circular dependency between BaseLogic and RiskManager interface IRiskManager { struct NewMarketParameters { uint16 pricingType; uint32 pricingParameters; Storage.AssetConfig config; } struct LiquidityStatus { uint collateralValue; uint liabilityValue; uint numBorrows; bool borrowIsolated; } struct AssetLiquidity { address underlying; LiquidityStatus status; } function getNewMarketParameters(address underlying) external returns (NewMarketParameters memory); function requireLiquidity(address account) external view; function computeLiquidity(address account) external view returns (LiquidityStatus memory status); function computeAssetLiquidities(address account) external view returns (AssetLiquidity[] memory assets); function getPrice(address underlying) external view returns (uint twap, uint twapPeriod); function getPriceFull(address underlying) external view returns (uint twap, uint twapPeriod, uint currPrice); } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity ^0.8.0; //import "hardhat/console.sol"; // DEV_MODE import "./Storage.sol"; import "./Events.sol"; import "./Proxy.sol"; abstract contract Base is Storage, Events { // Modules function _createProxy(uint proxyModuleId) internal returns (address) { require(proxyModuleId != 0, "e/create-proxy/invalid-module"); require(proxyModuleId <= MAX_EXTERNAL_MODULEID, "e/create-proxy/internal-module"); // If we've already created a proxy for a single-proxy module, just return it: if (proxyLookup[proxyModuleId] != address(0)) return proxyLookup[proxyModuleId]; // Otherwise create a proxy: address proxyAddr = address(new Proxy()); if (proxyModuleId <= MAX_EXTERNAL_SINGLE_PROXY_MODULEID) proxyLookup[proxyModuleId] = proxyAddr; trustedSenders[proxyAddr] = TrustedSenderInfo({ moduleId: uint32(proxyModuleId), moduleImpl: address(0) }); emit ProxyCreated(proxyAddr, proxyModuleId); return proxyAddr; } function callInternalModule(uint moduleId, bytes memory input) internal returns (bytes memory) { (bool success, bytes memory result) = moduleLookup[moduleId].delegatecall(input); if (!success) revertBytes(result); return result; } // Modifiers modifier nonReentrant() { require(reentrancyLock == REENTRANCYLOCK__UNLOCKED, "e/reentrancy"); reentrancyLock = REENTRANCYLOCK__LOCKED; _; reentrancyLock = REENTRANCYLOCK__UNLOCKED; } modifier reentrantOK() { // documentation only _; } // Used to flag functions which do not modify storage, but do perform a delegate call // to a view function, which prohibits a standard view modifier. The flag is used to // patch state mutability in compiled ABIs and interfaces. modifier staticDelegate() { _; } // WARNING: Must be very careful with this modifier. It resets the free memory pointer // to the value it was when the function started. This saves gas if more memory will // be allocated in the future. However, if the memory will be later referenced // (for example because the function has returned a pointer to it) then you cannot // use this modifier. modifier FREEMEM() { uint origFreeMemPtr; assembly { origFreeMemPtr := mload(0x40) } _; /* assembly { // DEV_MODE: overwrite the freed memory with garbage to detect bugs let garbage := 0xDEADBEEFDEADBEEFDEADBEEFDEADBEEFDEADBEEFDEADBEEFDEADBEEFDEADBEEF for { let i := origFreeMemPtr } lt(i, mload(0x40)) { i := add(i, 32) } { mstore(i, garbage) } } */ assembly { mstore(0x40, origFreeMemPtr) } } // Error handling function revertBytes(bytes memory errMsg) internal pure { if (errMsg.length > 0) { assembly { revert(add(32, errMsg), mload(errMsg)) } } revert("e/empty-error"); } } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity ^0.8.0; import "./Constants.sol"; abstract contract Storage is Constants { // Dispatcher and upgrades uint reentrancyLock; address upgradeAdmin; address governorAdmin; mapping(uint => address) moduleLookup; // moduleId => module implementation mapping(uint => address) proxyLookup; // moduleId => proxy address (only for single-proxy modules) struct TrustedSenderInfo { uint32 moduleId; // 0 = un-trusted address moduleImpl; // only non-zero for external single-proxy modules } mapping(address => TrustedSenderInfo) trustedSenders; // sender address => moduleId (0 = un-trusted) // Account-level state // Sub-accounts are considered distinct accounts struct AccountStorage { // Packed slot: 1 + 5 + 4 + 20 = 30 uint8 deferLiquidityStatus; uint40 lastAverageLiquidityUpdate; uint32 numMarketsEntered; address firstMarketEntered; uint averageLiquidity; address averageLiquidityDelegate; } mapping(address => AccountStorage) accountLookup; mapping(address => address[MAX_POSSIBLE_ENTERED_MARKETS]) marketsEntered; // Markets and assets struct AssetConfig { // Packed slot: 20 + 1 + 4 + 4 + 3 = 32 address eTokenAddress; bool borrowIsolated; uint32 collateralFactor; uint32 borrowFactor; uint24 twapWindow; } struct UserAsset { uint112 balance; uint144 owed; uint interestAccumulator; } struct AssetStorage { // Packed slot: 5 + 1 + 4 + 12 + 4 + 2 + 4 = 32 uint40 lastInterestAccumulatorUpdate; uint8 underlyingDecimals; // Not dynamic, but put here to live in same storage slot uint32 interestRateModel; int96 interestRate; uint32 reserveFee; uint16 pricingType; uint32 pricingParameters; address underlying; uint96 reserveBalance; address dTokenAddress; uint112 totalBalances; uint144 totalBorrows; uint interestAccumulator; mapping(address => UserAsset) users; mapping(address => mapping(address => uint)) eTokenAllowance; mapping(address => mapping(address => uint)) dTokenAllowance; } mapping(address => AssetConfig) internal underlyingLookup; // underlying => AssetConfig mapping(address => AssetStorage) internal eTokenLookup; // EToken => AssetStorage mapping(address => address) internal dTokenLookup; // DToken => EToken mapping(address => address) internal pTokenLookup; // PToken => underlying mapping(address => address) internal reversePTokenLookup; // underlying => PToken } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity ^0.8.0; import "./Storage.sol"; abstract contract Events { event Genesis(); event ProxyCreated(address indexed proxy, uint moduleId); event MarketActivated(address indexed underlying, address indexed eToken, address indexed dToken); event PTokenActivated(address indexed underlying, address indexed pToken); event EnterMarket(address indexed underlying, address indexed account); event ExitMarket(address indexed underlying, address indexed account); event Deposit(address indexed underlying, address indexed account, uint amount); event Withdraw(address indexed underlying, address indexed account, uint amount); event Borrow(address indexed underlying, address indexed account, uint amount); event Repay(address indexed underlying, address indexed account, uint amount); event Liquidation(address indexed liquidator, address indexed violator, address indexed underlying, address collateral, uint repay, uint yield, uint healthScore, uint baseDiscount, uint discount); event TrackAverageLiquidity(address indexed account); event UnTrackAverageLiquidity(address indexed account); event DelegateAverageLiquidity(address indexed account, address indexed delegate); event PTokenWrap(address indexed underlying, address indexed account, uint amount); event PTokenUnWrap(address indexed underlying, address indexed account, uint amount); event AssetStatus(address indexed underlying, uint totalBalances, uint totalBorrows, uint96 reserveBalance, uint poolSize, uint interestAccumulator, int96 interestRate, uint timestamp); event RequestDeposit(address indexed account, uint amount); event RequestWithdraw(address indexed account, uint amount); event RequestMint(address indexed account, uint amount); event RequestBurn(address indexed account, uint amount); event RequestTransferEToken(address indexed from, address indexed to, uint amount); event RequestBorrow(address indexed account, uint amount); event RequestRepay(address indexed account, uint amount); event RequestTransferDToken(address indexed from, address indexed to, uint amount); event RequestLiquidate(address indexed liquidator, address indexed violator, address indexed underlying, address collateral, uint repay, uint minYield); event InstallerSetUpgradeAdmin(address indexed newUpgradeAdmin); event InstallerSetGovernorAdmin(address indexed newGovernorAdmin); event InstallerInstallModule(uint indexed moduleId, address indexed moduleImpl, bytes32 moduleGitCommit); event GovSetAssetConfig(address indexed underlying, Storage.AssetConfig newConfig); event GovSetIRM(address indexed underlying, uint interestRateModel, bytes resetParams); event GovSetPricingConfig(address indexed underlying, uint16 newPricingType, uint32 newPricingParameter); event GovSetReserveFee(address indexed underlying, uint32 newReserveFee); event GovConvertReserves(address indexed underlying, address indexed recipient, uint amount); event RequestSwap(address indexed accountIn, address indexed accountOut, address indexed underlyingIn, address underlyingOut, uint amount, uint swapType); } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity ^0.8.0; contract Proxy { address immutable creator; constructor() { creator = msg.sender; } // External interface fallback() external { address creator_ = creator; if (msg.sender == creator_) { assembly { mstore(0, 0) calldatacopy(31, 0, calldatasize()) switch mload(0) // numTopics case 0 { log0(32, sub(calldatasize(), 1)) } case 1 { log1(64, sub(calldatasize(), 33), mload(32)) } case 2 { log2(96, sub(calldatasize(), 65), mload(32), mload(64)) } case 3 { log3(128, sub(calldatasize(), 97), mload(32), mload(64), mload(96)) } case 4 { log4(160, sub(calldatasize(), 129), mload(32), mload(64), mload(96), mload(128)) } default { revert(0, 0) } return(0, 0) } } else { assembly { mstore(0, 0xe9c4a3ac00000000000000000000000000000000000000000000000000000000) // dispatch() selector calldatacopy(4, 0, calldatasize()) mstore(add(4, calldatasize()), shl(96, caller())) let result := call(gas(), creator_, 0, 0, add(24, calldatasize()), 0, 0) returndatacopy(0, 0, returndatasize()) switch result case 0 { revert(0, returndatasize()) } default { return(0, returndatasize()) } } } } } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity ^0.8.0; abstract contract Constants { // Universal uint internal constant SECONDS_PER_YEAR = 365.2425 * 86400; // Gregorian calendar // Protocol parameters uint internal constant MAX_SANE_AMOUNT = type(uint112).max; uint internal constant MAX_SANE_SMALL_AMOUNT = type(uint96).max; uint internal constant MAX_SANE_DEBT_AMOUNT = type(uint144).max; uint internal constant INTERNAL_DEBT_PRECISION = 1e9; uint internal constant MAX_ENTERED_MARKETS = 10; // per sub-account uint internal constant MAX_POSSIBLE_ENTERED_MARKETS = 2**32; // limited by size of AccountStorage.numMarketsEntered uint internal constant CONFIG_FACTOR_SCALE = 4_000_000_000; // must fit into a uint32 uint internal constant RESERVE_FEE_SCALE = 4_000_000_000; // must fit into a uint32 uint32 internal constant DEFAULT_RESERVE_FEE = uint32(0.23 * 4_000_000_000); uint internal constant INITIAL_INTEREST_ACCUMULATOR = 1e27; uint internal constant AVERAGE_LIQUIDITY_PERIOD = 24 * 60 * 60; uint16 internal constant MIN_UNISWAP3_OBSERVATION_CARDINALITY = 144; uint24 internal constant DEFAULT_TWAP_WINDOW_SECONDS = 30 * 60; uint32 internal constant DEFAULT_BORROW_FACTOR = uint32(0.28 * 4_000_000_000); uint32 internal constant SELF_COLLATERAL_FACTOR = uint32(0.95 * 4_000_000_000); // Implementation internals uint internal constant REENTRANCYLOCK__UNLOCKED = 1; uint internal constant REENTRANCYLOCK__LOCKED = 2; uint8 internal constant DEFERLIQUIDITY__NONE = 0; uint8 internal constant DEFERLIQUIDITY__CLEAN = 1; uint8 internal constant DEFERLIQUIDITY__DIRTY = 2; // Pricing types uint16 internal constant PRICINGTYPE__PEGGED = 1; uint16 internal constant PRICINGTYPE__UNISWAP3_TWAP = 2; uint16 internal constant PRICINGTYPE__FORWARDED = 3; // Modules // Public single-proxy modules uint internal constant MODULEID__INSTALLER = 1; uint internal constant MODULEID__MARKETS = 2; uint internal constant MODULEID__LIQUIDATION = 3; uint internal constant MODULEID__GOVERNANCE = 4; uint internal constant MODULEID__EXEC = 5; uint internal constant MODULEID__SWAP = 6; uint internal constant MAX_EXTERNAL_SINGLE_PROXY_MODULEID = 499_999; // Public multi-proxy modules uint internal constant MODULEID__ETOKEN = 500_000; uint internal constant MODULEID__DTOKEN = 500_001; uint internal constant MAX_EXTERNAL_MODULEID = 999_999; // Internal modules uint internal constant MODULEID__RISK_MANAGER = 1_000_000; // Interest rate models // Default for new markets uint internal constant MODULEID__IRM_DEFAULT = 2_000_000; // Testing-only uint internal constant MODULEID__IRM_ZERO = 2_000_001; uint internal constant MODULEID__IRM_FIXED = 2_000_002; uint internal constant MODULEID__IRM_LINEAR = 2_000_100; // Classes uint internal constant MODULEID__IRM_CLASS__STABLE = 2_000_500; uint internal constant MODULEID__IRM_CLASS__MAJOR = 2_000_501; uint internal constant MODULEID__IRM_CLASS__MIDCAP = 2_000_502; uint internal constant MODULEID__IRM_CLASS__MEGA = 2_000_503; // Swap types uint internal constant SWAP_TYPE__UNI_EXACT_INPUT_SINGLE = 1; uint internal constant SWAP_TYPE__UNI_EXACT_INPUT = 2; uint internal constant SWAP_TYPE__UNI_EXACT_OUTPUT_SINGLE = 3; uint internal constant SWAP_TYPE__UNI_EXACT_OUTPUT = 4; uint internal constant SWAP_TYPE__1INCH = 5; uint internal constant SWAP_TYPE__UNI_EXACT_OUTPUT_SINGLE_REPAY = 6; uint internal constant SWAP_TYPE__UNI_EXACT_OUTPUT_REPAY = 7; } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.5.0; /// @title Callback for IUniswapV3PoolActions#swap /// @notice Any contract that calls IUniswapV3PoolActions#swap must implement this interface interface IUniswapV3SwapCallback { /// @notice Called to `msg.sender` after executing a swap via IUniswapV3Pool#swap. /// @dev In the implementation you must pay the pool tokens owed for the swap. /// The caller of this method must be checked to be a UniswapV3Pool deployed by the canonical UniswapV3Factory. /// amount0Delta and amount1Delta can both be 0 if no tokens were swapped. /// @param amount0Delta The amount of token0 that was sent (negative) or must be received (positive) by the pool by /// the end of the swap. If positive, the callback must send that amount of token0 to the pool. /// @param amount1Delta The amount of token1 that was sent (negative) or must be received (positive) by the pool by /// the end of the swap. If positive, the callback must send that amount of token1 to the pool. /// @param data Any data passed through by the caller via the IUniswapV3PoolActions#swap call function uniswapV3SwapCallback( int256 amount0Delta, int256 amount1Delta, bytes calldata data ) external; }
Execute Uniswap V3 exact output trade on a single pool params struct defining trade parameters
function swapUniExactOutputSingle(SwapUniExactOutputSingleParams memory params) external nonReentrant { SwapCache memory swap = initSwap( params.underlyingIn, params.underlyingOut, params.amountOut, params.subAccountIdIn, params.subAccountIdOut, SWAP_TYPE__UNI_EXACT_OUTPUT_SINGLE ); swap.amountOut = params.amountOut; doSwapUniExactOutputSingle(swap, params); finalizeSwap(swap); }
25,734
pragma solidity ^0.4.21; /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { function mul(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a * b; assert(a == 0 || c / a == b); return c; } function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } } /** * @title ERC20Basic * @dev Simpler version of ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/179 */ contract ERC20Basic { uint256 public totalSupply; function balanceOf(address who) public constant 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; /** * @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) { 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 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)) allowed; /** * @dev Transfer tokens from one address to another * @param _from address The address which you want to send tokens from * @param _to address The address which you want to transfer to * @param _value uint256 the amout of tokens to be transfered */ function transferFrom(address _from, address _to, uint256 _value)public returns (bool) { // Check is not needed because sub(_allowance, _value) will already throw if this condition is not met // require (_value <= _allowance); balances[_to] = balances[_to].add(_value); balances[_from] = balances[_from].sub(_value); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); emit Transfer(_from, _to, _value); return true; } /** * @dev Aprove the passed address to spend the specified amount of tokens on behalf of msg.sender. * @param _spender The address which will spend the funds. * @param _value The amount of tokens to be spent. */ function approve(address _spender, uint256 _value)public returns (bool) { // To change the approve amount you first have to reduce the addresses` // allowance to zero by calling `approve(_spender, 0)` if it is not // already 0 to mitigate the race condition described here: // https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 require((_value == 0) || (allowed[msg.sender][_spender] == 0)); allowed[msg.sender][_spender] = _value; 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 specifing the amount of tokens still available for the spender. */ function allowance(address _owner, address _spender)public constant returns (uint256 remaining) { return allowed[_owner][_spender]; } } /** * @title SimpleToken * @dev Very simple ERC20 Token example, 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 LTBToken is StandardToken { string public constant name = "Litrabit"; string public constant symbol = "LTB"; uint256 public constant decimals = 18; uint256 public constant INITIAL_SUPPLY = 22000000 * 10**18; /** * @dev Contructor that gives msg.sender all of existing tokens. */ function LTBToken()public { totalSupply = INITIAL_SUPPLY; balances[msg.sender] = INITIAL_SUPPLY; } }
Contructor that gives msg.sender all of existing tokens./
function LTBToken()public { totalSupply = INITIAL_SUPPLY; balances[msg.sender] = INITIAL_SUPPLY; }
6,053,772
// SPDX-License-Identifier: MIT pragma solidity 0.7.5; import './Context.sol'; import './Strings.sol'; import './ERC165.sol'; /** * @dev External interface of AccessControl declared to support ERC165 detection. */ interface IAccessControlUpgradeable { function hasRole(bytes32 role, address account) external view returns (bool); function getRoleAdmin(bytes32 role) external view returns (bytes32); function grantRole(bytes32 role, address account) external; function revokeRole(bytes32 role, address account) external; function renounceRole(bytes32 role, address account) external; } /** * @dev Contract module that allows children to implement role-based access * control mechanisms. This is a lightweight version that doesn't allow enumerating role * members except through off-chain means by accessing the contract event logs. Some * applications may benefit from on-chain enumerability, for those cases see * {AccessControlEnumerable}. * * Roles are referred to by their `bytes32` identifier. These should be exposed * in the external API and be unique. The best way to achieve this is by * using `public constant` hash digests: * * ``` * bytes32 public constant MY_ROLE = keccak256("MY_ROLE"); * ``` * * Roles can be used to represent a set of permissions. To restrict access to a * function call, use {hasRole}: * * ``` * function foo() public { * require(hasRole(MY_ROLE, msg.sender)); * ... * } * ``` * * Roles can be granted and revoked dynamically via the {grantRole} and * {revokeRole} functions. Each role has an associated admin role, and only * accounts that have a role's admin role can call {grantRole} and {revokeRole}. * * By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means * that only accounts with this role will be able to grant or revoke other * roles. More complex role relationships can be created by using * {_setRoleAdmin}. * * WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to * grant and revoke this role. Extra precautions should be taken to secure * accounts that have been granted it. */ abstract contract AccessControlUpgradeable is Context, IAccessControlUpgradeable, ERC165 { struct RoleData { mapping(address => bool) members; bytes32 adminRole; } mapping(bytes32 => RoleData) private _roles; bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00; /** * @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole` * * `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite * {RoleAdminChanged} not being emitted signaling this. * * _Available since v3.1._ */ event RoleAdminChanged( bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole ); /** * @dev Emitted when `account` is granted `role`. * * `sender` is the account that originated the contract call, an admin role * bearer except when using {_setupRole}. */ event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Emitted when `account` is revoked `role`. * * `sender` is the account that originated the contract call: * - if using `revokeRole`, it is the admin role bearer * - if using `renounceRole`, it is the role bearer (i.e. `account`) */ event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev 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]{20}) is missing role (0x[0-9a-f]{32})$/ * * _Available since v4.1._ */ modifier onlyRole(bytes32 role) { _checkRole(role, _msgSender()); _; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IAccessControlUpgradeable).interfaceId || super.supportsInterface(interfaceId); } /** * @dev Returns `true` if `account` has been granted `role`. */ function hasRole(bytes32 role, address account) public view override returns (bool) { return _roles[role].members[account]; } /** * @dev Revert with a standard message if `account` is missing `role`. * * The format of the revert reason is given by the following regular expression: * * /^AccessControl: account (0x[0-9a-f]{20}) is missing role (0x[0-9a-f]{32})$/ */ 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 { emit RoleAdminChanged(role, getRoleAdmin(role), adminRole); _roles[role].adminRole = adminRole; } function _grantRole(bytes32 role, address account) private { if (!hasRole(role, account)) { _roles[role].members[account] = true; emit RoleGranted(role, account, _msgSender()); } } function _revokeRole(bytes32 role, address account) private { if (hasRole(role, account)) { _roles[role].members[account] = false; emit RoleRevoked(role, account, _msgSender()); } } uint256[49] private __gap; } // SPDX-License-Identifier: MIT pragma solidity 0.7.5; /* * @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.7.5; /** * @dev String operations. */ library Strings { bytes16 private constant alphabet = '0123456789abcdef'; /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return '0'; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return '0x00'; } uint256 temp = value; uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return toHexString(value, length); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = '0'; buffer[1] = 'x'; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = alphabet[value & 0xf]; value >>= 4; } require(value == 0, 'Strings: hex length insufficient'); return string(buffer); } } // SPDX-License-Identifier: MIT pragma solidity 0.7.5; 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.7.5; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // SPDX-License-Identifier: Apache-2.0 pragma solidity 0.7.5; pragma abicoder v2; import { AccessControlUpgradeable } from '../../../dependencies/open-zeppelin/AccessControlUpgradeable.sol'; import { ReentrancyGuard } from '../../../utils/ReentrancyGuard.sol'; import { VersionedInitializable } from '../../../utils/VersionedInitializable.sol'; import { LS1Types } from '../lib/LS1Types.sol'; /** * @title LS1Storage * @author dYdX * * @dev Storage contract. Contains or inherits from all contract with storage. */ abstract contract LS1Storage is AccessControlUpgradeable, ReentrancyGuard, VersionedInitializable { // ============ Epoch Schedule ============ /// @dev The parameters specifying the function from timestamp to epoch number. LS1Types.EpochParameters internal _EPOCH_PARAMETERS_; /// @dev The period of time at the end of each epoch in which withdrawals cannot be requested. /// We also restrict other changes which could affect borrowers' repayment plans, such as /// modifications to the epoch schedule, or to borrower allocations. uint256 internal _BLACKOUT_WINDOW_; // ============ Staked Token ERC20 ============ mapping(address => mapping(address => uint256)) internal _ALLOWANCES_; // ============ Rewards Accounting ============ /// @dev The emission rate of rewards. uint256 internal _REWARDS_PER_SECOND_; /// @dev The cumulative rewards earned per staked token. (Shared storage slot.) uint224 internal _GLOBAL_INDEX_; /// @dev The timestamp at which the global index was last updated. (Shared storage slot.) uint32 internal _GLOBAL_INDEX_TIMESTAMP_; /// @dev The value of the global index when the user's staked balance was last updated. mapping(address => uint256) internal _USER_INDEXES_; /// @dev The user's accrued, unclaimed rewards (as of the last update to the user index). mapping(address => uint256) internal _USER_REWARDS_BALANCES_; /// @dev The value of the global index at the end of a given epoch. mapping(uint256 => uint256) internal _EPOCH_INDEXES_; // ============ Staker Accounting ============ /// @dev The active balance by staker. mapping(address => LS1Types.StoredBalance) internal _ACTIVE_BALANCES_; /// @dev The total active balance of stakers. LS1Types.StoredBalance internal _TOTAL_ACTIVE_BALANCE_; /// @dev The inactive balance by staker. mapping(address => LS1Types.StoredBalance) internal _INACTIVE_BALANCES_; /// @dev The total inactive balance of stakers. Note: The shortfallCounter field is unused. LS1Types.StoredBalance internal _TOTAL_INACTIVE_BALANCE_; /// @dev Information about shortfalls that have occurred. LS1Types.Shortfall[] internal _SHORTFALLS_; // ============ Borrower Accounting ============ /// @dev The units allocated to each borrower. /// @dev Values are represented relative to total allocation, i.e. as hundredeths of a percent. /// Also, the total of the values contained in the mapping must always equal the total /// allocation (i.e. must sum to 10,000). mapping(address => LS1Types.StoredAllocation) internal _BORROWER_ALLOCATIONS_; /// @dev The token balance currently borrowed by the borrower. mapping(address => uint256) internal _BORROWED_BALANCES_; /// @dev The total token balance currently borrowed by borrowers. uint256 internal _TOTAL_BORROWED_BALANCE_; /// @dev Indicates whether a borrower is restricted from new borrowing. mapping(address => bool) internal _BORROWER_RESTRICTIONS_; // ============ Debt Accounting ============ /// @dev The debt balance owed to each staker. mapping(address => uint256) internal _STAKER_DEBT_BALANCES_; /// @dev The debt balance by borrower. mapping(address => uint256) internal _BORROWER_DEBT_BALANCES_; /// @dev The total debt balance of borrowers. uint256 internal _TOTAL_BORROWER_DEBT_BALANCE_; /// @dev The total debt amount repaid and not yet withdrawn. uint256 internal _TOTAL_DEBT_AVAILABLE_TO_WITHDRAW_; } // SPDX-License-Identifier: Apache-2.0 pragma solidity 0.7.5; pragma abicoder v2; /** * @title ReentrancyGuard * @author dYdX * * @dev Updated ReentrancyGuard library designed to be used with Proxy Contracts. */ abstract contract ReentrancyGuard { uint256 private constant NOT_ENTERED = 1; uint256 private constant ENTERED = uint256(int256(-1)); uint256 private _STATUS_; constructor() internal { _STATUS_ = NOT_ENTERED; } modifier nonReentrant() { require(_STATUS_ != ENTERED, 'ReentrancyGuard: reentrant call'); _STATUS_ = ENTERED; _; _STATUS_ = NOT_ENTERED; } } // SPDX-License-Identifier: AGPL-3.0 pragma solidity 0.7.5; /** * @title VersionedInitializable * @author Aave, inspired by the OpenZeppelin Initializable contract * * @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. * */ abstract contract VersionedInitializable { /** * @dev Indicates that the contract has been initialized. */ uint256 internal lastInitializedRevision = 0; /** * @dev Modifier to use in the initializer function of a contract. */ modifier initializer() { uint256 revision = getRevision(); require(revision > lastInitializedRevision, "Contract instance has already been initialized"); lastInitializedRevision = revision; _; } /// @dev returns the revision number of the contract. /// Needs to be defined in the inherited class as a constant. function getRevision() internal pure virtual returns(uint256); // Reserved storage space to allow for layout changes in the future. uint256[50] private ______gap; } // SPDX-License-Identifier: Apache-2.0 pragma solidity 0.7.5; pragma abicoder v2; /** * @title LS1Types * @author dYdX * * @dev Structs used by the LiquidityStaking contract. */ library LS1Types { /** * @dev The parameters used to convert a timestamp to an epoch number. */ struct EpochParameters { uint128 interval; uint128 offset; } /** * @dev The parameters representing a shortfall event. * * @param index Fraction of inactive funds converted into debt, scaled by SHORTFALL_INDEX_BASE. * @param epoch The epoch in which the shortfall occurred. */ struct Shortfall { uint16 epoch; // Note: Supports at least 1000 years given min epoch length of 6 days. uint224 index; // Note: Save on contract bytecode size by reusing uint224 instead of uint240. } /** * @dev A balance, possibly with a change scheduled for the next epoch. * Also includes cached index information for inactive balances. * * @param currentEpoch The epoch in which the balance was last updated. * @param currentEpochBalance The balance at epoch `currentEpoch`. * @param nextEpochBalance The balance at epoch `currentEpoch + 1`. * @param shortfallCounter Incrementing counter of the next shortfall index to be applied. */ struct StoredBalance { uint16 currentEpoch; // Supports at least 1000 years given min epoch length of 6 days. uint112 currentEpochBalance; uint112 nextEpochBalance; uint16 shortfallCounter; // Only for staker inactive balances. At most one shortfall per epoch. } /** * @dev A borrower allocation, possibly with a change scheduled for the next epoch. */ struct StoredAllocation { uint16 currentEpoch; // Note: Supports at least 1000 years given min epoch length of 6 days. uint120 currentEpochAllocation; uint120 nextEpochAllocation; } } // SPDX-License-Identifier: Apache-2.0 pragma solidity 0.7.5; pragma abicoder v2; import { SafeMath } from '../../../dependencies/open-zeppelin/SafeMath.sol'; import { Math } from '../../../utils/Math.sol'; import { LS1Types } from '../lib/LS1Types.sol'; import { LS1Storage } from './LS1Storage.sol'; /** * @title LS1Getters * @author dYdX * * @dev Some external getter functions. */ abstract contract LS1Getters is LS1Storage { using SafeMath for uint256; // ============ External Functions ============ /** * @notice The token balance currently borrowed by the borrower. * * @param borrower The borrower whose balance to query. * * @return The number of tokens borrowed. */ function getBorrowedBalance( address borrower ) external view returns (uint256) { return _BORROWED_BALANCES_[borrower]; } /** * @notice The total token balance borrowed by borrowers. * * @return The number of tokens borrowed. */ function getTotalBorrowedBalance() external view returns (uint256) { return _TOTAL_BORROWED_BALANCE_; } /** * @notice The debt balance owed by the borrower. * * @param borrower The borrower whose balance to query. * * @return The number of tokens owed. */ function getBorrowerDebtBalance( address borrower ) external view returns (uint256) { return _BORROWER_DEBT_BALANCES_[borrower]; } /** * @notice The total debt balance owed by borrowers. * * @return The number of tokens owed. */ function getTotalBorrowerDebtBalance() external view returns (uint256) { return _TOTAL_BORROWER_DEBT_BALANCE_; } /** * @notice The total debt repaid by borrowers and available for stakers to withdraw. * * @return The number of tokens available. */ function getTotalDebtAvailableToWithdraw() external view returns (uint256) { return _TOTAL_DEBT_AVAILABLE_TO_WITHDRAW_; } /** * @notice Check whether a borrower is restricted from new borrowing. * * @param borrower The borrower to check. * * @return Boolean `true` if the borrower is restricted, otherwise `false`. */ function isBorrowingRestrictedForBorrower( address borrower ) external view returns (bool) { return _BORROWER_RESTRICTIONS_[borrower]; } /** * @notice The parameters specifying the function from timestamp to epoch number. * * @return The parameters struct with `interval` and `offset` fields. */ function getEpochParameters() external view returns (LS1Types.EpochParameters memory) { return _EPOCH_PARAMETERS_; } /** * @notice The period of time at the end of each epoch in which withdrawals cannot be requested. * * Other changes which could affect borrowers' repayment plans are also restricted during * this period. */ function getBlackoutWindow() external view returns (uint256) { return _BLACKOUT_WINDOW_; } /** * @notice Get information about a shortfall that occurred. * * @param shortfallCounter The array index for the shortfall event to look up. * * @return Struct containing the epoch and shortfall index value. */ function getShortfall( uint256 shortfallCounter ) external view returns (LS1Types.Shortfall memory) { return _SHORTFALLS_[shortfallCounter]; } /** * @notice Get the number of shortfalls that have occurred. * * @return The number of shortfalls that have occurred. */ function getShortfallCount() external view returns (uint256) { return _SHORTFALLS_.length; } } // SPDX-License-Identifier: MIT pragma solidity 0.7.5; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, 'SafeMath: addition overflow'); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, 'SafeMath: subtraction overflow'); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. */ function sub( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, 'SafeMath: multiplication overflow'); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, 'SafeMath: division by zero'); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function div( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { // Solidity only automatically asserts when dividing by 0 require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, 'SafeMath: modulo by zero'); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function mod( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } // SPDX-License-Identifier: Apache-2.0 pragma solidity 0.7.5; pragma abicoder v2; import { SafeMath } from '../dependencies/open-zeppelin/SafeMath.sol'; /** * @title Math * @author dYdX * * @dev Library for non-standard Math functions. */ library Math { using SafeMath for uint256; // ============ Library Functions ============ /** * @dev Return `ceil(numerator / denominator)`. */ function divRoundUp( uint256 numerator, uint256 denominator ) internal pure returns (uint256) { if (numerator == 0) { // SafeMath will check for zero denominator return SafeMath.div(0, denominator); } return numerator.sub(1).div(denominator).add(1); } /** * @dev Returns the minimum between a and b. */ function min( uint256 a, uint256 b ) internal pure returns (uint256) { return a < b ? a : b; } /** * @dev Returns the maximum between a and b. */ function max( uint256 a, uint256 b ) internal pure returns (uint256) { return a > b ? a : b; } } // SPDX-License-Identifier: Apache-2.0 // // Contracts by dYdX Foundation. Individual files are released under different licenses. // // https://dydx.community // https://github.com/dydxfoundation/governance-contracts pragma solidity 0.7.5; pragma abicoder v2; import { IERC20 } from '../../interfaces/IERC20.sol'; import { LS1Admin } from './impl/LS1Admin.sol'; import { LS1Borrowing } from './impl/LS1Borrowing.sol'; import { LS1DebtAccounting } from './impl/LS1DebtAccounting.sol'; import { LS1ERC20 } from './impl/LS1ERC20.sol'; import { LS1Failsafe } from './impl/LS1Failsafe.sol'; import { LS1Getters } from './impl/LS1Getters.sol'; import { LS1Operators } from './impl/LS1Operators.sol'; /** * @title LiquidityStakingV1 * @author dYdX * * @notice Contract for staking tokens, which may then be borrowed by pre-approved borrowers. * * NOTE: Most functions will revert if epoch zero has not started. */ contract LiquidityStakingV1 is LS1Borrowing, LS1DebtAccounting, LS1Admin, LS1Operators, LS1Getters, LS1Failsafe { // ============ Constructor ============ constructor( IERC20 stakedToken, IERC20 rewardsToken, address rewardsTreasury, uint256 distributionStart, uint256 distributionEnd ) LS1Borrowing(stakedToken, rewardsToken, rewardsTreasury, distributionStart, distributionEnd) {} // ============ External Functions ============ function initialize( uint256 interval, uint256 offset, uint256 blackoutWindow ) external initializer { __LS1Roles_init(); __LS1EpochSchedule_init(interval, offset, blackoutWindow); __LS1Rewards_init(); __LS1BorrowerAllocations_init(); } // ============ Internal Functions ============ /** * @dev Returns the revision of the implementation contract. * * @return The revision number. */ function getRevision() internal pure override returns (uint256) { return 1; } } // SPDX-License-Identifier: AGPL-3.0 pragma solidity 0.7.5; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: Apache-2.0 pragma solidity 0.7.5; pragma abicoder v2; import { SafeMath } from '../../../dependencies/open-zeppelin/SafeMath.sol'; import { LS1Types } from '../lib/LS1Types.sol'; import { SafeCast } from '../lib/SafeCast.sol'; import { LS1Borrowing } from './LS1Borrowing.sol'; /** * @title LS1Admin * @author dYdX * * @dev Admin-only functions. */ abstract contract LS1Admin is LS1Borrowing { using SafeCast for uint256; using SafeMath for uint256; // ============ External Functions ============ /** * @notice Set the parameters defining the function from timestamp to epoch number. * * The formula used is `n = floor((t - b) / a)` where: * - `n` is the epoch number * - `t` is the timestamp (in seconds) * - `b` is a non-negative offset, indicating the start of epoch zero (in seconds) * - `a` is the length of an epoch, a.k.a. the interval (in seconds) * * Reverts if epoch zero already started, and the new parameters would change the current epoch. * Reverts if epoch zero has not started, but would have had started under the new parameters. * Reverts if the new interval is less than twice the blackout window. * * @param interval The length `a` of an epoch, in seconds. * @param offset The offset `b`, i.e. the start of epoch zero, in seconds. */ function setEpochParameters( uint256 interval, uint256 offset ) external onlyRole(EPOCH_PARAMETERS_ROLE) nonReentrant { if (!hasEpochZeroStarted()) { require(block.timestamp < offset, 'LS1Admin: Started epoch zero'); _setEpochParameters(interval, offset); return; } // Require that we are not currently in a blackout window. require( !inBlackoutWindow(), 'LS1Admin: Blackout window' ); // We must settle the total active balance to ensure the index is recorded at the epoch // boundary as needed, before we make any changes to the epoch formula. _settleTotalActiveBalance(); // Update the epoch parameters. Require that the current epoch number is unchanged. uint256 originalCurrentEpoch = getCurrentEpoch(); _setEpochParameters(interval, offset); uint256 newCurrentEpoch = getCurrentEpoch(); require(originalCurrentEpoch == newCurrentEpoch, 'LS1Admin: Changed epochs'); // Require that the new parameters don't put us in a blackout window. require(!inBlackoutWindow(), 'LS1Admin: End in blackout window'); } /** * @notice Set the blackout window, during which one cannot request withdrawals of staked funds. */ function setBlackoutWindow( uint256 blackoutWindow ) external onlyRole(EPOCH_PARAMETERS_ROLE) nonReentrant { require( !inBlackoutWindow(), 'LS1Admin: Blackout window' ); _setBlackoutWindow(blackoutWindow); // Require that the new parameters don't put us in a blackout window. require(!inBlackoutWindow(), 'LS1Admin: End in blackout window'); } /** * @notice Set the emission rate of rewards. * * @param emissionPerSecond The new number of rewards tokens given out per second. */ function setRewardsPerSecond( uint256 emissionPerSecond ) external onlyRole(REWARDS_RATE_ROLE) nonReentrant { uint256 totalStaked = 0; if (hasEpochZeroStarted()) { // We must settle the total active balance to ensure the index is recorded at the epoch // boundary as needed, before we make any changes to the emission rate. totalStaked = _settleTotalActiveBalance(); } _setRewardsPerSecond(emissionPerSecond, totalStaked); } /** * @notice Change the allocations of certain borrowers. Can be used to add and remove borrowers. * Increases take effect in the next epoch, but decreases will restrict borrowing immediately. * This function cannot be called during the blackout window. * * @param borrowers Array of borrower addresses. * @param newAllocations Array of new allocations per borrower, as hundredths of a percent. */ function setBorrowerAllocations( address[] calldata borrowers, uint256[] calldata newAllocations ) external onlyRole(BORROWER_ADMIN_ROLE) nonReentrant { require(borrowers.length == newAllocations.length, 'LS1Admin: Params length mismatch'); require( !inBlackoutWindow(), 'LS1Admin: Blackout window' ); _setBorrowerAllocations(borrowers, newAllocations); } function setBorrowingRestriction( address borrower, bool isBorrowingRestricted ) external onlyRole(BORROWER_ADMIN_ROLE) nonReentrant { _setBorrowingRestriction(borrower, isBorrowingRestricted); } } // SPDX-License-Identifier: Apache-2.0 pragma solidity 0.7.5; pragma abicoder v2; import { SafeERC20 } from '../../../dependencies/open-zeppelin/SafeERC20.sol'; import { SafeMath } from '../../../dependencies/open-zeppelin/SafeMath.sol'; import { IERC20 } from '../../../interfaces/IERC20.sol'; import { Math } from '../../../utils/Math.sol'; import { LS1Types } from '../lib/LS1Types.sol'; import { SafeCast } from '../lib/SafeCast.sol'; import { LS1BorrowerAllocations } from './LS1BorrowerAllocations.sol'; import { LS1Staking } from './LS1Staking.sol'; /** * @title LS1Borrowing * @author dYdX * * @dev External functions for borrowers. See LS1BorrowerAllocations for details on * borrower accounting. */ abstract contract LS1Borrowing is LS1Staking, LS1BorrowerAllocations { using SafeCast for uint256; using SafeERC20 for IERC20; using SafeMath for uint256; // ============ Events ============ event Borrowed( address indexed borrower, uint256 amount, uint256 newBorrowedBalance ); event RepaidBorrow( address indexed borrower, address sender, uint256 amount, uint256 newBorrowedBalance ); event RepaidDebt( address indexed borrower, address sender, uint256 amount, uint256 newDebtBalance ); // ============ Constructor ============ constructor( IERC20 stakedToken, IERC20 rewardsToken, address rewardsTreasury, uint256 distributionStart, uint256 distributionEnd ) LS1Staking(stakedToken, rewardsToken, rewardsTreasury, distributionStart, distributionEnd) {} // ============ External Functions ============ /** * @notice Borrow staked funds. * * @param amount The token amount to borrow. */ function borrow( uint256 amount ) external nonReentrant { require(amount > 0, 'LS1Borrowing: Cannot borrow zero'); address borrower = msg.sender; // Revert if the borrower is restricted. require(!_BORROWER_RESTRICTIONS_[borrower], 'LS1Borrowing: Restricted'); // Get contract available amount and revert if there is not enough to withdraw. uint256 totalAvailableForBorrow = getContractBalanceAvailableToBorrow(); require( amount <= totalAvailableForBorrow, 'LS1Borrowing: Amount > available' ); // Get new net borrow and revert if it is greater than the allocated balance for new borrowing. uint256 newBorrowedBalance = _BORROWED_BALANCES_[borrower].add(amount); require( newBorrowedBalance <= _getAllocatedBalanceForNewBorrowing(borrower), 'LS1Borrowing: Amount > allocated' ); // Update storage. _BORROWED_BALANCES_[borrower] = newBorrowedBalance; _TOTAL_BORROWED_BALANCE_ = _TOTAL_BORROWED_BALANCE_.add(amount); // Transfer token to the borrower. STAKED_TOKEN.safeTransfer(borrower, amount); emit Borrowed(borrower, amount, newBorrowedBalance); } /** * @notice Repay borrowed funds for the specified borrower. Reverts if repay amount exceeds * borrowed amount. * * @param borrower The borrower on whose behalf to make a repayment. * @param amount The amount to repay. */ function repayBorrow( address borrower, uint256 amount ) external nonReentrant { require(amount > 0, 'LS1Borrowing: Cannot repay zero'); uint256 oldBorrowedBalance = _BORROWED_BALANCES_[borrower]; require(amount <= oldBorrowedBalance, 'LS1Borrowing: Repay > borrowed'); uint256 newBorrowedBalance = oldBorrowedBalance.sub(amount); // Update storage. _BORROWED_BALANCES_[borrower] = newBorrowedBalance; _TOTAL_BORROWED_BALANCE_ = _TOTAL_BORROWED_BALANCE_.sub(amount); // Transfer token from the sender. STAKED_TOKEN.safeTransferFrom(msg.sender, address(this), amount); emit RepaidBorrow(borrower, msg.sender, amount, newBorrowedBalance); } /** * @notice Repay a debt amount owed by a borrower. * * @param borrower The borrower whose debt to repay. * @param amount The amount to repay. */ function repayDebt( address borrower, uint256 amount ) external nonReentrant { require(amount > 0, 'LS1Borrowing: Cannot repay zero'); uint256 oldDebtAmount = _BORROWER_DEBT_BALANCES_[borrower]; require(amount <= oldDebtAmount, 'LS1Borrowing: Repay > debt'); uint256 newDebtBalance = oldDebtAmount.sub(amount); // Update storage. _BORROWER_DEBT_BALANCES_[borrower] = newDebtBalance; _TOTAL_BORROWER_DEBT_BALANCE_ = _TOTAL_BORROWER_DEBT_BALANCE_.sub(amount); _TOTAL_DEBT_AVAILABLE_TO_WITHDRAW_ = _TOTAL_DEBT_AVAILABLE_TO_WITHDRAW_.add(amount); // Transfer token from the sender. STAKED_TOKEN.safeTransferFrom(msg.sender, address(this), amount); emit RepaidDebt(borrower, msg.sender, amount, newDebtBalance); } /** * @notice Get the max additional amount that the borrower can borrow. * * @return The max additional amount that the borrower can borrow right now. */ function getBorrowableAmount( address borrower ) external view returns (uint256) { if (_BORROWER_RESTRICTIONS_[borrower]) { return 0; } // Get the remaining unused allocation for the borrower. uint256 oldBorrowedBalance = _BORROWED_BALANCES_[borrower]; uint256 borrowerAllocatedBalance = _getAllocatedBalanceForNewBorrowing(borrower); if (borrowerAllocatedBalance <= oldBorrowedBalance) { return 0; } uint256 borrowerRemainingAllocatedBalance = borrowerAllocatedBalance.sub(oldBorrowedBalance); // Don't allow new borrowing to take out funds that are reserved for debt or inactive balances. // Typically, this will not be the limiting factor, but it can be. uint256 totalAvailableForBorrow = getContractBalanceAvailableToBorrow(); return Math.min(borrowerRemainingAllocatedBalance, totalAvailableForBorrow); } // ============ Public Functions ============ /** * @notice Get the funds currently available in the contract for borrowing. * * @return The amount of non-debt, non-inactive funds in the contract. */ function getContractBalanceAvailableToBorrow() public view returns (uint256) { uint256 availableStake = getContractBalanceAvailableToWithdraw(); uint256 inactiveBalance = getTotalInactiveBalanceCurrentEpoch(); // Note: The funds available to withdraw may be less than the inactive balance. if (availableStake <= inactiveBalance) { return 0; } return availableStake.sub(inactiveBalance); } } // SPDX-License-Identifier: Apache-2.0 pragma solidity 0.7.5; pragma abicoder v2; import { SafeERC20 } from '../../../dependencies/open-zeppelin/SafeERC20.sol'; import { SafeMath } from '../../../dependencies/open-zeppelin/SafeMath.sol'; import { IERC20 } from '../../../interfaces/IERC20.sol'; import { Math } from '../../../utils/Math.sol'; import { LS1Types } from '../lib/LS1Types.sol'; import { LS1BorrowerAllocations } from './LS1BorrowerAllocations.sol'; /** * @title LS1DebtAccounting * @author dYdX * * @dev Allows converting an overdue balance into "debt", which is accounted for separately from * the staked and borrowed balances. This allows the system to rebalance/restabilize itself in the * case where a borrower fails to return borrowed funds on time. * * The shortfall debt calculation is as follows: * * - Let A be the total active balance. * - Let B be the total borrowed balance. * - Let X be the total inactive balance. * - Then, a shortfall occurs if at any point B > A. * - The shortfall debt amount is `D = B - A` * - The borrowed balances are decreased by `B_new = B - D` * - The inactive balances are decreased by `X_new = X - D` * - The shortfall index is recorded as `Y = X_new / X` * - The borrower and staker debt balances are increased by `D` * * Note that `A + X >= B` (The active and inactive balances are at least the borrowed balance.) * This implies that `X >= D` (The inactive balance is always at least the shortfall debt.) */ abstract contract LS1DebtAccounting is LS1BorrowerAllocations { using SafeERC20 for IERC20; using SafeMath for uint256; using Math for uint256; // ============ Events ============ event ConvertedInactiveBalancesToDebt( uint256 shortfallAmount, uint256 shortfallIndex, uint256 newInactiveBalance ); event DebtMarked( address indexed borrower, uint256 amount, uint256 newBorrowedBalance, uint256 newDebtBalance ); // ============ External Functions ============ /** * @notice Restrict a borrower from borrowing. The borrower must have exceeded their borrowing * allocation. Can be called by anyone. * * Unlike markDebt(), this function can be called even if the contract in TOTAL is not insolvent. */ function restrictBorrower( address borrower ) external nonReentrant { require( isBorrowerOverdue(borrower), 'LS1DebtAccounting: Borrower not overdue' ); _setBorrowingRestriction(borrower, true); } /** * @notice Convert the shortfall amount between the active and borrowed balances into “debt.” * * The function determines the size of the debt, and then does the following: * - Assign the debt to borrowers, taking the same amount out of their borrowed balance. * - Impose borrow restrictions on borrowers to whom the debt was assigned. * - Socialize the loss pro-rata across inactive balances. Each balance with a loss receives * an equal amount of debt balance that can be withdrawn as debts are repaid. * * @param borrowers A list of borrowers who are responsible for the full shortfall amount. * * @return The shortfall debt amount. */ function markDebt( address[] calldata borrowers ) external nonReentrant returns (uint256) { // The debt is equal to the difference between the total active and total borrowed balances. uint256 totalActiveCurrent = getTotalActiveBalanceCurrentEpoch(); uint256 totalBorrowed = _TOTAL_BORROWED_BALANCE_; require(totalBorrowed > totalActiveCurrent, 'LS1DebtAccounting: No shortfall'); uint256 shortfallDebt = totalBorrowed.sub(totalActiveCurrent); // Attribute debt to borrowers. _attributeDebtToBorrowers(shortfallDebt, totalActiveCurrent, borrowers); // Apply the debt to inactive balances, moving the same amount into users debt balances. _convertInactiveBalanceToDebt(shortfallDebt); return shortfallDebt; } // ============ Public Functions ============ /** * @notice Whether the borrower is overdue on a payment, and is currently subject to having their * borrowing rights revoked. * * @param borrower The borrower to check. */ function isBorrowerOverdue( address borrower ) public view returns (bool) { uint256 allocatedBalance = getAllocatedBalanceCurrentEpoch(borrower); uint256 borrowedBalance = _BORROWED_BALANCES_[borrower]; return borrowedBalance > allocatedBalance; } // ============ Private Functions ============ /** * @dev Helper function to partially or fully convert inactive balances to debt. * * @param shortfallDebt The shortfall amount: borrowed balances less active balances. */ function _convertInactiveBalanceToDebt( uint256 shortfallDebt ) private { // Get the total inactive balance. uint256 oldInactiveBalance = getTotalInactiveBalanceCurrentEpoch(); // Calculate the index factor for the shortfall. uint256 newInactiveBalance = 0; uint256 shortfallIndex = 0; if (oldInactiveBalance > shortfallDebt) { newInactiveBalance = oldInactiveBalance.sub(shortfallDebt); shortfallIndex = SHORTFALL_INDEX_BASE.mul(newInactiveBalance).div(oldInactiveBalance); } // Get the shortfall amount applied to inactive balances. uint256 shortfallAmount = oldInactiveBalance.sub(newInactiveBalance); // Apply the loss. This moves the debt from stakers' inactive balances to their debt balances. _applyShortfall(shortfallAmount, shortfallIndex); emit ConvertedInactiveBalancesToDebt(shortfallAmount, shortfallIndex, newInactiveBalance); } /** * @dev Helper function to attribute debt to borrowers, adding it to their debt balances. * * @param shortfallDebt The shortfall amount: borrowed balances less active balances. * @param totalActiveCurrent The total active balance for the current epoch. * @param borrowers A list of borrowers responsible for the full shortfall amount. */ function _attributeDebtToBorrowers( uint256 shortfallDebt, uint256 totalActiveCurrent, address[] calldata borrowers ) private { // Find borrowers to attribute the total debt amount to. The sum of all borrower shortfalls is // always at least equal to the overall shortfall, so it is always possible to specify a list // of borrowers whose excess borrows cover the full shortfall amount. // // Denominate values in “points” scaled by TOTAL_ALLOCATION to avoid rounding. uint256 debtToBeAttributedPoints = shortfallDebt.mul(TOTAL_ALLOCATION); uint256 shortfallDebtAfterRounding = 0; for (uint256 i = 0; i < borrowers.length; i++) { address borrower = borrowers[i]; uint256 borrowedBalanceTokenAmount = _BORROWED_BALANCES_[borrower]; uint256 borrowedBalancePoints = borrowedBalanceTokenAmount.mul(TOTAL_ALLOCATION); uint256 allocationPoints = getAllocationFractionCurrentEpoch(borrower); uint256 allocatedBalancePoints = totalActiveCurrent.mul(allocationPoints); // Skip this borrower if they have not exceeded their allocation. if (borrowedBalancePoints <= allocatedBalancePoints) { continue; } // Calculate the borrower's debt, and limit to the remaining amount to be allocated. uint256 borrowerDebtPoints = borrowedBalancePoints.sub(allocatedBalancePoints); borrowerDebtPoints = Math.min(borrowerDebtPoints, debtToBeAttributedPoints); // Move the debt from the borrowers' borrowed balance to the debt balance. Rounding may occur // when converting from “points” to tokens. We round up to ensure the final borrowed balance // is not greater than the allocated balance. uint256 borrowerDebtTokenAmount = borrowerDebtPoints.divRoundUp(TOTAL_ALLOCATION); uint256 newDebtBalance = _BORROWER_DEBT_BALANCES_[borrower].add(borrowerDebtTokenAmount); uint256 newBorrowedBalance = borrowedBalanceTokenAmount.sub(borrowerDebtTokenAmount); _BORROWER_DEBT_BALANCES_[borrower] = newDebtBalance; _BORROWED_BALANCES_[borrower] = newBorrowedBalance; emit DebtMarked(borrower, borrowerDebtTokenAmount, newBorrowedBalance, newDebtBalance); shortfallDebtAfterRounding = shortfallDebtAfterRounding.add(borrowerDebtTokenAmount); // Restrict the borrower from further borrowing. _setBorrowingRestriction(borrower, true); // Update the remaining amount to allocate. debtToBeAttributedPoints = debtToBeAttributedPoints.sub(borrowerDebtPoints); // Exit early if all debt was allocated. if (debtToBeAttributedPoints == 0) { break; } } // Require the borrowers to cover the full debt amount. This should always be possible. require( debtToBeAttributedPoints == 0, 'LS1DebtAccounting: Borrowers do not cover the shortfall' ); // Move the debt from the total borrowed balance to the total debt balance. _TOTAL_BORROWED_BALANCE_ = _TOTAL_BORROWED_BALANCE_.sub(shortfallDebtAfterRounding); _TOTAL_BORROWER_DEBT_BALANCE_ = _TOTAL_BORROWER_DEBT_BALANCE_.add(shortfallDebtAfterRounding); } } // SPDX-License-Identifier: Apache-2.0 pragma solidity 0.7.5; pragma abicoder v2; import { SafeMath } from '../../../dependencies/open-zeppelin/SafeMath.sol'; import { IERC20Detailed } from '../../../interfaces/IERC20Detailed.sol'; import { LS1Types } from '../lib/LS1Types.sol'; import { LS1StakedBalances } from './LS1StakedBalances.sol'; /** * @title LS1ERC20 * @author dYdX * * @dev ERC20 interface for staked tokens. Allows a user with an active stake to transfer their * staked tokens to another user, even if they would otherwise be restricted from withdrawing. */ abstract contract LS1ERC20 is LS1StakedBalances, IERC20Detailed { using SafeMath for uint256; // ============ External Functions ============ function name() external pure override returns (string memory) { return 'dYdX Staked USDC'; } function symbol() external pure override returns (string memory) { return 'stkUSDC'; } function decimals() external pure override returns (uint8) { return 6; } /** * @notice Get the total supply of `STAKED_TOKEN` staked to the contract. * This value is calculated from adding the active + inactive balances of * this current epoch. * * @return The total staked balance of this contract. */ function totalSupply() external view override returns (uint256) { return getTotalActiveBalanceCurrentEpoch() + getTotalInactiveBalanceCurrentEpoch(); } /** * @notice Get the current balance of `STAKED_TOKEN` the user has staked to the contract. * This value includes the users active + inactive balances, but note that only * their active balance in the next epoch is transferable. * * @param account The account to get the balance of. * * @return The user's balance. */ function balanceOf( address account ) external view override returns (uint256) { return getActiveBalanceCurrentEpoch(account) + getInactiveBalanceCurrentEpoch(account); } function transfer( address recipient, uint256 amount ) external override nonReentrant returns (bool) { _transfer(msg.sender, recipient, amount); return true; } function allowance( address owner, address spender ) external view override returns (uint256) { return _ALLOWANCES_[owner][spender]; } function approve( address spender, uint256 amount ) external override returns (bool) { _approve(msg.sender, spender, amount); return true; } function transferFrom( address sender, address recipient, uint256 amount ) external override nonReentrant returns (bool) { _transfer(sender, recipient, amount); _approve( sender, msg.sender, _ALLOWANCES_[sender][msg.sender].sub(amount, 'LS1ERC20: transfer amount exceeds allowance') ); return true; } function increaseAllowance( address spender, uint256 addedValue ) external returns (bool) { _approve(msg.sender, spender, _ALLOWANCES_[msg.sender][spender].add(addedValue)); return true; } function decreaseAllowance( address spender, uint256 subtractedValue ) external returns (bool) { _approve( msg.sender, spender, _ALLOWANCES_[msg.sender][spender].sub( subtractedValue, 'LS1ERC20: Decreased allowance below zero' ) ); return true; } // ============ Internal Functions ============ function _transfer( address sender, address recipient, uint256 amount ) internal { require(sender != address(0), 'LS1ERC20: Transfer from address(0)'); require(recipient != address(0), 'LS1ERC20: Transfer to address(0)'); require( getTransferableBalance(sender) >= amount, 'LS1ERC20: Transfer exceeds next epoch active balance' ); _transferCurrentAndNextActiveBalance(sender, recipient, amount); emit Transfer(sender, recipient, amount); } function _approve( address owner, address spender, uint256 amount ) internal { require(owner != address(0), 'LS1ERC20: Approve from address(0)'); require(spender != address(0), 'LS1ERC20: Approve to address(0)'); _ALLOWANCES_[owner][spender] = amount; emit Approval(owner, spender, amount); } } // SPDX-License-Identifier: Apache-2.0 pragma solidity 0.7.5; pragma abicoder v2; import { SafeMath } from '../../../dependencies/open-zeppelin/SafeMath.sol'; import { IERC20 } from '../../../interfaces/IERC20.sol'; import { LS1Types } from '../lib/LS1Types.sol'; import { SafeCast } from '../lib/SafeCast.sol'; import { LS1StakedBalances } from './LS1StakedBalances.sol'; /** * @title LS1Failsafe * @author dYdX * * @dev Functions for recovering from very unlikely edge cases. */ abstract contract LS1Failsafe is LS1StakedBalances { using SafeCast for uint256; using SafeMath for uint256; /** * @notice Settle the sender's inactive balance up to the specified epoch. This allows the * balance to be settled while putting an upper bound on the gas expenditure per function call. * This is unlikely to be needed in practice. * * @param maxEpoch The epoch to settle the sender's inactive balance up to. */ function failsafeSettleUserInactiveBalanceToEpoch( uint256 maxEpoch ) external nonReentrant { address staker = msg.sender; _failsafeSettleUserInactiveBalance(staker, maxEpoch); } /** * @notice Sets the sender's inactive balance to zero. This allows for recovery from a situation * where the gas cost to settle the balance is higher than the value of the balance itself. * We provide this function as an alternative to settlement, since the gas cost for settling an * inactive balance is unbounded (except in that it may grow at most linearly with the number of * epochs that have passed). */ function failsafeDeleteUserInactiveBalance() external nonReentrant { address staker = msg.sender; _failsafeDeleteUserInactiveBalance(staker); } } // SPDX-License-Identifier: Apache-2.0 pragma solidity 0.7.5; pragma abicoder v2; import { SafeMath } from '../../../dependencies/open-zeppelin/SafeMath.sol'; import { LS1Staking } from './LS1Staking.sol'; /** * @title LS1Operators * @author dYdX * * @dev Actions which may be called by authorized operators, nominated by the contract owner. * * There are three types of operators. These should be smart contracts, which can be used to * provide additional functionality to users: * * STAKE_OPERATOR_ROLE: * * This operator is allowed to request withdrawals and withdraw funds on behalf of stakers. This * role could be used by a smart contract to provide a staking interface with additional * features, for example, optional lock-up periods that pay out additional rewards (from a * separate rewards pool). * * CLAIM_OPERATOR_ROLE: * * This operator is allowed to claim rewards on behalf of stakers. This role could be used by a * smart contract to provide an interface for claiming rewards from multiple incentive programs * at once. * * DEBT_OPERATOR_ROLE: * * This operator is allowed to decrease staker and borrower debt balances. Typically, each change * to a staker debt balance should be offset by a corresponding change in a borrower debt * balance, but this is not strictly required. This role could used by a smart contract to * tokenize debt balances or to provide a pro-rata distribution to debt holders, for example. */ abstract contract LS1Operators is LS1Staking { using SafeMath for uint256; // ============ Events ============ event OperatorStakedFor( address indexed staker, uint256 amount, address operator ); event OperatorWithdrawalRequestedFor( address indexed staker, uint256 amount, address operator ); event OperatorWithdrewStakeFor( address indexed staker, address recipient, uint256 amount, address operator ); event OperatorClaimedRewardsFor( address indexed staker, address recipient, uint256 claimedRewards, address operator ); event OperatorDecreasedStakerDebt( address indexed staker, uint256 amount, uint256 newDebtBalance, address operator ); event OperatorDecreasedBorrowerDebt( address indexed borrower, uint256 amount, uint256 newDebtBalance, address operator ); // ============ External Functions ============ /** * @notice Request a withdrawal on behalf of a staker. * * Reverts if we are currently in the blackout window. * * @param staker The staker whose stake to request a withdrawal for. * @param amount The amount to move from the active to the inactive balance. */ function requestWithdrawalFor( address staker, uint256 amount ) external onlyRole(STAKE_OPERATOR_ROLE) nonReentrant { _requestWithdrawal(staker, amount); emit OperatorWithdrawalRequestedFor(staker, amount, msg.sender); } /** * @notice Withdraw a staker's stake, and send to the specified recipient. * * @param staker The staker whose stake to withdraw. * @param recipient The address that should receive the funds. * @param amount The amount to withdraw from the staker's inactive balance. */ function withdrawStakeFor( address staker, address recipient, uint256 amount ) external onlyRole(STAKE_OPERATOR_ROLE) nonReentrant { _withdrawStake(staker, recipient, amount); emit OperatorWithdrewStakeFor(staker, recipient, amount, msg.sender); } /** * @notice Claim rewards on behalf of a staker, and send them to the specified recipient. * * @param staker The staker whose rewards to claim. * @param recipient The address that should receive the funds. * * @return The number of rewards tokens claimed. */ function claimRewardsFor( address staker, address recipient ) external onlyRole(CLAIM_OPERATOR_ROLE) nonReentrant returns (uint256) { uint256 rewards = _settleAndClaimRewards(staker, recipient); // Emits an event internally. emit OperatorClaimedRewardsFor(staker, recipient, rewards, msg.sender); return rewards; } /** * @notice Decreased the balance recording debt owed to a staker. * * @param staker The staker whose balance to decrease. * @param amount The amount to decrease the balance by. * * @return The new debt balance. */ function decreaseStakerDebt( address staker, uint256 amount ) external onlyRole(DEBT_OPERATOR_ROLE) nonReentrant returns (uint256) { uint256 oldDebtBalance = _settleStakerDebtBalance(staker); uint256 newDebtBalance = oldDebtBalance.sub(amount); _STAKER_DEBT_BALANCES_[staker] = newDebtBalance; emit OperatorDecreasedStakerDebt(staker, amount, newDebtBalance, msg.sender); return newDebtBalance; } /** * @notice Decreased the balance recording debt owed by a borrower. * * @param borrower The borrower whose balance to decrease. * @param amount The amount to decrease the balance by. * * @return The new debt balance. */ function decreaseBorrowerDebt( address borrower, uint256 amount ) external onlyRole(DEBT_OPERATOR_ROLE) nonReentrant returns (uint256) { uint256 newDebtBalance = _BORROWER_DEBT_BALANCES_[borrower].sub(amount); _BORROWER_DEBT_BALANCES_[borrower] = newDebtBalance; _TOTAL_BORROWER_DEBT_BALANCE_ = _TOTAL_BORROWER_DEBT_BALANCE_.sub(amount); emit OperatorDecreasedBorrowerDebt(borrower, amount, newDebtBalance, msg.sender); return newDebtBalance; } } // SPDX-License-Identifier: Apache-2.0 pragma solidity 0.7.5; pragma abicoder v2; /** * @title SafeCast * @author dYdX * * @dev Methods for downcasting unsigned integers, reverting on overflow. */ library SafeCast { /** * @dev Downcast to a uint16, reverting on overflow. */ function toUint16( uint256 a ) internal pure returns (uint16) { uint16 b = uint16(a); require(uint256(b) == a, 'SafeCast: toUint16 overflow'); return b; } /** * @dev Downcast to a uint32, reverting on overflow. */ function toUint32( uint256 a ) internal pure returns (uint32) { uint32 b = uint32(a); require(uint256(b) == a, 'SafeCast: toUint32 overflow'); return b; } /** * @dev Downcast to a uint112, reverting on overflow. */ function toUint112( uint256 a ) internal pure returns (uint112) { uint112 b = uint112(a); require(uint256(b) == a, 'SafeCast: toUint112 overflow'); return b; } /** * @dev Downcast to a uint120, reverting on overflow. */ function toUint120( uint256 a ) internal pure returns (uint120) { uint120 b = uint120(a); require(uint256(b) == a, 'SafeCast: toUint120 overflow'); return b; } /** * @dev Downcast to a uint128, reverting on overflow. */ function toUint128( uint256 a ) internal pure returns (uint128) { uint128 b = uint128(a); require(uint256(b) == a, 'SafeCast: toUint128 overflow'); return b; } /** * @dev Downcast to a uint224, reverting on overflow. */ function toUint224( uint256 a ) internal pure returns (uint224) { uint224 b = uint224(a); require(uint256(b) == a, 'SafeCast: toUint224 overflow'); return b; } } // SPDX-License-Identifier: MIT pragma solidity 0.7.5; import { IERC20 } from '../../interfaces/IERC20.sol'; import { SafeMath } from './SafeMath.sol'; import { Address } from './Address.sol'; /** * @title SafeERC20 * @dev From https://github.com/OpenZeppelin/openzeppelin-contracts * 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)); } function safeApprove( IERC20 token, address spender, uint256 value ) internal { require( (value == 0) || (token.allowance(address(this), spender) == 0), 'SafeERC20: approve from non-zero to non-zero allowance' ); callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function callOptionalReturn(IERC20 token, bytes memory data) private { require(address(token).isContract(), 'SafeERC20: call to non-contract'); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = address(token).call(data); require(success, 'SafeERC20: low-level call failed'); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), 'SafeERC20: ERC20 operation did not succeed'); } } } // SPDX-License-Identifier: Apache-2.0 pragma solidity 0.7.5; pragma abicoder v2; import { SafeERC20 } from '../../../dependencies/open-zeppelin/SafeERC20.sol'; import { SafeMath } from '../../../dependencies/open-zeppelin/SafeMath.sol'; import { IERC20 } from '../../../interfaces/IERC20.sol'; import { Math } from '../../../utils/Math.sol'; import { LS1Types } from '../lib/LS1Types.sol'; import { SafeCast } from '../lib/SafeCast.sol'; import { LS1StakedBalances } from './LS1StakedBalances.sol'; /** * @title LS1BorrowerAllocations * @author dYdX * * @dev Gives a set of addresses permission to withdraw staked funds. * * The amount that can be withdrawn depends on a borrower's allocation percentage and the total * available funds. Both the allocated percentage and total available funds can change, at * predefined times specified by LS1EpochSchedule. * * If a borrower's borrowed balance is greater than their allocation at the start of the next epoch * then they are expected and trusted to return the difference before the start of that epoch. */ abstract contract LS1BorrowerAllocations is LS1StakedBalances { using SafeCast for uint256; using SafeERC20 for IERC20; using SafeMath for uint256; // ============ Constants ============ /// @notice The total units to be allocated. uint256 public constant TOTAL_ALLOCATION = 1e4; // ============ Events ============ event ScheduledBorrowerAllocationChange( address indexed borrower, uint256 oldAllocation, uint256 newAllocation, uint256 epochNumber ); event BorrowingRestrictionChanged( address indexed borrower, bool isBorrowingRestricted ); // ============ Initializer ============ function __LS1BorrowerAllocations_init() internal { _BORROWER_ALLOCATIONS_[address(0)] = LS1Types.StoredAllocation({ currentEpoch: 0, currentEpochAllocation: TOTAL_ALLOCATION.toUint120(), nextEpochAllocation: TOTAL_ALLOCATION.toUint120() }); } // ============ Public Functions ============ /** * @notice Get the borrower allocation for the current epoch. * * @param borrower The borrower to get the allocation for. * * @return The borrower's current allocation in hundreds of a percent. */ function getAllocationFractionCurrentEpoch( address borrower ) public view returns (uint256) { return uint256(_loadBorrowerAllocation(borrower).currentEpochAllocation); } /** * @notice Get the borrower allocation for the next epoch. * * @param borrower The borrower to get the allocation for. * * @return The borrower's next allocation in hundreds of a percent. */ function getAllocationFractionNextEpoch( address borrower ) public view returns (uint256) { return uint256(_loadBorrowerAllocation(borrower).nextEpochAllocation); } /** * @notice Get the allocated borrowable token balance of a borrower for the current epoch. * * This is the amount which a borrower can be penalized for exceeding. * * @param borrower The borrower to get the allocation for. * * @return The token amount allocated to the borrower for the current epoch. */ function getAllocatedBalanceCurrentEpoch( address borrower ) public view returns (uint256) { uint256 allocation = getAllocationFractionCurrentEpoch(borrower); uint256 availableTokens = getTotalActiveBalanceCurrentEpoch(); return availableTokens.mul(allocation).div(TOTAL_ALLOCATION); } /** * @notice Preview the allocated balance of a borrower for the next epoch. * * @param borrower The borrower to get the allocation for. * * @return The anticipated token amount allocated to the borrower for the next epoch. */ function getAllocatedBalanceNextEpoch( address borrower ) public view returns (uint256) { uint256 allocation = getAllocationFractionNextEpoch(borrower); uint256 availableTokens = getTotalActiveBalanceNextEpoch(); return availableTokens.mul(allocation).div(TOTAL_ALLOCATION); } // ============ Internal Functions ============ /** * @dev Change the allocations of certain borrowers. */ function _setBorrowerAllocations( address[] calldata borrowers, uint256[] calldata newAllocations ) internal { // These must net out so that the total allocation is unchanged. uint256 oldAllocationSum = 0; uint256 newAllocationSum = 0; for (uint256 i = 0; i < borrowers.length; i++) { address borrower = borrowers[i]; uint256 newAllocation = newAllocations[i]; // Get the old allocation. LS1Types.StoredAllocation memory allocationStruct = _loadBorrowerAllocation(borrower); uint256 oldAllocation = uint256(allocationStruct.currentEpochAllocation); // Update the borrower's next allocation. allocationStruct.nextEpochAllocation = newAllocation.toUint120(); // If epoch zero hasn't started, update current allocation as well. uint256 epochNumber = 0; if (hasEpochZeroStarted()) { epochNumber = uint256(allocationStruct.currentEpoch).add(1); } else { allocationStruct.currentEpochAllocation = newAllocation.toUint120(); } // Commit the new allocation. _BORROWER_ALLOCATIONS_[borrower] = allocationStruct; emit ScheduledBorrowerAllocationChange(borrower, oldAllocation, newAllocation, epochNumber); // Record totals. oldAllocationSum = oldAllocationSum.add(oldAllocation); newAllocationSum = newAllocationSum.add(newAllocation); } // Require the total allocated units to be unchanged. require( oldAllocationSum == newAllocationSum, 'LS1BorrowerAllocations: Invalid' ); } /** * @dev Restrict a borrower from further borrowing. */ function _setBorrowingRestriction( address borrower, bool isBorrowingRestricted ) internal { bool oldIsBorrowingRestricted = _BORROWER_RESTRICTIONS_[borrower]; if (oldIsBorrowingRestricted != isBorrowingRestricted) { _BORROWER_RESTRICTIONS_[borrower] = isBorrowingRestricted; emit BorrowingRestrictionChanged(borrower, isBorrowingRestricted); } } /** * @dev Get the allocated balance that the borrower can make use of for new borrowing. * * @return The amount that the borrower can borrow up to. */ function _getAllocatedBalanceForNewBorrowing( address borrower ) internal view returns (uint256) { // Use the smaller of the current and next allocation fractions, since if a borrower's // allocation was just decreased, we should take that into account in limiting new borrows. uint256 currentAllocation = getAllocationFractionCurrentEpoch(borrower); uint256 nextAllocation = getAllocationFractionNextEpoch(borrower); uint256 allocation = Math.min(currentAllocation, nextAllocation); // If we are in the blackout window, use the next active balance. Otherwise, use current. // Note that the next active balance is never greater than the current active balance. uint256 availableTokens; if (inBlackoutWindow()) { availableTokens = getTotalActiveBalanceNextEpoch(); } else { availableTokens = getTotalActiveBalanceCurrentEpoch(); } return availableTokens.mul(allocation).div(TOTAL_ALLOCATION); } // ============ Private Functions ============ function _loadBorrowerAllocation( address borrower ) private view returns (LS1Types.StoredAllocation memory) { LS1Types.StoredAllocation memory allocation = _BORROWER_ALLOCATIONS_[borrower]; // Ignore rollover logic before epoch zero. if (hasEpochZeroStarted()) { uint256 currentEpoch = getCurrentEpoch(); if (currentEpoch > uint256(allocation.currentEpoch)) { // Roll the allocation forward. allocation.currentEpoch = currentEpoch.toUint16(); allocation.currentEpochAllocation = allocation.nextEpochAllocation; } } return allocation; } } // SPDX-License-Identifier: Apache-2.0 pragma solidity 0.7.5; pragma abicoder v2; import { SafeERC20 } from '../../../dependencies/open-zeppelin/SafeERC20.sol'; import { SafeMath } from '../../../dependencies/open-zeppelin/SafeMath.sol'; import { IERC20 } from '../../../interfaces/IERC20.sol'; import { Math } from '../../../utils/Math.sol'; import { LS1Types } from '../lib/LS1Types.sol'; import { LS1ERC20 } from './LS1ERC20.sol'; import { LS1StakedBalances } from './LS1StakedBalances.sol'; /** * @title LS1Staking * @author dYdX * * @dev External functions for stakers. See LS1StakedBalances for details on staker accounting. */ abstract contract LS1Staking is LS1StakedBalances, LS1ERC20 { using SafeERC20 for IERC20; using SafeMath for uint256; // ============ Events ============ event Staked( address indexed staker, address spender, uint256 amount ); event WithdrawalRequested( address indexed staker, uint256 amount ); event WithdrewStake( address indexed staker, address recipient, uint256 amount ); event WithdrewDebt( address indexed staker, address recipient, uint256 amount, uint256 newDebtBalance ); // ============ Constants ============ IERC20 public immutable STAKED_TOKEN; // ============ Constructor ============ constructor( IERC20 stakedToken, IERC20 rewardsToken, address rewardsTreasury, uint256 distributionStart, uint256 distributionEnd ) LS1StakedBalances(rewardsToken, rewardsTreasury, distributionStart, distributionEnd) { STAKED_TOKEN = stakedToken; } // ============ External Functions ============ /** * @notice Deposit and stake funds. These funds are active and start earning rewards immediately. * * @param amount The amount to stake. */ function stake( uint256 amount ) external nonReentrant { _stake(msg.sender, amount); } /** * @notice Deposit and stake on behalf of another address. * * @param staker The staker who will receive the stake. * @param amount The amount to stake. */ function stakeFor( address staker, uint256 amount ) external nonReentrant { _stake(staker, amount); } /** * @notice Request to withdraw funds. Starting in the next epoch, the funds will be “inactive” * and available for withdrawal. Inactive funds do not earn rewards. * * Reverts if we are currently in the blackout window. * * @param amount The amount to move from the active to the inactive balance. */ function requestWithdrawal( uint256 amount ) external nonReentrant { _requestWithdrawal(msg.sender, amount); } /** * @notice Withdraw the sender's inactive funds, and send to the specified recipient. * * @param recipient The address that should receive the funds. * @param amount The amount to withdraw from the sender's inactive balance. */ function withdrawStake( address recipient, uint256 amount ) external nonReentrant { _withdrawStake(msg.sender, recipient, amount); } /** * @notice Withdraw the max available inactive funds, and send to the specified recipient. * * This is less gas-efficient than querying the max via eth_call and calling withdrawStake(). * * @param recipient The address that should receive the funds. * * @return The withdrawn amount. */ function withdrawMaxStake( address recipient ) external nonReentrant returns (uint256) { uint256 amount = getStakeAvailableToWithdraw(msg.sender); _withdrawStake(msg.sender, recipient, amount); return amount; } /** * @notice Withdraw a debt amount owed to the sender, and send to the specified recipient. * * @param recipient The address that should receive the funds. * @param amount The token amount to withdraw from the sender's debt balance. */ function withdrawDebt( address recipient, uint256 amount ) external nonReentrant { _withdrawDebt(msg.sender, recipient, amount); } /** * @notice Withdraw the max available debt amount. * * This is less gas-efficient than querying the max via eth_call and calling withdrawDebt(). * * @param recipient The address that should receive the funds. * * @return The withdrawn amount. */ function withdrawMaxDebt( address recipient ) external nonReentrant returns (uint256) { uint256 amount = getDebtAvailableToWithdraw(msg.sender); _withdrawDebt(msg.sender, recipient, amount); return amount; } /** * @notice Settle and claim all rewards, and send them to the specified recipient. * * Call this function with eth_call to query the claimable rewards balance. * * @param recipient The address that should receive the funds. * * @return The number of rewards tokens claimed. */ function claimRewards( address recipient ) external nonReentrant returns (uint256) { return _settleAndClaimRewards(msg.sender, recipient); // Emits an event internally. } // ============ Public Functions ============ /** * @notice Get the amount of stake available to withdraw taking into account the contract balance. * * @param staker The address whose balance to check. * * @return The staker's stake amount that is inactive and available to withdraw. */ function getStakeAvailableToWithdraw( address staker ) public view returns (uint256) { // Note that the next epoch inactive balance is always at least that of the current epoch. uint256 stakerBalance = getInactiveBalanceCurrentEpoch(staker); uint256 totalStakeAvailable = getContractBalanceAvailableToWithdraw(); return Math.min(stakerBalance, totalStakeAvailable); } /** * @notice Get the funds currently available in the contract for staker withdrawals. * * @return The amount of non-debt funds in the contract. */ function getContractBalanceAvailableToWithdraw() public view returns (uint256) { uint256 contractBalance = STAKED_TOKEN.balanceOf(address(this)); uint256 availableDebtBalance = _TOTAL_DEBT_AVAILABLE_TO_WITHDRAW_; return contractBalance.sub(availableDebtBalance); // Should never underflow. } /** * @notice Get the amount of debt available to withdraw. * * @param staker The address whose balance to check. * * @return The debt amount that can be withdrawn. */ function getDebtAvailableToWithdraw( address staker ) public view returns (uint256) { // Note that `totalDebtAvailable` should never be less than the contract token balance. uint256 stakerDebtBalance = getStakerDebtBalance(staker); uint256 totalDebtAvailable = _TOTAL_DEBT_AVAILABLE_TO_WITHDRAW_; return Math.min(stakerDebtBalance, totalDebtAvailable); } // ============ Internal Functions ============ function _stake( address staker, uint256 amount ) internal { // Increase current and next active balance. _increaseCurrentAndNextActiveBalance(staker, amount); // Transfer token from the sender. STAKED_TOKEN.safeTransferFrom(msg.sender, address(this), amount); emit Staked(staker, msg.sender, amount); emit Transfer(address(0), msg.sender, amount); } function _requestWithdrawal( address staker, uint256 amount ) internal { require( !inBlackoutWindow(), 'LS1Staking: Withdraw requests restricted in the blackout window' ); // Get the staker's requestable amount and revert if there is not enough to request withdrawal. uint256 requestableBalance = getActiveBalanceNextEpoch(staker); require( amount <= requestableBalance, 'LS1Staking: Withdraw request exceeds next active balance' ); // Move amount from active to inactive in the next epoch. _moveNextBalanceActiveToInactive(staker, amount); emit WithdrawalRequested(staker, amount); } function _withdrawStake( address staker, address recipient, uint256 amount ) internal { // Get contract available amount and revert if there is not enough to withdraw. uint256 totalStakeAvailable = getContractBalanceAvailableToWithdraw(); require( amount <= totalStakeAvailable, 'LS1Staking: Withdraw exceeds amount available in the contract' ); // Get staker withdrawable balance and revert if there is not enough to withdraw. uint256 withdrawableBalance = getInactiveBalanceCurrentEpoch(staker); require( amount <= withdrawableBalance, 'LS1Staking: Withdraw exceeds inactive balance' ); // Decrease the staker's current and next inactive balance. Reverts if balance is insufficient. _decreaseCurrentAndNextInactiveBalance(staker, amount); // Transfer token to the recipient. STAKED_TOKEN.safeTransfer(recipient, amount); emit Transfer(msg.sender, address(0), amount); emit WithdrewStake(staker, recipient, amount); } // ============ Private Functions ============ function _withdrawDebt( address staker, address recipient, uint256 amount ) private { // Get old amounts and revert if there is not enough to withdraw. uint256 oldDebtBalance = _settleStakerDebtBalance(staker); require( amount <= oldDebtBalance, 'LS1Staking: Withdraw debt exceeds debt owed' ); uint256 oldDebtAvailable = _TOTAL_DEBT_AVAILABLE_TO_WITHDRAW_; require( amount <= oldDebtAvailable, 'LS1Staking: Withdraw debt exceeds amount available' ); // Caculate updated amounts and update storage. uint256 newDebtBalance = oldDebtBalance.sub(amount); uint256 newDebtAvailable = oldDebtAvailable.sub(amount); _STAKER_DEBT_BALANCES_[staker] = newDebtBalance; _TOTAL_DEBT_AVAILABLE_TO_WITHDRAW_ = newDebtAvailable; // Transfer token to the recipient. STAKED_TOKEN.safeTransfer(recipient, amount); emit WithdrewDebt(staker, recipient, amount, newDebtBalance); } } // SPDX-License-Identifier: MIT pragma solidity 0.7.5; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // According to EIP-1052, 0x0 is the value returned for not-yet created accounts // and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned // for accounts without code, i.e. `keccak256('')` bytes32 codehash; bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; // solhint-disable-next-line no-inline-assembly assembly { codehash := extcodehash(account) } return (codehash != accountHash && codehash != 0x0); } /** * @dev 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'); } } // SPDX-License-Identifier: Apache-2.0 pragma solidity 0.7.5; pragma abicoder v2; import { SafeMath } from '../../../dependencies/open-zeppelin/SafeMath.sol'; import { IERC20 } from '../../../interfaces/IERC20.sol'; import { LS1Types } from '../lib/LS1Types.sol'; import { SafeCast } from '../lib/SafeCast.sol'; import { LS1Rewards } from './LS1Rewards.sol'; /** * @title LS1StakedBalances * @author dYdX * * @dev Accounting of staked balances. * * NOTE: Internal functions may revert if epoch zero has not started. * * STAKED BALANCE ACCOUNTING: * * A staked balance is in one of two states: * - active: Available for borrowing; earning staking rewards; cannot be withdrawn by staker. * - inactive: Unavailable for borrowing; does not earn rewards; can be withdrawn by the staker. * * A staker may have a combination of active and inactive balances. The following operations * affect staked balances as follows: * - deposit: Increase active balance. * - request withdrawal: At the end of the current epoch, move some active funds to inactive. * - withdraw: Decrease inactive balance. * - transfer: Move some active funds to another staker. * * To encode the fact that a balance may be scheduled to change at the end of a certain epoch, we * store each balance as a struct of three fields: currentEpoch, currentEpochBalance, and * nextEpochBalance. Also, inactive user balances make use of the shortfallCounter field as * described below. * * INACTIVE BALANCE ACCOUNTING: * * Inactive funds may be subject to pro-rata socialized losses in the event of a shortfall where * a borrower is late to pay back funds that have been requested for withdrawal. We track losses * via indexes. Each index represents the fraction of inactive funds that were converted into * debt during a given shortfall event. Each staker inactive balance stores a cached shortfall * counter, representing the number of shortfalls that occurred in the past relative to when the * balance was last updated. * * Any losses incurred by an inactive balance translate into an equal credit to that staker's * debt balance. See LS1DebtAccounting for more info about how the index is calculated. * * REWARDS ACCOUNTING: * * Active funds earn rewards for the period of time that they remain active. This means, after * requesting a withdrawal of some funds, those funds will continue to earn rewards until the end * of the epoch. For example: * * epoch: n n + 1 n + 2 n + 3 * | | | | * +----------+----------+----------+-----... * ^ t_0: User makes a deposit. * ^ t_1: User requests a withdrawal of all funds. * ^ t_2: The funds change state from active to inactive. * * In the above scenario, the user would earn rewards for the period from t_0 to t_2, varying * with the total staked balance in that period. If the user only request a withdrawal for a part * of their balance, then the remaining balance would continue earning rewards beyond t_2. * * User rewards must be settled via LS1Rewards any time a user's active balance changes. Special * attention is paid to the the epoch boundaries, where funds may have transitioned from active * to inactive. * * SETTLEMENT DETAILS: * * Internally, this module uses the following types of operations on stored balances: * - Load: Loads a balance, while applying settlement logic internally to get the * up-to-date result. Returns settlement results without updating state. * - Store: Stores a balance. * - Load-for-update: Performs a load and applies updates as needed to rewards or debt balances. * Since this is state-changing, it must be followed by a store operation. * - Settle: Performs load-for-update and store operations. * * This module is responsible for maintaining the following invariants to ensure rewards are * calculated correctly: * - When an active balance is loaded for update, if a rollover occurs from one epoch to the * next, the rewards index must be settled up to the boundary at which the rollover occurs. * - Because the global rewards index is needed to update the user rewards index, the total * active balance must be settled before any staker balances are settled or loaded for update. * - A staker's balance must be settled before their rewards are settled. */ abstract contract LS1StakedBalances is LS1Rewards { using SafeCast for uint256; using SafeMath for uint256; // ============ Constants ============ uint256 internal constant SHORTFALL_INDEX_BASE = 1e36; // ============ Events ============ event ReceivedDebt( address indexed staker, uint256 amount, uint256 newDebtBalance ); // ============ Constructor ============ constructor( IERC20 rewardsToken, address rewardsTreasury, uint256 distributionStart, uint256 distributionEnd ) LS1Rewards(rewardsToken, rewardsTreasury, distributionStart, distributionEnd) {} // ============ Public Functions ============ /** * @notice Get the current active balance of a staker. */ function getActiveBalanceCurrentEpoch( address staker ) public view returns (uint256) { if (!hasEpochZeroStarted()) { return 0; } (LS1Types.StoredBalance memory balance, , , ) = _loadActiveBalance(_ACTIVE_BALANCES_[staker]); return uint256(balance.currentEpochBalance); } /** * @notice Get the next epoch active balance of a staker. */ function getActiveBalanceNextEpoch( address staker ) public view returns (uint256) { if (!hasEpochZeroStarted()) { return 0; } (LS1Types.StoredBalance memory balance, , , ) = _loadActiveBalance(_ACTIVE_BALANCES_[staker]); return uint256(balance.nextEpochBalance); } /** * @notice Get the current total active balance. */ function getTotalActiveBalanceCurrentEpoch() public view returns (uint256) { if (!hasEpochZeroStarted()) { return 0; } (LS1Types.StoredBalance memory balance, , , ) = _loadActiveBalance(_TOTAL_ACTIVE_BALANCE_); return uint256(balance.currentEpochBalance); } /** * @notice Get the next epoch total active balance. */ function getTotalActiveBalanceNextEpoch() public view returns (uint256) { if (!hasEpochZeroStarted()) { return 0; } (LS1Types.StoredBalance memory balance, , , ) = _loadActiveBalance(_TOTAL_ACTIVE_BALANCE_); return uint256(balance.nextEpochBalance); } /** * @notice Get the current inactive balance of a staker. * @dev The balance is converted via the index to token units. */ function getInactiveBalanceCurrentEpoch( address staker ) public view returns (uint256) { if (!hasEpochZeroStarted()) { return 0; } (LS1Types.StoredBalance memory balance, ) = _loadUserInactiveBalance(_INACTIVE_BALANCES_[staker]); return uint256(balance.currentEpochBalance); } /** * @notice Get the next epoch inactive balance of a staker. * @dev The balance is converted via the index to token units. */ function getInactiveBalanceNextEpoch( address staker ) public view returns (uint256) { if (!hasEpochZeroStarted()) { return 0; } (LS1Types.StoredBalance memory balance, ) = _loadUserInactiveBalance(_INACTIVE_BALANCES_[staker]); return uint256(balance.nextEpochBalance); } /** * @notice Get the current total inactive balance. */ function getTotalInactiveBalanceCurrentEpoch() public view returns (uint256) { if (!hasEpochZeroStarted()) { return 0; } LS1Types.StoredBalance memory balance = _loadTotalInactiveBalance(_TOTAL_INACTIVE_BALANCE_); return uint256(balance.currentEpochBalance); } /** * @notice Get the next epoch total inactive balance. */ function getTotalInactiveBalanceNextEpoch() public view returns (uint256) { if (!hasEpochZeroStarted()) { return 0; } LS1Types.StoredBalance memory balance = _loadTotalInactiveBalance(_TOTAL_INACTIVE_BALANCE_); return uint256(balance.nextEpochBalance); } /** * @notice Get a staker's debt balance, after accounting for unsettled shortfalls. * Note that this does not modify _STAKER_DEBT_BALANCES_, so the debt balance must still be * settled before it can be withdrawn. * * @param staker The staker to get the balance of. * * @return The settled debt balance. */ function getStakerDebtBalance( address staker ) public view returns (uint256) { if (!hasEpochZeroStarted()) { return 0; } (, uint256 newDebtAmount) = _loadUserInactiveBalance(_INACTIVE_BALANCES_[staker]); return _STAKER_DEBT_BALANCES_[staker].add(newDebtAmount); } /** * @notice Get the current transferable balance for a user. The user can * only transfer their balance that is not currently inactive or going to be * inactive in the next epoch. Note that this means the user's transferable funds * are their active balance of the next epoch. * * @param account The account to get the transferable balance of. * * @return The user's transferable balance. */ function getTransferableBalance( address account ) public view returns (uint256) { return getActiveBalanceNextEpoch(account); } // ============ Internal Functions ============ function _increaseCurrentAndNextActiveBalance( address staker, uint256 amount ) internal { // Always settle total active balance before settling a staker active balance. uint256 oldTotalBalance = _increaseCurrentAndNextBalances(address(0), true, amount); uint256 oldUserBalance = _increaseCurrentAndNextBalances(staker, true, amount); // When an active balance changes at current timestamp, settle rewards to the current timestamp. _settleUserRewardsUpToNow(staker, oldUserBalance, oldTotalBalance); } function _moveNextBalanceActiveToInactive( address staker, uint256 amount ) internal { // Decrease the active balance for the next epoch. // Always settle total active balance before settling a staker active balance. _decreaseNextBalance(address(0), true, amount); _decreaseNextBalance(staker, true, amount); // Increase the inactive balance for the next epoch. _increaseNextBalance(address(0), false, amount); _increaseNextBalance(staker, false, amount); // Note that we don't need to settle rewards since the current active balance did not change. } function _transferCurrentAndNextActiveBalance( address sender, address recipient, uint256 amount ) internal { // Always settle total active balance before settling a staker active balance. uint256 totalBalance = _settleTotalActiveBalance(); // Move current and next active balances from sender to recipient. uint256 oldSenderBalance = _decreaseCurrentAndNextBalances(sender, true, amount); uint256 oldRecipientBalance = _increaseCurrentAndNextBalances(recipient, true, amount); // When an active balance changes at current timestamp, settle rewards to the current timestamp. _settleUserRewardsUpToNow(sender, oldSenderBalance, totalBalance); _settleUserRewardsUpToNow(recipient, oldRecipientBalance, totalBalance); } function _decreaseCurrentAndNextInactiveBalance( address staker, uint256 amount ) internal { // Decrease the inactive balance for the next epoch. _decreaseCurrentAndNextBalances(address(0), false, amount); _decreaseCurrentAndNextBalances(staker, false, amount); // Note that we don't settle rewards since active balances are not affected. } function _settleTotalActiveBalance() internal returns (uint256) { return _settleBalance(address(0), true); } function _settleStakerDebtBalance( address staker ) internal returns (uint256) { // Settle the inactive balance to settle any new debt. _settleBalance(staker, false); // Return the settled debt balance. return _STAKER_DEBT_BALANCES_[staker]; } function _settleAndClaimRewards( address staker, address recipient ) internal returns (uint256) { // Always settle total active balance before settling a staker active balance. uint256 totalBalance = _settleTotalActiveBalance(); // Always settle staker active balance before settling staker rewards. uint256 userBalance = _settleBalance(staker, true); // Settle rewards balance since we want to claim the full accrued amount. _settleUserRewardsUpToNow(staker, userBalance, totalBalance); // Claim rewards balance. return _claimRewards(staker, recipient); } function _applyShortfall( uint256 shortfallAmount, uint256 shortfallIndex ) internal { // Decrease the total inactive balance. _decreaseCurrentAndNextBalances(address(0), false, shortfallAmount); _SHORTFALLS_.push(LS1Types.Shortfall({ epoch: getCurrentEpoch().toUint16(), index: shortfallIndex.toUint224() })); } /** * @dev Does the same thing as _settleBalance() for a user inactive balance, but limits * the epoch we progress to, in order that we can put an upper bound on the gas expenditure of * the function. See LS1Failsafe. */ function _failsafeSettleUserInactiveBalance( address staker, uint256 maxEpoch ) internal { LS1Types.StoredBalance storage balancePtr = _getBalancePtr(staker, false); LS1Types.StoredBalance memory balance = _failsafeLoadUserInactiveBalanceForUpdate(balancePtr, staker, maxEpoch); _storeBalance(balancePtr, balance); } /** * @dev Sets the user inactive balance to zero. See LS1Failsafe. * * Since the balance will never be settled, the staker loses any debt balance that they would * have otherwise been entitled to from shortfall losses. * * Also note that we don't update the total inactive balance, but this is fine. */ function _failsafeDeleteUserInactiveBalance( address staker ) internal { LS1Types.StoredBalance storage balancePtr = _getBalancePtr(staker, false); LS1Types.StoredBalance memory balance = LS1Types.StoredBalance({ currentEpoch: 0, currentEpochBalance: 0, nextEpochBalance: 0, shortfallCounter: 0 }); _storeBalance(balancePtr, balance); } // ============ Private Functions ============ /** * @dev Load a balance for update and then store it. */ function _settleBalance( address maybeStaker, bool isActiveBalance ) private returns (uint256) { LS1Types.StoredBalance storage balancePtr = _getBalancePtr(maybeStaker, isActiveBalance); LS1Types.StoredBalance memory balance = _loadBalanceForUpdate(balancePtr, maybeStaker, isActiveBalance); uint256 currentBalance = uint256(balance.currentEpochBalance); _storeBalance(balancePtr, balance); return currentBalance; } /** * @dev Settle a balance while applying an increase. */ function _increaseCurrentAndNextBalances( address maybeStaker, bool isActiveBalance, uint256 amount ) private returns (uint256) { LS1Types.StoredBalance storage balancePtr = _getBalancePtr(maybeStaker, isActiveBalance); LS1Types.StoredBalance memory balance = _loadBalanceForUpdate(balancePtr, maybeStaker, isActiveBalance); uint256 originalCurrentBalance = uint256(balance.currentEpochBalance); balance.currentEpochBalance = originalCurrentBalance.add(amount).toUint112(); balance.nextEpochBalance = uint256(balance.nextEpochBalance).add(amount).toUint112(); _storeBalance(balancePtr, balance); return originalCurrentBalance; } /** * @dev Settle a balance while applying a decrease. */ function _decreaseCurrentAndNextBalances( address maybeStaker, bool isActiveBalance, uint256 amount ) private returns (uint256) { LS1Types.StoredBalance storage balancePtr = _getBalancePtr(maybeStaker, isActiveBalance); LS1Types.StoredBalance memory balance = _loadBalanceForUpdate(balancePtr, maybeStaker, isActiveBalance); uint256 originalCurrentBalance = uint256(balance.currentEpochBalance); balance.currentEpochBalance = originalCurrentBalance.sub(amount).toUint112(); balance.nextEpochBalance = uint256(balance.nextEpochBalance).sub(amount).toUint112(); _storeBalance(balancePtr, balance); return originalCurrentBalance; } /** * @dev Settle a balance while applying an increase. */ function _increaseNextBalance( address maybeStaker, bool isActiveBalance, uint256 amount ) private { LS1Types.StoredBalance storage balancePtr = _getBalancePtr(maybeStaker, isActiveBalance); LS1Types.StoredBalance memory balance = _loadBalanceForUpdate(balancePtr, maybeStaker, isActiveBalance); balance.nextEpochBalance = uint256(balance.nextEpochBalance).add(amount).toUint112(); _storeBalance(balancePtr, balance); } /** * @dev Settle a balance while applying a decrease. */ function _decreaseNextBalance( address maybeStaker, bool isActiveBalance, uint256 amount ) private { LS1Types.StoredBalance storage balancePtr = _getBalancePtr(maybeStaker, isActiveBalance); LS1Types.StoredBalance memory balance = _loadBalanceForUpdate(balancePtr, maybeStaker, isActiveBalance); balance.nextEpochBalance = uint256(balance.nextEpochBalance).sub(amount).toUint112(); _storeBalance(balancePtr, balance); } function _getBalancePtr( address maybeStaker, bool isActiveBalance ) private view returns (LS1Types.StoredBalance storage) { // Active. if (isActiveBalance) { if (maybeStaker != address(0)) { return _ACTIVE_BALANCES_[maybeStaker]; } return _TOTAL_ACTIVE_BALANCE_; } // Inactive. if (maybeStaker != address(0)) { return _INACTIVE_BALANCES_[maybeStaker]; } return _TOTAL_INACTIVE_BALANCE_; } /** * @dev Load a balance for updating. * * IMPORTANT: This function modifies state, and so the balance MUST be stored afterwards. * - For active balances: if a rollover occurs, rewards are settled to the epoch boundary. * - For inactive user balances: if a shortfall occurs, the user's debt balance is increased. * * @param balancePtr A storage pointer to the balance. * @param maybeStaker The user address, or address(0) to update total balance. * @param isActiveBalance Whether the balance is an active balance. */ function _loadBalanceForUpdate( LS1Types.StoredBalance storage balancePtr, address maybeStaker, bool isActiveBalance ) private returns (LS1Types.StoredBalance memory) { // Active balance. if (isActiveBalance) { ( LS1Types.StoredBalance memory balance, uint256 beforeRolloverEpoch, uint256 beforeRolloverBalance, bool didRolloverOccur ) = _loadActiveBalance(balancePtr); if (didRolloverOccur) { // Handle the effect of the balance rollover on rewards. We must partially settle the index // up to the epoch boundary where the change in balance occurred. We pass in the balance // from before the boundary. if (maybeStaker == address(0)) { // If it's the total active balance... _settleGlobalIndexUpToEpoch(beforeRolloverBalance, beforeRolloverEpoch); } else { // If it's a user active balance... _settleUserRewardsUpToEpoch(maybeStaker, beforeRolloverBalance, beforeRolloverEpoch); } } return balance; } // Total inactive balance. if (maybeStaker == address(0)) { return _loadTotalInactiveBalance(balancePtr); } // User inactive balance. (LS1Types.StoredBalance memory balance, uint256 newStakerDebt) = _loadUserInactiveBalance(balancePtr); if (newStakerDebt != 0) { uint256 newDebtBalance = _STAKER_DEBT_BALANCES_[maybeStaker].add(newStakerDebt); _STAKER_DEBT_BALANCES_[maybeStaker] = newDebtBalance; emit ReceivedDebt(maybeStaker, newStakerDebt, newDebtBalance); } return balance; } function _loadActiveBalance( LS1Types.StoredBalance storage balancePtr ) private view returns ( LS1Types.StoredBalance memory, uint256, uint256, bool ) { LS1Types.StoredBalance memory balance = balancePtr; // Return these as they may be needed for rewards settlement. uint256 beforeRolloverEpoch = uint256(balance.currentEpoch); uint256 beforeRolloverBalance = uint256(balance.currentEpochBalance); bool didRolloverOccur = false; // Roll the balance forward if needed. uint256 currentEpoch = getCurrentEpoch(); if (currentEpoch > uint256(balance.currentEpoch)) { didRolloverOccur = balance.currentEpochBalance != balance.nextEpochBalance; balance.currentEpoch = currentEpoch.toUint16(); balance.currentEpochBalance = balance.nextEpochBalance; } return (balance, beforeRolloverEpoch, beforeRolloverBalance, didRolloverOccur); } function _loadTotalInactiveBalance( LS1Types.StoredBalance storage balancePtr ) private view returns (LS1Types.StoredBalance memory) { LS1Types.StoredBalance memory balance = balancePtr; // Roll the balance forward if needed. uint256 currentEpoch = getCurrentEpoch(); if (currentEpoch > uint256(balance.currentEpoch)) { balance.currentEpoch = currentEpoch.toUint16(); balance.currentEpochBalance = balance.nextEpochBalance; } return balance; } function _loadUserInactiveBalance( LS1Types.StoredBalance storage balancePtr ) private view returns (LS1Types.StoredBalance memory, uint256) { LS1Types.StoredBalance memory balance = balancePtr; uint256 currentEpoch = getCurrentEpoch(); // If there is no non-zero balance, sync the epoch number and shortfall counter and exit. // Note: Next inactive balance is always >= current, so we only need to check next. if (balance.nextEpochBalance == 0) { balance.currentEpoch = currentEpoch.toUint16(); balance.shortfallCounter = _SHORTFALLS_.length.toUint16(); return (balance, 0); } // Apply any pending shortfalls that don't affect the “next epoch” balance. uint256 newStakerDebt; (balance, newStakerDebt) = _applyShortfallsToBalance(balance); // Roll the balance forward if needed. if (currentEpoch > uint256(balance.currentEpoch)) { balance.currentEpoch = currentEpoch.toUint16(); balance.currentEpochBalance = balance.nextEpochBalance; // Check for more shortfalls affecting the “next epoch” and beyond. uint256 moreNewStakerDebt; (balance, moreNewStakerDebt) = _applyShortfallsToBalance(balance); newStakerDebt = newStakerDebt.add(moreNewStakerDebt); } return (balance, newStakerDebt); } function _applyShortfallsToBalance( LS1Types.StoredBalance memory balance ) private view returns (LS1Types.StoredBalance memory, uint256) { // Get the cached and global shortfall counters. uint256 shortfallCounter = uint256(balance.shortfallCounter); uint256 globalShortfallCounter = _SHORTFALLS_.length; // If the counters are in sync, then there is nothing to do. if (shortfallCounter == globalShortfallCounter) { return (balance, 0); } // Get the balance params. uint16 cachedEpoch = balance.currentEpoch; uint256 oldCurrentBalance = uint256(balance.currentEpochBalance); // Calculate the new balance after applying shortfalls. // // Note: In theory, this while-loop may render an account's funds inaccessible if there are // too many shortfalls, and too much gas is required to apply them all. This is very unlikely // to occur in practice, but we provide _failsafeLoadUserInactiveBalance() just in case to // ensure recovery is possible. uint256 newCurrentBalance = oldCurrentBalance; while (shortfallCounter < globalShortfallCounter) { LS1Types.Shortfall memory shortfall = _SHORTFALLS_[shortfallCounter]; // Stop applying shortfalls if they are in the future relative to the balance current epoch. if (shortfall.epoch > cachedEpoch) { break; } // Update the current balance to reflect the shortfall. uint256 shortfallIndex = uint256(shortfall.index); newCurrentBalance = newCurrentBalance.mul(shortfallIndex).div(SHORTFALL_INDEX_BASE); // Increment the staker's shortfall counter. shortfallCounter = shortfallCounter.add(1); } // Calculate the loss. // If the loaded balance is stored, this amount must be added to the staker's debt balance. uint256 newStakerDebt = oldCurrentBalance.sub(newCurrentBalance); // Update the balance. balance.currentEpochBalance = newCurrentBalance.toUint112(); balance.nextEpochBalance = uint256(balance.nextEpochBalance).sub(newStakerDebt).toUint112(); balance.shortfallCounter = shortfallCounter.toUint16(); return (balance, newStakerDebt); } /** * @dev Store a balance. */ function _storeBalance( LS1Types.StoredBalance storage balancePtr, LS1Types.StoredBalance memory balance ) private { // Note: This should use a single `sstore` when compiler optimizations are enabled. balancePtr.currentEpoch = balance.currentEpoch; balancePtr.currentEpochBalance = balance.currentEpochBalance; balancePtr.nextEpochBalance = balance.nextEpochBalance; balancePtr.shortfallCounter = balance.shortfallCounter; } /** * @dev Does the same thing as _loadBalanceForUpdate() for a user inactive balance, but limits * the epoch we progress to, in order that we can put an upper bound on the gas expenditure of * the function. See LS1Failsafe. */ function _failsafeLoadUserInactiveBalanceForUpdate( LS1Types.StoredBalance storage balancePtr, address staker, uint256 maxEpoch ) private returns (LS1Types.StoredBalance memory) { LS1Types.StoredBalance memory balance = balancePtr; // Validate maxEpoch. uint256 currentEpoch = getCurrentEpoch(); uint256 cachedEpoch = uint256(balance.currentEpoch); require( maxEpoch >= cachedEpoch && maxEpoch <= currentEpoch, 'LS1StakedBalances: maxEpoch' ); // Apply any pending shortfalls that don't affect the “next epoch” balance. uint256 newStakerDebt; (balance, newStakerDebt) = _applyShortfallsToBalance(balance); // Roll the balance forward if needed. if (maxEpoch > cachedEpoch) { balance.currentEpoch = maxEpoch.toUint16(); // Use maxEpoch instead of currentEpoch. balance.currentEpochBalance = balance.nextEpochBalance; // Check for more shortfalls affecting the “next epoch” and beyond. uint256 moreNewStakerDebt; (balance, moreNewStakerDebt) = _applyShortfallsToBalance(balance); newStakerDebt = newStakerDebt.add(moreNewStakerDebt); } // Apply debt if needed. if (newStakerDebt != 0) { uint256 newDebtBalance = _STAKER_DEBT_BALANCES_[staker].add(newStakerDebt); _STAKER_DEBT_BALANCES_[staker] = newDebtBalance; emit ReceivedDebt(staker, newStakerDebt, newDebtBalance); } return balance; } } // SPDX-License-Identifier: Apache-2.0 pragma solidity 0.7.5; pragma abicoder v2; import { SafeERC20 } from '../../../dependencies/open-zeppelin/SafeERC20.sol'; import { SafeMath } from '../../../dependencies/open-zeppelin/SafeMath.sol'; import { IERC20 } from '../../../interfaces/IERC20.sol'; import { Math } from '../../../utils/Math.sol'; import { SafeCast } from '../lib/SafeCast.sol'; import { LS1EpochSchedule } from './LS1EpochSchedule.sol'; /** * @title LS1Rewards * @author dYdX * * @dev Manages the distribution of token rewards. * * Rewards are distributed continuously. After each second, an account earns rewards `r` according * to the following formula: * * r = R * s / S * * Where: * - `R` is the rewards distributed globally each second, also called the “emission rate.” * - `s` is the account's staked balance in that second (technically, it is measured at the * end of the second) * - `S` is the sum total of all staked balances in that second (again, measured at the end of * the second) * * The parameter `R` can be configured by the contract owner. For every second that elapses, * exactly `R` tokens will accrue to users, save for rounding errors, and with the exception that * while the total staked balance is zero, no tokens will accrue to anyone. * * The accounting works as follows: A global index is stored which represents the cumulative * number of rewards tokens earned per staked token since the start of the distribution. * The value of this index increases over time, and there are two factors affecting the rate of * increase: * 1) The emission rate (in the numerator) * 2) The total number of staked tokens (in the denominator) * * Whenever either factor changes, in some timestamp T, we settle the global index up to T by * calculating the increase in the index since the last update using the OLD values of the factors: * * indexDelta = timeDelta * emissionPerSecond * INDEX_BASE / totalStaked * * Where `INDEX_BASE` is a scaling factor used to allow more precision in the storage of the index. * * For each user we store an accrued rewards balance, as well as a user index, which is a cache of * the global index at the time that the user's accrued rewards balance was last updated. Then at * any point in time, a user's claimable rewards are represented by the following: * * rewards = _USER_REWARDS_BALANCES_[user] + userStaked * ( * settledGlobalIndex - _USER_INDEXES_[user] * ) / INDEX_BASE */ abstract contract LS1Rewards is LS1EpochSchedule { using SafeERC20 for IERC20; using SafeCast for uint256; using SafeMath for uint256; // ============ Constants ============ /// @dev Additional precision used to represent the global and user index values. uint256 private constant INDEX_BASE = 10**18; /// @notice The rewards token. IERC20 public immutable REWARDS_TOKEN; /// @notice Address to pull rewards from. Must have provided an allowance to this contract. address public immutable REWARDS_TREASURY; /// @notice Start timestamp (inclusive) of the period in which rewards can be earned. uint256 public immutable DISTRIBUTION_START; /// @notice End timestamp (exclusive) of the period in which rewards can be earned. uint256 public immutable DISTRIBUTION_END; // ============ Events ============ event RewardsPerSecondUpdated( uint256 emissionPerSecond ); event GlobalIndexUpdated( uint256 index ); event UserIndexUpdated( address indexed user, uint256 index, uint256 unclaimedRewards ); event ClaimedRewards( address indexed user, address recipient, uint256 claimedRewards ); // ============ Constructor ============ constructor( IERC20 rewardsToken, address rewardsTreasury, uint256 distributionStart, uint256 distributionEnd ) { require(distributionEnd >= distributionStart, 'LS1Rewards: Invalid parameters'); REWARDS_TOKEN = rewardsToken; REWARDS_TREASURY = rewardsTreasury; DISTRIBUTION_START = distributionStart; DISTRIBUTION_END = distributionEnd; } // ============ External Functions ============ /** * @notice The current emission rate of rewards. * * @return The number of rewards tokens issued globally each second. */ function getRewardsPerSecond() external view returns (uint256) { return _REWARDS_PER_SECOND_; } // ============ Internal Functions ============ /** * @dev Initialize the contract. */ function __LS1Rewards_init() internal { _GLOBAL_INDEX_TIMESTAMP_ = Math.max(block.timestamp, DISTRIBUTION_START).toUint32(); } /** * @dev Set the emission rate of rewards. * * IMPORTANT: Do not call this function without settling the total staked balance first, to * ensure that the index is settled up to the epoch boundaries. * * @param emissionPerSecond The new number of rewards tokens to give out each second. * @param totalStaked The total staked balance. */ function _setRewardsPerSecond( uint256 emissionPerSecond, uint256 totalStaked ) internal { _settleGlobalIndexUpToNow(totalStaked); _REWARDS_PER_SECOND_ = emissionPerSecond; emit RewardsPerSecondUpdated(emissionPerSecond); } /** * @dev Claim tokens, sending them to the specified recipient. * * Note: In order to claim all accrued rewards, the total and user staked balances must first be * settled before calling this function. * * @param user The user's address. * @param recipient The address to send rewards to. * * @return The number of rewards tokens claimed. */ function _claimRewards( address user, address recipient ) internal returns (uint256) { uint256 accruedRewards = _USER_REWARDS_BALANCES_[user]; _USER_REWARDS_BALANCES_[user] = 0; REWARDS_TOKEN.safeTransferFrom(REWARDS_TREASURY, recipient, accruedRewards); emit ClaimedRewards(user, recipient, accruedRewards); return accruedRewards; } /** * @dev Settle a user's rewards up to the latest global index as of `block.timestamp`. Triggers a * settlement of the global index up to `block.timestamp`. Should be called with the OLD user * and total balances. * * @param user The user's address. * @param userStaked Tokens staked by the user during the period since the last user index * update. * @param totalStaked Total tokens staked by all users during the period since the last global * index update. * * @return The user's accrued rewards, including past unclaimed rewards. */ function _settleUserRewardsUpToNow( address user, uint256 userStaked, uint256 totalStaked ) internal returns (uint256) { uint256 globalIndex = _settleGlobalIndexUpToNow(totalStaked); return _settleUserRewardsUpToIndex(user, userStaked, globalIndex); } /** * @dev Settle a user's rewards up to an epoch boundary. Should be used to partially settle a * user's rewards if their balance was known to have changed on that epoch boundary. * * @param user The user's address. * @param userStaked Tokens staked by the user. Should be accurate for the time period * since the last update to this user and up to the end of the * specified epoch. * @param epochNumber Settle the user's rewards up to the end of this epoch. * * @return The user's accrued rewards, including past unclaimed rewards, up to the end of the * specified epoch. */ function _settleUserRewardsUpToEpoch( address user, uint256 userStaked, uint256 epochNumber ) internal returns (uint256) { uint256 globalIndex = _EPOCH_INDEXES_[epochNumber]; return _settleUserRewardsUpToIndex(user, userStaked, globalIndex); } /** * @dev Settle the global index up to the end of the given epoch. * * IMPORTANT: This function should only be called under conditions which ensure the following: * - `epochNumber` < the current epoch number * - `_GLOBAL_INDEX_TIMESTAMP_ < settleUpToTimestamp` * - `_EPOCH_INDEXES_[epochNumber] = 0` */ function _settleGlobalIndexUpToEpoch( uint256 totalStaked, uint256 epochNumber ) internal returns (uint256) { uint256 settleUpToTimestamp = getStartOfEpoch(epochNumber.add(1)); uint256 globalIndex = _settleGlobalIndexUpToTimestamp(totalStaked, settleUpToTimestamp); _EPOCH_INDEXES_[epochNumber] = globalIndex; return globalIndex; } // ============ Private Functions ============ function _settleGlobalIndexUpToNow( uint256 totalStaked ) private returns (uint256) { return _settleGlobalIndexUpToTimestamp(totalStaked, block.timestamp); } /** * @dev Helper function which settles a user's rewards up to a global index. Should be called * any time a user's staked balance changes, with the OLD user and total balances. * * @param user The user's address. * @param userStaked Tokens staked by the user during the period since the last user index * update. * @param newGlobalIndex The new index value to bring the user index up to. * * @return The user's accrued rewards, including past unclaimed rewards. */ function _settleUserRewardsUpToIndex( address user, uint256 userStaked, uint256 newGlobalIndex ) private returns (uint256) { uint256 oldAccruedRewards = _USER_REWARDS_BALANCES_[user]; uint256 oldUserIndex = _USER_INDEXES_[user]; if (oldUserIndex == newGlobalIndex) { return oldAccruedRewards; } uint256 newAccruedRewards; if (userStaked == 0) { // Note: Even if the user's staked balance is zero, we still need to update the user index. newAccruedRewards = oldAccruedRewards; } else { // Calculate newly accrued rewards since the last update to the user's index. uint256 indexDelta = newGlobalIndex.sub(oldUserIndex); uint256 accruedRewardsDelta = userStaked.mul(indexDelta).div(INDEX_BASE); newAccruedRewards = oldAccruedRewards.add(accruedRewardsDelta); // Update the user's rewards. _USER_REWARDS_BALANCES_[user] = newAccruedRewards; } // Update the user's index. _USER_INDEXES_[user] = newGlobalIndex; emit UserIndexUpdated(user, newGlobalIndex, newAccruedRewards); return newAccruedRewards; } /** * @dev Updates the global index, reflecting cumulative rewards given out per staked token. * * @param totalStaked The total staked balance, which should be constant in the interval * (_GLOBAL_INDEX_TIMESTAMP_, settleUpToTimestamp). * @param settleUpToTimestamp The timestamp up to which to settle rewards. It MUST satisfy * `settleUpToTimestamp <= block.timestamp`. * * @return The new global index. */ function _settleGlobalIndexUpToTimestamp( uint256 totalStaked, uint256 settleUpToTimestamp ) private returns (uint256) { uint256 oldGlobalIndex = uint256(_GLOBAL_INDEX_); // The goal of this function is to calculate rewards earned since the last global index update. // These rewards are earned over the time interval which is the intersection of the intervals // [_GLOBAL_INDEX_TIMESTAMP_, settleUpToTimestamp] and [DISTRIBUTION_START, DISTRIBUTION_END]. // // We can simplify a bit based on the assumption: // `_GLOBAL_INDEX_TIMESTAMP_ >= DISTRIBUTION_START` // // Get the start and end of the time interval under consideration. uint256 intervalStart = uint256(_GLOBAL_INDEX_TIMESTAMP_); uint256 intervalEnd = Math.min(settleUpToTimestamp, DISTRIBUTION_END); // Return early if the interval has length zero (incl. case where intervalEnd < intervalStart). if (intervalEnd <= intervalStart) { return oldGlobalIndex; } // Note: If we reach this point, we must update _GLOBAL_INDEX_TIMESTAMP_. uint256 emissionPerSecond = _REWARDS_PER_SECOND_; if (emissionPerSecond == 0 || totalStaked == 0) { // Ensure a log is emitted if the timestamp changed, even if the index does not change. _GLOBAL_INDEX_TIMESTAMP_ = intervalEnd.toUint32(); emit GlobalIndexUpdated(oldGlobalIndex); return oldGlobalIndex; } // Calculate the change in index over the interval. uint256 timeDelta = intervalEnd.sub(intervalStart); uint256 indexDelta = timeDelta.mul(emissionPerSecond).mul(INDEX_BASE).div(totalStaked); // Calculate, update, and return the new global index. uint256 newGlobalIndex = oldGlobalIndex.add(indexDelta); // Update storage. (Shared storage slot.) _GLOBAL_INDEX_TIMESTAMP_ = intervalEnd.toUint32(); _GLOBAL_INDEX_ = newGlobalIndex.toUint224(); emit GlobalIndexUpdated(newGlobalIndex); return newGlobalIndex; } } // SPDX-License-Identifier: Apache-2.0 pragma solidity 0.7.5; pragma abicoder v2; import { SafeMath } from '../../../dependencies/open-zeppelin/SafeMath.sol'; import { LS1Types } from '../lib/LS1Types.sol'; import { SafeCast } from '../lib/SafeCast.sol'; import { LS1Roles } from './LS1Roles.sol'; /** * @title LS1EpochSchedule * @author dYdX * * @dev Defines a function from block timestamp to epoch number. * * The formula used is `n = floor((t - b) / a)` where: * - `n` is the epoch number * - `t` is the timestamp (in seconds) * - `b` is a non-negative offset, indicating the start of epoch zero (in seconds) * - `a` is the length of an epoch, a.k.a. the interval (in seconds) * * Note that by restricting `b` to be non-negative, we limit ourselves to functions in which epoch * zero starts at a non-negative timestamp. * * The recommended epoch length and blackout window are 28 and 7 days respectively; however, these * are modifiable by the admin, within the specified bounds. */ abstract contract LS1EpochSchedule is LS1Roles { using SafeCast for uint256; using SafeMath for uint256; // ============ Constants ============ /// @dev Minimum blackout window. Note: The min epoch length is twice the current blackout window. uint256 private constant MIN_BLACKOUT_WINDOW = 3 days; /// @dev Maximum epoch length. Note: The max blackout window is half the current epoch length. uint256 private constant MAX_EPOCH_LENGTH = 92 days; // Approximately one quarter year. // ============ Events ============ event EpochParametersChanged( LS1Types.EpochParameters epochParameters ); event BlackoutWindowChanged( uint256 blackoutWindow ); // ============ Initializer ============ function __LS1EpochSchedule_init( uint256 interval, uint256 offset, uint256 blackoutWindow ) internal { require( block.timestamp < offset, 'LS1EpochSchedule: Epoch zero must be in future' ); // Don't use _setBlackoutWindow() since the interval is not set yet and validation would fail. _BLACKOUT_WINDOW_ = blackoutWindow; emit BlackoutWindowChanged(blackoutWindow); _setEpochParameters(interval, offset); } // ============ Public Functions ============ /** * @notice Get the epoch at the current block timestamp. * * NOTE: Reverts if epoch zero has not started. * * @return The current epoch number. */ function getCurrentEpoch() public view returns (uint256) { (uint256 interval, uint256 offsetTimestamp) = _getIntervalAndOffsetTimestamp(); return offsetTimestamp.div(interval); } /** * @notice Get the time remaining in the current epoch. * * NOTE: Reverts if epoch zero has not started. * * @return The number of seconds until the next epoch. */ function getTimeRemainingInCurrentEpoch() public view returns (uint256) { (uint256 interval, uint256 offsetTimestamp) = _getIntervalAndOffsetTimestamp(); uint256 timeElapsedInEpoch = offsetTimestamp.mod(interval); return interval.sub(timeElapsedInEpoch); } /** * @notice Given an epoch number, get the start of that epoch. Calculated as `t = (n * a) + b`. * * @return The timestamp in seconds representing the start of that epoch. */ function getStartOfEpoch( uint256 epochNumber ) public view returns (uint256) { LS1Types.EpochParameters memory epochParameters = _EPOCH_PARAMETERS_; uint256 interval = uint256(epochParameters.interval); uint256 offset = uint256(epochParameters.offset); return epochNumber.mul(interval).add(offset); } /** * @notice Check whether we are at or past the start of epoch zero. * * @return Boolean `true` if the current timestamp is at least the start of epoch zero, * otherwise `false`. */ function hasEpochZeroStarted() public view returns (bool) { LS1Types.EpochParameters memory epochParameters = _EPOCH_PARAMETERS_; uint256 offset = uint256(epochParameters.offset); return block.timestamp >= offset; } /** * @notice Check whether we are in a blackout window, where withdrawal requests are restricted. * Note that before epoch zero has started, there are no blackout windows. * * @return Boolean `true` if we are in a blackout window, otherwise `false`. */ function inBlackoutWindow() public view returns (bool) { return hasEpochZeroStarted() && getTimeRemainingInCurrentEpoch() <= _BLACKOUT_WINDOW_; } // ============ Internal Functions ============ function _setEpochParameters( uint256 interval, uint256 offset ) internal { _validateParamLengths(interval, _BLACKOUT_WINDOW_); LS1Types.EpochParameters memory epochParameters = LS1Types.EpochParameters({interval: interval.toUint128(), offset: offset.toUint128()}); _EPOCH_PARAMETERS_ = epochParameters; emit EpochParametersChanged(epochParameters); } function _setBlackoutWindow( uint256 blackoutWindow ) internal { _validateParamLengths(uint256(_EPOCH_PARAMETERS_.interval), blackoutWindow); _BLACKOUT_WINDOW_ = blackoutWindow; emit BlackoutWindowChanged(blackoutWindow); } // ============ Private Functions ============ /** * @dev Helper function to read params from storage and apply offset to the given timestamp. * * NOTE: Reverts if epoch zero has not started. * * @return The length of an epoch, in seconds. * @return The start of epoch zero, in seconds. */ function _getIntervalAndOffsetTimestamp() private view returns (uint256, uint256) { LS1Types.EpochParameters memory epochParameters = _EPOCH_PARAMETERS_; uint256 interval = uint256(epochParameters.interval); uint256 offset = uint256(epochParameters.offset); require(block.timestamp >= offset, 'LS1EpochSchedule: Epoch zero has not started'); uint256 offsetTimestamp = block.timestamp.sub(offset); return (interval, offsetTimestamp); } /** * @dev Helper for common validation: verify that the interval and window lengths are valid. */ function _validateParamLengths( uint256 interval, uint256 blackoutWindow ) private pure { require( blackoutWindow.mul(2) <= interval, 'LS1EpochSchedule: Blackout window can be at most half the epoch length' ); require( blackoutWindow >= MIN_BLACKOUT_WINDOW, 'LS1EpochSchedule: Blackout window too large' ); require( interval <= MAX_EPOCH_LENGTH, 'LS1EpochSchedule: Epoch length too small' ); } } // SPDX-License-Identifier: Apache-2.0 pragma solidity 0.7.5; pragma abicoder v2; import { LS1Storage } from './LS1Storage.sol'; /** * @title LS1Roles * @author dYdX * * @dev Defines roles used in the LiquidityStakingV1 contract. The hierarchy of roles and powers * of each role are described below. * * Roles: * * OWNER_ROLE * | -> May add or remove users from any of the below roles it manages. * | * +-- EPOCH_PARAMETERS_ROLE * | -> May set epoch parameters such as the interval, offset, and blackout window. * | * +-- REWARDS_RATE_ROLE * | -> May set the emission rate of rewards. * | * +-- BORROWER_ADMIN_ROLE * | -> May set borrower allocations and allow/restrict borrowers from borrowing. * | * +-- CLAIM_OPERATOR_ROLE * | -> May claim rewards on behalf of a user. * | * +-- STAKE_OPERATOR_ROLE * | -> May manipulate user's staked funds (e.g. perform withdrawals on behalf of a user). * | * +-- DEBT_OPERATOR_ROLE * -> May decrease borrow debt and decrease staker debt. */ abstract contract LS1Roles is LS1Storage { bytes32 public constant OWNER_ROLE = keccak256('OWNER_ROLE'); bytes32 public constant EPOCH_PARAMETERS_ROLE = keccak256('EPOCH_PARAMETERS_ROLE'); bytes32 public constant REWARDS_RATE_ROLE = keccak256('REWARDS_RATE_ROLE'); bytes32 public constant BORROWER_ADMIN_ROLE = keccak256('BORROWER_ADMIN_ROLE'); bytes32 public constant CLAIM_OPERATOR_ROLE = keccak256('CLAIM_OPERATOR_ROLE'); bytes32 public constant STAKE_OPERATOR_ROLE = keccak256('STAKE_OPERATOR_ROLE'); bytes32 public constant DEBT_OPERATOR_ROLE = keccak256('DEBT_OPERATOR_ROLE'); function __LS1Roles_init() internal { // Assign roles to the sender. // // The DEBT_OPERATOR_ROLE, STAKE_OPERATOR_ROLE, and CLAIM_OPERATOR_ROLE roles are not // initially assigned. These can be assigned to other smart contracts to provide additional // functionality for users. _setupRole(OWNER_ROLE, msg.sender); _setupRole(EPOCH_PARAMETERS_ROLE, msg.sender); _setupRole(REWARDS_RATE_ROLE, msg.sender); _setupRole(BORROWER_ADMIN_ROLE, msg.sender); // Set OWNER_ROLE as the admin of all roles. _setRoleAdmin(OWNER_ROLE, OWNER_ROLE); _setRoleAdmin(EPOCH_PARAMETERS_ROLE, OWNER_ROLE); _setRoleAdmin(REWARDS_RATE_ROLE, OWNER_ROLE); _setRoleAdmin(BORROWER_ADMIN_ROLE, OWNER_ROLE); _setRoleAdmin(CLAIM_OPERATOR_ROLE, OWNER_ROLE); _setRoleAdmin(STAKE_OPERATOR_ROLE, OWNER_ROLE); _setRoleAdmin(DEBT_OPERATOR_ROLE, OWNER_ROLE); } } // SPDX-License-Identifier: AGPL-3.0 pragma solidity 0.7.5; import { IERC20 } from './IERC20.sol'; /** * @dev Interface for ERC20 including metadata **/ interface IERC20Detailed is IERC20 { function name() external view returns (string memory); function symbol() external view returns (string memory); function decimals() external view returns (uint8); }
Helper for common validation: verify that the interval and window lengths are valid./
function _validateParamLengths( uint256 interval, uint256 blackoutWindow ) private pure { require( blackoutWindow.mul(2) <= interval, 'LS1EpochSchedule: Blackout window can be at most half the epoch length' ); require( blackoutWindow >= MIN_BLACKOUT_WINDOW, 'LS1EpochSchedule: Blackout window too large' ); require( interval <= MAX_EPOCH_LENGTH, 'LS1EpochSchedule: Epoch length too small' ); }
5,860,627
./full_match/1/0x5Ec09Dc83080A17De87aE0bd22097F360e078cf7/sources/src/interfaces/IUnitPricesGovernance.sol
------------------- EXTERNAL, VIEW ------------------- ------------------- EXTERNAL, MUTATING -------------------
interface IUnitPricesGovernance is IDefaultAccessControl, IERC165 { function stagedUnitPrices(address token) external view returns (uint256); function stagedUnitPricesTimestamps(address token) external view returns (uint256); function unitPrices(address token) external view returns (uint256); function stageUnitPrice(address token, uint256 value) external; function rollbackUnitPrice(address token) external; function commitUnitPrice(address token) external; pragma solidity ^0.8.0; }
4,887,349
./partial_match/42/0xeb6fF4C0c4c551eBA648A683E85feE8FffdA8dD7/sources/CollateralErc20.sol
https:docs.Pynthetix.io/contracts/source/interfaces/iexchangerates Structs
interface IExchangeRates { function accessControl(bytes32 section, address account) external view returns (bool canSuspend, bool canResume); function requireSystemActive() external view; function requireIssuanceActive() external view; function requireExchangeActive() external view; function requireExchangeBetweenPynthsAllowed(bytes32 sourceCurrencyKey, bytes32 destinationCurrencyKey) external view; function requirePynthActive(bytes32 currencyKey) external view; function requirePynthsActive(bytes32 sourceCurrencyKey, bytes32 destinationCurrencyKey) external view; function systemSuspension() external view returns (bool suspended, uint248 reason); function issuanceSuspension() external view returns (bool suspended, uint248 reason); function exchangeSuspension() external view returns (bool suspended, uint248 reason); function PynthExchangeSuspension(bytes32 currencyKey) external view returns (bool suspended, uint248 reason); function PynthSuspension(bytes32 currencyKey) external view returns (bool suspended, uint248 reason); function getPynthExchangeSuspensions(bytes32[] calldata Pynths) external view returns (bool[] memory exchangeSuspensions, uint256[] memory reasons); function getPynthSuspensions(bytes32[] calldata Pynths) external view returns (bool[] memory suspensions, uint256[] memory reasons); function suspendPynth(bytes32 currencyKey, uint256 reason) external; function updateAccessControl( bytes32 section, address account, bool canSuspend, bool canResume ) external; } } } struct RateAndUpdatedTime { uint216 rate; uint40 time; } struct InversePricing { uint entryPoint; uint upperLimit; uint lowerLimit; bool frozenAtUpperLimit; bool frozenAtLowerLimit; } }
8,910,161
./full_match/1/0x6513Aedb4D1593BA12e50644401D976aebDc90d8/sources/contracts/deploy/Deployer.sol
Returns the address where a contract will be stored if deployed via {deploy} or {deployAndInit} by `sender`. Any change in the `bytecode` (except for `CREATE3`), `sender`, or `salt` will result in a new deployed address. bytecode The bytecode of the contract to be deployed sender The address that will deploy the contract via the deployment method salt The salt that will be used to influence the contract address return deployedAddress_ The address that the contract will be deployed to/
function deployedAddress( bytes memory bytecode, address sender, bytes32 salt ) public view returns (address) { bytes32 deploySalt = keccak256(abi.encode(sender, salt)); return _deployedAddress(bytecode, deploySalt); }
4,948,960
pragma solidity 0.5.17; contract IFactRegistry { /* Returns true if the given fact was previously registered in the contract. */ function isValid(bytes32 fact) external view returns(bool); } contract IMerkleVerifier { uint256 constant internal MAX_N_MERKLE_VERIFIER_QUERIES = 128; function verify( uint256 channelPtr, uint256 queuePtr, bytes32 root, uint256 n) internal view returns (bytes32 hash); } contract IQueryableFactRegistry is IFactRegistry { /* Returns true if at least one fact has been registered. */ function hasRegisteredFact() external view returns(bool); } contract IStarkVerifier { function verifyProof( uint256[] memory proofParams, uint256[] memory proof, uint256[] memory publicInput ) internal; } contract MemoryMap { /* We store the state of the verifer in a contiguous chunk of memory. The offsets of the different fields are listed below. E.g. The offset of the i'th hash is [mm_hashes + i]. */ uint256 constant internal CHANNEL_STATE_SIZE = 3; uint256 constant internal MAX_N_QUERIES = 48; uint256 constant internal FRI_QUEUE_SIZE = MAX_N_QUERIES; uint256 constant internal MAX_SUPPORTED_MAX_FRI_STEP = 4; uint256 constant internal MM_EVAL_DOMAIN_SIZE = 0x0; uint256 constant internal MM_BLOW_UP_FACTOR = 0x1; uint256 constant internal MM_LOG_EVAL_DOMAIN_SIZE = 0x2; uint256 constant internal MM_PROOF_OF_WORK_BITS = 0x3; uint256 constant internal MM_EVAL_DOMAIN_GENERATOR = 0x4; uint256 constant internal MM_PUBLIC_INPUT_PTR = 0x5; uint256 constant internal MM_TRACE_COMMITMENT = 0x6; uint256 constant internal MM_OODS_COMMITMENT = 0x7; uint256 constant internal MM_N_UNIQUE_QUERIES = 0x8; uint256 constant internal MM_CHANNEL = 0x9; // uint256[3] uint256 constant internal MM_MERKLE_QUEUE = 0xc; // uint256[96] uint256 constant internal MM_FRI_QUEUE = 0x6c; // uint256[144] uint256 constant internal MM_FRI_QUERIES_DELIMITER = 0xfc; uint256 constant internal MM_FRI_CTX = 0xfd; // uint256[40] uint256 constant internal MM_FRI_STEPS_PTR = 0x125; uint256 constant internal MM_FRI_EVAL_POINTS = 0x126; // uint256[10] uint256 constant internal MM_FRI_COMMITMENTS = 0x130; // uint256[10] uint256 constant internal MM_FRI_LAST_LAYER_DEG_BOUND = 0x13a; uint256 constant internal MM_FRI_LAST_LAYER_PTR = 0x13b; uint256 constant internal MM_CONSTRAINT_POLY_ARGS_START = 0x13c; uint256 constant internal MM_PERIODIC_COLUMN__CONSTS0_A = 0x13c; uint256 constant internal MM_PERIODIC_COLUMN__CONSTS1_A = 0x13d; uint256 constant internal MM_PERIODIC_COLUMN__CONSTS2_A = 0x13e; uint256 constant internal MM_PERIODIC_COLUMN__CONSTS3_A = 0x13f; uint256 constant internal MM_PERIODIC_COLUMN__CONSTS4_A = 0x140; uint256 constant internal MM_PERIODIC_COLUMN__CONSTS5_A = 0x141; uint256 constant internal MM_PERIODIC_COLUMN__CONSTS6_A = 0x142; uint256 constant internal MM_PERIODIC_COLUMN__CONSTS7_A = 0x143; uint256 constant internal MM_PERIODIC_COLUMN__CONSTS8_A = 0x144; uint256 constant internal MM_PERIODIC_COLUMN__CONSTS9_A = 0x145; uint256 constant internal MM_PERIODIC_COLUMN__CONSTS0_B = 0x146; uint256 constant internal MM_PERIODIC_COLUMN__CONSTS1_B = 0x147; uint256 constant internal MM_PERIODIC_COLUMN__CONSTS2_B = 0x148; uint256 constant internal MM_PERIODIC_COLUMN__CONSTS3_B = 0x149; uint256 constant internal MM_PERIODIC_COLUMN__CONSTS4_B = 0x14a; uint256 constant internal MM_PERIODIC_COLUMN__CONSTS5_B = 0x14b; uint256 constant internal MM_PERIODIC_COLUMN__CONSTS6_B = 0x14c; uint256 constant internal MM_PERIODIC_COLUMN__CONSTS7_B = 0x14d; uint256 constant internal MM_PERIODIC_COLUMN__CONSTS8_B = 0x14e; uint256 constant internal MM_PERIODIC_COLUMN__CONSTS9_B = 0x14f; uint256 constant internal MM_MAT00 = 0x150; uint256 constant internal MM_MAT01 = 0x151; uint256 constant internal MM_TRACE_LENGTH = 0x152; uint256 constant internal MM_MAT10 = 0x153; uint256 constant internal MM_MAT11 = 0x154; uint256 constant internal MM_INPUT_VALUE_A = 0x155; uint256 constant internal MM_OUTPUT_VALUE_A = 0x156; uint256 constant internal MM_INPUT_VALUE_B = 0x157; uint256 constant internal MM_OUTPUT_VALUE_B = 0x158; uint256 constant internal MM_TRACE_GENERATOR = 0x159; uint256 constant internal MM_OODS_POINT = 0x15a; uint256 constant internal MM_COEFFICIENTS = 0x15b; // uint256[48] uint256 constant internal MM_OODS_VALUES = 0x18b; // uint256[22] uint256 constant internal MM_CONSTRAINT_POLY_ARGS_END = 0x1a1; uint256 constant internal MM_COMPOSITION_OODS_VALUES = 0x1a1; // uint256[2] uint256 constant internal MM_OODS_EVAL_POINTS = 0x1a3; // uint256[48] uint256 constant internal MM_OODS_COEFFICIENTS = 0x1d3; // uint256[24] uint256 constant internal MM_TRACE_QUERY_RESPONSES = 0x1eb; // uint256[960] uint256 constant internal MM_COMPOSITION_QUERY_RESPONSES = 0x5ab; // uint256[96] uint256 constant internal MM_CONTEXT_SIZE = 0x60b; } contract MerkleVerifier is IMerkleVerifier { function getHashMask() internal pure returns(uint256) { // Default implementation. return 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF000000000000000000000000; } /* Verifies a Merkle tree decommitment for n leaves in a Merkle tree with N leaves. The inputs data sits in the queue at queuePtr. Each slot in the queue contains a 32 bytes leaf index and a 32 byte leaf value. The indices need to be in the range [N..2*N-1] and strictly incrementing. Decommitments are read from the channel in the ctx. The input data is destroyed during verification. */ function verify( uint256 channelPtr, uint256 queuePtr, bytes32 root, uint256 n) internal view returns (bytes32 hash) { uint256 lhashMask = getHashMask(); require(n <= MAX_N_MERKLE_VERIFIER_QUERIES, "TOO_MANY_MERKLE_QUERIES"); assembly { // queuePtr + i * 0x40 gives the i'th index in the queue. // hashesPtr + i * 0x40 gives the i'th hash in the queue. let hashesPtr := add(queuePtr, 0x20) let queueSize := mul(n, 0x40) let slotSize := 0x40 // The items are in slots [0, n-1]. let rdIdx := 0 let wrIdx := 0 // = n % n. // Iterate the queue until we hit the root. let index := mload(add(rdIdx, queuePtr)) let proofPtr := mload(channelPtr) // while(index > 1). for { } gt(index, 1) { } { let siblingIndex := xor(index, 1) // sibblingOffset := 0x20 * lsb(siblingIndex). let sibblingOffset := mulmod(siblingIndex, 0x20, 0x40) // Store the hash corresponding to index in the correct slot. // 0 if index is even and 0x20 if index is odd. // The hash of the sibling will be written to the other slot. mstore(xor(0x20, sibblingOffset), mload(add(rdIdx, hashesPtr))) rdIdx := addmod(rdIdx, slotSize, queueSize) // Inline channel operation: // Assume we are going to read a new hash from the proof. // If this is not the case add(proofPtr, 0x20) will be reverted. let newHashPtr := proofPtr proofPtr := add(proofPtr, 0x20) // Push index/2 into the queue, before reading the next index. // The order is important, as otherwise we may try to read from an empty queue (in // the case where we are working on one item). // wrIdx will be updated after writing the relevant hash to the queue. mstore(add(wrIdx, queuePtr), div(index, 2)) // Load the next index from the queue and check if it is our sibling. index := mload(add(rdIdx, queuePtr)) if eq(index, siblingIndex) { // Take sibling from queue rather than from proof. newHashPtr := add(rdIdx, hashesPtr) // Revert reading from proof. proofPtr := sub(proofPtr, 0x20) rdIdx := addmod(rdIdx, slotSize, queueSize) // Index was consumed, read the next one. // Note that the queue can't be empty at this point. // The index of the parent of the current node was already pushed into the // queue, and the parent is never the sibling. index := mload(add(rdIdx, queuePtr)) } mstore(sibblingOffset, mload(newHashPtr)) // Push the new hash to the end of the queue. mstore(add(wrIdx, hashesPtr), and(lhashMask, keccak256(0x00, 0x40))) wrIdx := addmod(wrIdx, slotSize, queueSize) } hash := mload(add(rdIdx, hashesPtr)) // Update the proof pointer in the context. mstore(channelPtr, proofPtr) } // emit LogBool(hash == root); require(hash == root, "INVALID_MERKLE_PROOF"); } } contract MimcConstraintPoly { // The Memory map during the execution of this contract is as follows: // [0x0, 0x20) - periodic_column/consts0_a. // [0x20, 0x40) - periodic_column/consts1_a. // [0x40, 0x60) - periodic_column/consts2_a. // [0x60, 0x80) - periodic_column/consts3_a. // [0x80, 0xa0) - periodic_column/consts4_a. // [0xa0, 0xc0) - periodic_column/consts5_a. // [0xc0, 0xe0) - periodic_column/consts6_a. // [0xe0, 0x100) - periodic_column/consts7_a. // [0x100, 0x120) - periodic_column/consts8_a. // [0x120, 0x140) - periodic_column/consts9_a. // [0x140, 0x160) - periodic_column/consts0_b. // [0x160, 0x180) - periodic_column/consts1_b. // [0x180, 0x1a0) - periodic_column/consts2_b. // [0x1a0, 0x1c0) - periodic_column/consts3_b. // [0x1c0, 0x1e0) - periodic_column/consts4_b. // [0x1e0, 0x200) - periodic_column/consts5_b. // [0x200, 0x220) - periodic_column/consts6_b. // [0x220, 0x240) - periodic_column/consts7_b. // [0x240, 0x260) - periodic_column/consts8_b. // [0x260, 0x280) - periodic_column/consts9_b. // [0x280, 0x2a0) - mat00. // [0x2a0, 0x2c0) - mat01. // [0x2c0, 0x2e0) - trace_length. // [0x2e0, 0x300) - mat10. // [0x300, 0x320) - mat11. // [0x320, 0x340) - input_value_a. // [0x340, 0x360) - output_value_a. // [0x360, 0x380) - input_value_b. // [0x380, 0x3a0) - output_value_b. // [0x3a0, 0x3c0) - trace_generator. // [0x3c0, 0x3e0) - oods_point. // [0x3e0, 0x9e0) - coefficients. // [0x9e0, 0xca0) - oods_values. // ----------------------- end of input data - ------------------------- // [0xca0, 0xcc0) - composition_degree_bound. // [0xcc0, 0xce0) - intermediate_value/after_lin_transform0_a_0. // [0xce0, 0xd00) - intermediate_value/after_lin_transform0_b_0. // [0xd00, 0xd20) - intermediate_value/after_lin_transform1_a_0. // [0xd20, 0xd40) - intermediate_value/after_lin_transform1_b_0. // [0xd40, 0xd60) - intermediate_value/after_lin_transform2_a_0. // [0xd60, 0xd80) - intermediate_value/after_lin_transform2_b_0. // [0xd80, 0xda0) - intermediate_value/after_lin_transform3_a_0. // [0xda0, 0xdc0) - intermediate_value/after_lin_transform3_b_0. // [0xdc0, 0xde0) - intermediate_value/after_lin_transform4_a_0. // [0xde0, 0xe00) - intermediate_value/after_lin_transform4_b_0. // [0xe00, 0xe20) - intermediate_value/after_lin_transform5_a_0. // [0xe20, 0xe40) - intermediate_value/after_lin_transform5_b_0. // [0xe40, 0xe60) - intermediate_value/after_lin_transform6_a_0. // [0xe60, 0xe80) - intermediate_value/after_lin_transform6_b_0. // [0xe80, 0xea0) - intermediate_value/after_lin_transform7_a_0. // [0xea0, 0xec0) - intermediate_value/after_lin_transform7_b_0. // [0xec0, 0xee0) - intermediate_value/after_lin_transform8_a_0. // [0xee0, 0xf00) - intermediate_value/after_lin_transform8_b_0. // [0xf00, 0xf20) - intermediate_value/after_lin_transform9_a_0. // [0xf20, 0xf40) - intermediate_value/after_lin_transform9_b_0. // [0xf40, 0xf80) - expmods. // [0xf80, 0xfe0) - denominator_invs. // [0xfe0, 0x1040) - denominators. // [0x1040, 0x1060) - numerators. // [0x1060, 0x10c0) - adjustments. // [0x10c0, 0x1180) - expmod_context. function() external { uint256 res; assembly { let PRIME := 0x30000003000000010000000000000001 // Copy input from calldata to memory. calldatacopy(0x0, 0x0, /*Input data size*/ 0xca0) let point := /*oods_point*/ mload(0x3c0) // Initialize composition_degree_bound to 2 * trace_length. mstore(0xca0, mul(2, /*trace_length*/ mload(0x2c0))) function expmod(base, exponent, modulus) -> res { let p := /*expmod_context*/ 0x10c0 mstore(p, 0x20) // Length of Base. mstore(add(p, 0x20), 0x20) // Length of Exponent. mstore(add(p, 0x40), 0x20) // Length of Modulus. mstore(add(p, 0x60), base) // Base. mstore(add(p, 0x80), exponent) // Exponent. mstore(add(p, 0xa0), modulus) // Modulus. // Call modexp precompile. if iszero(staticcall(not(0), 0x05, p, 0xc0, p, 0x20)) { revert(0, 0) } res := mload(p) } function degreeAdjustment(compositionPolynomialDegreeBound, constraintDegree, numeratorDegree, denominatorDegree) -> res { res := sub(sub(compositionPolynomialDegreeBound, 1), sub(add(constraintDegree, numeratorDegree), denominatorDegree)) } { // Prepare expmods for denominators and numerators. // expmods[0] = point^trace_length. mstore(0xf40, expmod(point, /*trace_length*/ mload(0x2c0), PRIME)) // expmods[1] = trace_generator^(trace_length - 1). mstore(0xf60, expmod(/*trace_generator*/ mload(0x3a0), sub(/*trace_length*/ mload(0x2c0), 1), PRIME)) } { // Prepare denominators for batch inverse. // Denominator for constraints: 'step0_a', 'step0_b', 'step1_a', 'step1_b', 'step2_a', 'step2_b', 'step3_a', 'step3_b', 'step4_a', 'step4_b', 'step5_a', 'step5_b', 'step6_a', 'step6_b', 'step7_a', 'step7_b', 'step8_a', 'step8_b', 'step9_a', 'step9_b'. // denominators[0] = point^trace_length - 1. mstore(0xfe0, addmod(/*point^trace_length*/ mload(0xf40), sub(PRIME, 1), PRIME)) // Denominator for constraints: 'input_a', 'input_b'. // denominators[1] = point - 1. mstore(0x1000, addmod(point, sub(PRIME, 1), PRIME)) // Denominator for constraints: 'output_a', 'output_b'. // denominators[2] = point - trace_generator^(trace_length - 1). mstore(0x1020, addmod(point, sub(PRIME, /*trace_generator^(trace_length - 1)*/ mload(0xf60)), PRIME)) } { // Compute the inverses of the denominators into denominatorInvs using batch inverse. // Start by computing the cumulative product. // Let (d_0, d_1, d_2, ..., d_{n-1}) be the values in denominators. After this loop // denominatorInvs will be (1, d_0, d_0 * d_1, ...) and prod will contain the value of // d_0 * ... * d_{n-1}. // Compute the offset between the partialProducts array and the input values array. let productsToValuesOffset := 0x60 let prod := 1 let partialProductEndPtr := 0xfe0 for { let partialProductPtr := 0xf80 } lt(partialProductPtr, partialProductEndPtr) { partialProductPtr := add(partialProductPtr, 0x20) } { mstore(partialProductPtr, prod) // prod *= d_{i}. prod := mulmod(prod, mload(add(partialProductPtr, productsToValuesOffset)), PRIME) } let firstPartialProductPtr := 0xf80 // Compute the inverse of the product. let prodInv := expmod(prod, sub(PRIME, 2), PRIME) if eq(prodInv, 0) { // Solidity generates reverts with reason that look as follows: // 1. 4 bytes with the constant 0x08c379a0 (== Keccak256(b'Error(string)')[:4]). // 2. 32 bytes offset bytes (always 0x20 as far as i can tell). // 3. 32 bytes with the length of the revert reason. // 4. Revert reason string. mstore(0, 0x08c379a000000000000000000000000000000000000000000000000000000000) mstore(0x4, 0x20) mstore(0x24, 0x1e) mstore(0x44, "Batch inverse product is zero.") revert(0, 0x62) } // Compute the inverses. // Loop over denominator_invs in reverse order. // currentPartialProductPtr is initialized to one past the end. let currentPartialProductPtr := 0xfe0 for { } gt(currentPartialProductPtr, firstPartialProductPtr) { } { currentPartialProductPtr := sub(currentPartialProductPtr, 0x20) // Store 1/d_{i} = (d_0 * ... * d_{i-1}) * 1/(d_0 * ... * d_{i}). mstore(currentPartialProductPtr, mulmod(mload(currentPartialProductPtr), prodInv, PRIME)) // Update prodInv to be 1/(d_0 * ... * d_{i-1}) by multiplying by d_i. prodInv := mulmod(prodInv, mload(add(currentPartialProductPtr, productsToValuesOffset)), PRIME) } } { // Compute numerators and adjustment polynomials. // Numerator for constraints 'step9_a', 'step9_b'. // numerators[0] = point - trace_generator^(trace_length - 1). mstore(0x1040, addmod(point, sub(PRIME, /*trace_generator^(trace_length - 1)*/ mload(0xf60)), PRIME)) // Adjustment polynomial for constraints 'step0_a', 'step0_b', 'step1_a', 'step1_b', 'step2_a', 'step2_b', 'step3_a', 'step3_b', 'step4_a', 'step4_b', 'step5_a', 'step5_b', 'step6_a', 'step6_b', 'step7_a', 'step7_b', 'step8_a', 'step8_b'. // adjustments[0] = point^degreeAdjustment(composition_degree_bound, 3 * (trace_length - 1), 0, trace_length). mstore(0x1060, expmod(point, degreeAdjustment(/*composition_degree_bound*/ mload(0xca0), mul(3, sub(/*trace_length*/ mload(0x2c0), 1)), 0, /*trace_length*/ mload(0x2c0)), PRIME)) // Adjustment polynomial for constraints 'step9_a', 'step9_b'. // adjustments[1] = point^degreeAdjustment(composition_degree_bound, 3 * (trace_length - 1), 1, trace_length). mstore(0x1080, expmod(point, degreeAdjustment(/*composition_degree_bound*/ mload(0xca0), mul(3, sub(/*trace_length*/ mload(0x2c0), 1)), 1, /*trace_length*/ mload(0x2c0)), PRIME)) // Adjustment polynomial for constraints 'input_a', 'output_a', 'input_b', 'output_b'. // adjustments[2] = point^degreeAdjustment(composition_degree_bound, trace_length - 1, 0, 1). mstore(0x10a0, expmod(point, degreeAdjustment(/*composition_degree_bound*/ mload(0xca0), sub(/*trace_length*/ mload(0x2c0), 1), 0, 1), PRIME)) } { // Compute the result of the composition polynomial. { // after_lin_transform0_a_0 = mat00 * (column0_row0 - consts0_a) + mat01 * (column10_row0 - consts0_b). let val := addmod( mulmod( /*mat00*/ mload(0x280), addmod( /*column0_row0*/ mload(0x9e0), sub(PRIME, /*periodic_column/consts0_a*/ mload(0x0)), PRIME), PRIME), mulmod( /*mat01*/ mload(0x2a0), addmod( /*column10_row0*/ mload(0xb40), sub(PRIME, /*periodic_column/consts0_b*/ mload(0x140)), PRIME), PRIME), PRIME) mstore(0xcc0, val) } { // after_lin_transform0_b_0 = mat10 * (column0_row0 - consts0_a) + mat11 * (column10_row0 - consts0_b). let val := addmod( mulmod( /*mat10*/ mload(0x2e0), addmod( /*column0_row0*/ mload(0x9e0), sub(PRIME, /*periodic_column/consts0_a*/ mload(0x0)), PRIME), PRIME), mulmod( /*mat11*/ mload(0x300), addmod( /*column10_row0*/ mload(0xb40), sub(PRIME, /*periodic_column/consts0_b*/ mload(0x140)), PRIME), PRIME), PRIME) mstore(0xce0, val) } { // after_lin_transform1_a_0 = mat00 * (column1_row0 - consts1_a) + mat01 * (column11_row0 - consts1_b). let val := addmod( mulmod( /*mat00*/ mload(0x280), addmod( /*column1_row0*/ mload(0xa20), sub(PRIME, /*periodic_column/consts1_a*/ mload(0x20)), PRIME), PRIME), mulmod( /*mat01*/ mload(0x2a0), addmod( /*column11_row0*/ mload(0xb80), sub(PRIME, /*periodic_column/consts1_b*/ mload(0x160)), PRIME), PRIME), PRIME) mstore(0xd00, val) } { // after_lin_transform1_b_0 = mat10 * (column1_row0 - consts1_a) + mat11 * (column11_row0 - consts1_b). let val := addmod( mulmod( /*mat10*/ mload(0x2e0), addmod( /*column1_row0*/ mload(0xa20), sub(PRIME, /*periodic_column/consts1_a*/ mload(0x20)), PRIME), PRIME), mulmod( /*mat11*/ mload(0x300), addmod( /*column11_row0*/ mload(0xb80), sub(PRIME, /*periodic_column/consts1_b*/ mload(0x160)), PRIME), PRIME), PRIME) mstore(0xd20, val) } { // after_lin_transform2_a_0 = mat00 * (column2_row0 - consts2_a) + mat01 * (column12_row0 - consts2_b). let val := addmod( mulmod( /*mat00*/ mload(0x280), addmod( /*column2_row0*/ mload(0xa40), sub(PRIME, /*periodic_column/consts2_a*/ mload(0x40)), PRIME), PRIME), mulmod( /*mat01*/ mload(0x2a0), addmod( /*column12_row0*/ mload(0xba0), sub(PRIME, /*periodic_column/consts2_b*/ mload(0x180)), PRIME), PRIME), PRIME) mstore(0xd40, val) } { // after_lin_transform2_b_0 = mat10 * (column2_row0 - consts2_a) + mat11 * (column12_row0 - consts2_b). let val := addmod( mulmod( /*mat10*/ mload(0x2e0), addmod( /*column2_row0*/ mload(0xa40), sub(PRIME, /*periodic_column/consts2_a*/ mload(0x40)), PRIME), PRIME), mulmod( /*mat11*/ mload(0x300), addmod( /*column12_row0*/ mload(0xba0), sub(PRIME, /*periodic_column/consts2_b*/ mload(0x180)), PRIME), PRIME), PRIME) mstore(0xd60, val) } { // after_lin_transform3_a_0 = mat00 * (column3_row0 - consts3_a) + mat01 * (column13_row0 - consts3_b). let val := addmod( mulmod( /*mat00*/ mload(0x280), addmod( /*column3_row0*/ mload(0xa60), sub(PRIME, /*periodic_column/consts3_a*/ mload(0x60)), PRIME), PRIME), mulmod( /*mat01*/ mload(0x2a0), addmod( /*column13_row0*/ mload(0xbc0), sub(PRIME, /*periodic_column/consts3_b*/ mload(0x1a0)), PRIME), PRIME), PRIME) mstore(0xd80, val) } { // after_lin_transform3_b_0 = mat10 * (column3_row0 - consts3_a) + mat11 * (column13_row0 - consts3_b). let val := addmod( mulmod( /*mat10*/ mload(0x2e0), addmod( /*column3_row0*/ mload(0xa60), sub(PRIME, /*periodic_column/consts3_a*/ mload(0x60)), PRIME), PRIME), mulmod( /*mat11*/ mload(0x300), addmod( /*column13_row0*/ mload(0xbc0), sub(PRIME, /*periodic_column/consts3_b*/ mload(0x1a0)), PRIME), PRIME), PRIME) mstore(0xda0, val) } { // after_lin_transform4_a_0 = mat00 * (column4_row0 - consts4_a) + mat01 * (column14_row0 - consts4_b). let val := addmod( mulmod( /*mat00*/ mload(0x280), addmod( /*column4_row0*/ mload(0xa80), sub(PRIME, /*periodic_column/consts4_a*/ mload(0x80)), PRIME), PRIME), mulmod( /*mat01*/ mload(0x2a0), addmod( /*column14_row0*/ mload(0xbe0), sub(PRIME, /*periodic_column/consts4_b*/ mload(0x1c0)), PRIME), PRIME), PRIME) mstore(0xdc0, val) } { // after_lin_transform4_b_0 = mat10 * (column4_row0 - consts4_a) + mat11 * (column14_row0 - consts4_b). let val := addmod( mulmod( /*mat10*/ mload(0x2e0), addmod( /*column4_row0*/ mload(0xa80), sub(PRIME, /*periodic_column/consts4_a*/ mload(0x80)), PRIME), PRIME), mulmod( /*mat11*/ mload(0x300), addmod( /*column14_row0*/ mload(0xbe0), sub(PRIME, /*periodic_column/consts4_b*/ mload(0x1c0)), PRIME), PRIME), PRIME) mstore(0xde0, val) } { // after_lin_transform5_a_0 = mat00 * (column5_row0 - consts5_a) + mat01 * (column15_row0 - consts5_b). let val := addmod( mulmod( /*mat00*/ mload(0x280), addmod( /*column5_row0*/ mload(0xaa0), sub(PRIME, /*periodic_column/consts5_a*/ mload(0xa0)), PRIME), PRIME), mulmod( /*mat01*/ mload(0x2a0), addmod( /*column15_row0*/ mload(0xc00), sub(PRIME, /*periodic_column/consts5_b*/ mload(0x1e0)), PRIME), PRIME), PRIME) mstore(0xe00, val) } { // after_lin_transform5_b_0 = mat10 * (column5_row0 - consts5_a) + mat11 * (column15_row0 - consts5_b). let val := addmod( mulmod( /*mat10*/ mload(0x2e0), addmod( /*column5_row0*/ mload(0xaa0), sub(PRIME, /*periodic_column/consts5_a*/ mload(0xa0)), PRIME), PRIME), mulmod( /*mat11*/ mload(0x300), addmod( /*column15_row0*/ mload(0xc00), sub(PRIME, /*periodic_column/consts5_b*/ mload(0x1e0)), PRIME), PRIME), PRIME) mstore(0xe20, val) } { // after_lin_transform6_a_0 = mat00 * (column6_row0 - consts6_a) + mat01 * (column16_row0 - consts6_b). let val := addmod( mulmod( /*mat00*/ mload(0x280), addmod( /*column6_row0*/ mload(0xac0), sub(PRIME, /*periodic_column/consts6_a*/ mload(0xc0)), PRIME), PRIME), mulmod( /*mat01*/ mload(0x2a0), addmod( /*column16_row0*/ mload(0xc20), sub(PRIME, /*periodic_column/consts6_b*/ mload(0x200)), PRIME), PRIME), PRIME) mstore(0xe40, val) } { // after_lin_transform6_b_0 = mat10 * (column6_row0 - consts6_a) + mat11 * (column16_row0 - consts6_b). let val := addmod( mulmod( /*mat10*/ mload(0x2e0), addmod( /*column6_row0*/ mload(0xac0), sub(PRIME, /*periodic_column/consts6_a*/ mload(0xc0)), PRIME), PRIME), mulmod( /*mat11*/ mload(0x300), addmod( /*column16_row0*/ mload(0xc20), sub(PRIME, /*periodic_column/consts6_b*/ mload(0x200)), PRIME), PRIME), PRIME) mstore(0xe60, val) } { // after_lin_transform7_a_0 = mat00 * (column7_row0 - consts7_a) + mat01 * (column17_row0 - consts7_b). let val := addmod( mulmod( /*mat00*/ mload(0x280), addmod( /*column7_row0*/ mload(0xae0), sub(PRIME, /*periodic_column/consts7_a*/ mload(0xe0)), PRIME), PRIME), mulmod( /*mat01*/ mload(0x2a0), addmod( /*column17_row0*/ mload(0xc40), sub(PRIME, /*periodic_column/consts7_b*/ mload(0x220)), PRIME), PRIME), PRIME) mstore(0xe80, val) } { // after_lin_transform7_b_0 = mat10 * (column7_row0 - consts7_a) + mat11 * (column17_row0 - consts7_b). let val := addmod( mulmod( /*mat10*/ mload(0x2e0), addmod( /*column7_row0*/ mload(0xae0), sub(PRIME, /*periodic_column/consts7_a*/ mload(0xe0)), PRIME), PRIME), mulmod( /*mat11*/ mload(0x300), addmod( /*column17_row0*/ mload(0xc40), sub(PRIME, /*periodic_column/consts7_b*/ mload(0x220)), PRIME), PRIME), PRIME) mstore(0xea0, val) } { // after_lin_transform8_a_0 = mat00 * (column8_row0 - consts8_a) + mat01 * (column18_row0 - consts8_b). let val := addmod( mulmod( /*mat00*/ mload(0x280), addmod( /*column8_row0*/ mload(0xb00), sub(PRIME, /*periodic_column/consts8_a*/ mload(0x100)), PRIME), PRIME), mulmod( /*mat01*/ mload(0x2a0), addmod( /*column18_row0*/ mload(0xc60), sub(PRIME, /*periodic_column/consts8_b*/ mload(0x240)), PRIME), PRIME), PRIME) mstore(0xec0, val) } { // after_lin_transform8_b_0 = mat10 * (column8_row0 - consts8_a) + mat11 * (column18_row0 - consts8_b). let val := addmod( mulmod( /*mat10*/ mload(0x2e0), addmod( /*column8_row0*/ mload(0xb00), sub(PRIME, /*periodic_column/consts8_a*/ mload(0x100)), PRIME), PRIME), mulmod( /*mat11*/ mload(0x300), addmod( /*column18_row0*/ mload(0xc60), sub(PRIME, /*periodic_column/consts8_b*/ mload(0x240)), PRIME), PRIME), PRIME) mstore(0xee0, val) } { // after_lin_transform9_a_0 = mat00 * (column9_row0 - consts9_a) + mat01 * (column19_row0 - consts9_b). let val := addmod( mulmod( /*mat00*/ mload(0x280), addmod( /*column9_row0*/ mload(0xb20), sub(PRIME, /*periodic_column/consts9_a*/ mload(0x120)), PRIME), PRIME), mulmod( /*mat01*/ mload(0x2a0), addmod( /*column19_row0*/ mload(0xc80), sub(PRIME, /*periodic_column/consts9_b*/ mload(0x260)), PRIME), PRIME), PRIME) mstore(0xf00, val) } { // after_lin_transform9_b_0 = mat10 * (column9_row0 - consts9_a) + mat11 * (column19_row0 - consts9_b). let val := addmod( mulmod( /*mat10*/ mload(0x2e0), addmod( /*column9_row0*/ mload(0xb20), sub(PRIME, /*periodic_column/consts9_a*/ mload(0x120)), PRIME), PRIME), mulmod( /*mat11*/ mload(0x300), addmod( /*column19_row0*/ mload(0xc80), sub(PRIME, /*periodic_column/consts9_b*/ mload(0x260)), PRIME), PRIME), PRIME) mstore(0xf20, val) } { // Constraint expression for step0_a: column1_row0 - after_lin_transform0_a_0 * after_lin_transform0_a_0 * after_lin_transform0_a_0. let val := addmod( /*column1_row0*/ mload(0xa20), sub( PRIME, mulmod( mulmod( /*intermediate_value/after_lin_transform0_a_0*/ mload(0xcc0), /*intermediate_value/after_lin_transform0_a_0*/ mload(0xcc0), PRIME), /*intermediate_value/after_lin_transform0_a_0*/ mload(0xcc0), PRIME)), PRIME) // Numerator: 1. // val *= 1. // val := mulmod(val, 1, PRIME). // Denominator: point^trace_length - 1. // val *= denominator_invs[0]. val := mulmod(val, mload(0xf80), PRIME) // res += val * (coefficients[0] + coefficients[1] * adjustments[0]). res := addmod(res, mulmod(val, add(/*coefficients[0]*/ mload(0x3e0), mulmod(/*coefficients[1]*/ mload(0x400), /*adjustments[0]*/mload(0x1060), PRIME)), PRIME), PRIME) } { // Constraint expression for step0_b: column11_row0 - after_lin_transform0_b_0 * after_lin_transform0_b_0 * after_lin_transform0_b_0. let val := addmod( /*column11_row0*/ mload(0xb80), sub( PRIME, mulmod( mulmod( /*intermediate_value/after_lin_transform0_b_0*/ mload(0xce0), /*intermediate_value/after_lin_transform0_b_0*/ mload(0xce0), PRIME), /*intermediate_value/after_lin_transform0_b_0*/ mload(0xce0), PRIME)), PRIME) // Numerator: 1. // val *= 1. // val := mulmod(val, 1, PRIME). // Denominator: point^trace_length - 1. // val *= denominator_invs[0]. val := mulmod(val, mload(0xf80), PRIME) // res += val * (coefficients[2] + coefficients[3] * adjustments[0]). res := addmod(res, mulmod(val, add(/*coefficients[2]*/ mload(0x420), mulmod(/*coefficients[3]*/ mload(0x440), /*adjustments[0]*/mload(0x1060), PRIME)), PRIME), PRIME) } { // Constraint expression for step1_a: column2_row0 - after_lin_transform1_a_0 * after_lin_transform1_a_0 * after_lin_transform1_a_0. let val := addmod( /*column2_row0*/ mload(0xa40), sub( PRIME, mulmod( mulmod( /*intermediate_value/after_lin_transform1_a_0*/ mload(0xd00), /*intermediate_value/after_lin_transform1_a_0*/ mload(0xd00), PRIME), /*intermediate_value/after_lin_transform1_a_0*/ mload(0xd00), PRIME)), PRIME) // Numerator: 1. // val *= 1. // val := mulmod(val, 1, PRIME). // Denominator: point^trace_length - 1. // val *= denominator_invs[0]. val := mulmod(val, mload(0xf80), PRIME) // res += val * (coefficients[4] + coefficients[5] * adjustments[0]). res := addmod(res, mulmod(val, add(/*coefficients[4]*/ mload(0x460), mulmod(/*coefficients[5]*/ mload(0x480), /*adjustments[0]*/mload(0x1060), PRIME)), PRIME), PRIME) } { // Constraint expression for step1_b: column12_row0 - after_lin_transform1_b_0 * after_lin_transform1_b_0 * after_lin_transform1_b_0. let val := addmod( /*column12_row0*/ mload(0xba0), sub( PRIME, mulmod( mulmod( /*intermediate_value/after_lin_transform1_b_0*/ mload(0xd20), /*intermediate_value/after_lin_transform1_b_0*/ mload(0xd20), PRIME), /*intermediate_value/after_lin_transform1_b_0*/ mload(0xd20), PRIME)), PRIME) // Numerator: 1. // val *= 1. // val := mulmod(val, 1, PRIME). // Denominator: point^trace_length - 1. // val *= denominator_invs[0]. val := mulmod(val, mload(0xf80), PRIME) // res += val * (coefficients[6] + coefficients[7] * adjustments[0]). res := addmod(res, mulmod(val, add(/*coefficients[6]*/ mload(0x4a0), mulmod(/*coefficients[7]*/ mload(0x4c0), /*adjustments[0]*/mload(0x1060), PRIME)), PRIME), PRIME) } { // Constraint expression for step2_a: column3_row0 - after_lin_transform2_a_0 * after_lin_transform2_a_0 * after_lin_transform2_a_0. let val := addmod( /*column3_row0*/ mload(0xa60), sub( PRIME, mulmod( mulmod( /*intermediate_value/after_lin_transform2_a_0*/ mload(0xd40), /*intermediate_value/after_lin_transform2_a_0*/ mload(0xd40), PRIME), /*intermediate_value/after_lin_transform2_a_0*/ mload(0xd40), PRIME)), PRIME) // Numerator: 1. // val *= 1. // val := mulmod(val, 1, PRIME). // Denominator: point^trace_length - 1. // val *= denominator_invs[0]. val := mulmod(val, mload(0xf80), PRIME) // res += val * (coefficients[8] + coefficients[9] * adjustments[0]). res := addmod(res, mulmod(val, add(/*coefficients[8]*/ mload(0x4e0), mulmod(/*coefficients[9]*/ mload(0x500), /*adjustments[0]*/mload(0x1060), PRIME)), PRIME), PRIME) } { // Constraint expression for step2_b: column13_row0 - after_lin_transform2_b_0 * after_lin_transform2_b_0 * after_lin_transform2_b_0. let val := addmod( /*column13_row0*/ mload(0xbc0), sub( PRIME, mulmod( mulmod( /*intermediate_value/after_lin_transform2_b_0*/ mload(0xd60), /*intermediate_value/after_lin_transform2_b_0*/ mload(0xd60), PRIME), /*intermediate_value/after_lin_transform2_b_0*/ mload(0xd60), PRIME)), PRIME) // Numerator: 1. // val *= 1. // val := mulmod(val, 1, PRIME). // Denominator: point^trace_length - 1. // val *= denominator_invs[0]. val := mulmod(val, mload(0xf80), PRIME) // res += val * (coefficients[10] + coefficients[11] * adjustments[0]). res := addmod(res, mulmod(val, add(/*coefficients[10]*/ mload(0x520), mulmod(/*coefficients[11]*/ mload(0x540), /*adjustments[0]*/mload(0x1060), PRIME)), PRIME), PRIME) } { // Constraint expression for step3_a: column4_row0 - after_lin_transform3_a_0 * after_lin_transform3_a_0 * after_lin_transform3_a_0. let val := addmod( /*column4_row0*/ mload(0xa80), sub( PRIME, mulmod( mulmod( /*intermediate_value/after_lin_transform3_a_0*/ mload(0xd80), /*intermediate_value/after_lin_transform3_a_0*/ mload(0xd80), PRIME), /*intermediate_value/after_lin_transform3_a_0*/ mload(0xd80), PRIME)), PRIME) // Numerator: 1. // val *= 1. // val := mulmod(val, 1, PRIME). // Denominator: point^trace_length - 1. // val *= denominator_invs[0]. val := mulmod(val, mload(0xf80), PRIME) // res += val * (coefficients[12] + coefficients[13] * adjustments[0]). res := addmod(res, mulmod(val, add(/*coefficients[12]*/ mload(0x560), mulmod(/*coefficients[13]*/ mload(0x580), /*adjustments[0]*/mload(0x1060), PRIME)), PRIME), PRIME) } { // Constraint expression for step3_b: column14_row0 - after_lin_transform3_b_0 * after_lin_transform3_b_0 * after_lin_transform3_b_0. let val := addmod( /*column14_row0*/ mload(0xbe0), sub( PRIME, mulmod( mulmod( /*intermediate_value/after_lin_transform3_b_0*/ mload(0xda0), /*intermediate_value/after_lin_transform3_b_0*/ mload(0xda0), PRIME), /*intermediate_value/after_lin_transform3_b_0*/ mload(0xda0), PRIME)), PRIME) // Numerator: 1. // val *= 1. // val := mulmod(val, 1, PRIME). // Denominator: point^trace_length - 1. // val *= denominator_invs[0]. val := mulmod(val, mload(0xf80), PRIME) // res += val * (coefficients[14] + coefficients[15] * adjustments[0]). res := addmod(res, mulmod(val, add(/*coefficients[14]*/ mload(0x5a0), mulmod(/*coefficients[15]*/ mload(0x5c0), /*adjustments[0]*/mload(0x1060), PRIME)), PRIME), PRIME) } { // Constraint expression for step4_a: column5_row0 - after_lin_transform4_a_0 * after_lin_transform4_a_0 * after_lin_transform4_a_0. let val := addmod( /*column5_row0*/ mload(0xaa0), sub( PRIME, mulmod( mulmod( /*intermediate_value/after_lin_transform4_a_0*/ mload(0xdc0), /*intermediate_value/after_lin_transform4_a_0*/ mload(0xdc0), PRIME), /*intermediate_value/after_lin_transform4_a_0*/ mload(0xdc0), PRIME)), PRIME) // Numerator: 1. // val *= 1. // val := mulmod(val, 1, PRIME). // Denominator: point^trace_length - 1. // val *= denominator_invs[0]. val := mulmod(val, mload(0xf80), PRIME) // res += val * (coefficients[16] + coefficients[17] * adjustments[0]). res := addmod(res, mulmod(val, add(/*coefficients[16]*/ mload(0x5e0), mulmod(/*coefficients[17]*/ mload(0x600), /*adjustments[0]*/mload(0x1060), PRIME)), PRIME), PRIME) } { // Constraint expression for step4_b: column15_row0 - after_lin_transform4_b_0 * after_lin_transform4_b_0 * after_lin_transform4_b_0. let val := addmod( /*column15_row0*/ mload(0xc00), sub( PRIME, mulmod( mulmod( /*intermediate_value/after_lin_transform4_b_0*/ mload(0xde0), /*intermediate_value/after_lin_transform4_b_0*/ mload(0xde0), PRIME), /*intermediate_value/after_lin_transform4_b_0*/ mload(0xde0), PRIME)), PRIME) // Numerator: 1. // val *= 1. // val := mulmod(val, 1, PRIME). // Denominator: point^trace_length - 1. // val *= denominator_invs[0]. val := mulmod(val, mload(0xf80), PRIME) // res += val * (coefficients[18] + coefficients[19] * adjustments[0]). res := addmod(res, mulmod(val, add(/*coefficients[18]*/ mload(0x620), mulmod(/*coefficients[19]*/ mload(0x640), /*adjustments[0]*/mload(0x1060), PRIME)), PRIME), PRIME) } { // Constraint expression for step5_a: column6_row0 - after_lin_transform5_a_0 * after_lin_transform5_a_0 * after_lin_transform5_a_0. let val := addmod( /*column6_row0*/ mload(0xac0), sub( PRIME, mulmod( mulmod( /*intermediate_value/after_lin_transform5_a_0*/ mload(0xe00), /*intermediate_value/after_lin_transform5_a_0*/ mload(0xe00), PRIME), /*intermediate_value/after_lin_transform5_a_0*/ mload(0xe00), PRIME)), PRIME) // Numerator: 1. // val *= 1. // val := mulmod(val, 1, PRIME). // Denominator: point^trace_length - 1. // val *= denominator_invs[0]. val := mulmod(val, mload(0xf80), PRIME) // res += val * (coefficients[20] + coefficients[21] * adjustments[0]). res := addmod(res, mulmod(val, add(/*coefficients[20]*/ mload(0x660), mulmod(/*coefficients[21]*/ mload(0x680), /*adjustments[0]*/mload(0x1060), PRIME)), PRIME), PRIME) } { // Constraint expression for step5_b: column16_row0 - after_lin_transform5_b_0 * after_lin_transform5_b_0 * after_lin_transform5_b_0. let val := addmod( /*column16_row0*/ mload(0xc20), sub( PRIME, mulmod( mulmod( /*intermediate_value/after_lin_transform5_b_0*/ mload(0xe20), /*intermediate_value/after_lin_transform5_b_0*/ mload(0xe20), PRIME), /*intermediate_value/after_lin_transform5_b_0*/ mload(0xe20), PRIME)), PRIME) // Numerator: 1. // val *= 1. // val := mulmod(val, 1, PRIME). // Denominator: point^trace_length - 1. // val *= denominator_invs[0]. val := mulmod(val, mload(0xf80), PRIME) // res += val * (coefficients[22] + coefficients[23] * adjustments[0]). res := addmod(res, mulmod(val, add(/*coefficients[22]*/ mload(0x6a0), mulmod(/*coefficients[23]*/ mload(0x6c0), /*adjustments[0]*/mload(0x1060), PRIME)), PRIME), PRIME) } { // Constraint expression for step6_a: column7_row0 - after_lin_transform6_a_0 * after_lin_transform6_a_0 * after_lin_transform6_a_0. let val := addmod( /*column7_row0*/ mload(0xae0), sub( PRIME, mulmod( mulmod( /*intermediate_value/after_lin_transform6_a_0*/ mload(0xe40), /*intermediate_value/after_lin_transform6_a_0*/ mload(0xe40), PRIME), /*intermediate_value/after_lin_transform6_a_0*/ mload(0xe40), PRIME)), PRIME) // Numerator: 1. // val *= 1. // val := mulmod(val, 1, PRIME). // Denominator: point^trace_length - 1. // val *= denominator_invs[0]. val := mulmod(val, mload(0xf80), PRIME) // res += val * (coefficients[24] + coefficients[25] * adjustments[0]). res := addmod(res, mulmod(val, add(/*coefficients[24]*/ mload(0x6e0), mulmod(/*coefficients[25]*/ mload(0x700), /*adjustments[0]*/mload(0x1060), PRIME)), PRIME), PRIME) } { // Constraint expression for step6_b: column17_row0 - after_lin_transform6_b_0 * after_lin_transform6_b_0 * after_lin_transform6_b_0. let val := addmod( /*column17_row0*/ mload(0xc40), sub( PRIME, mulmod( mulmod( /*intermediate_value/after_lin_transform6_b_0*/ mload(0xe60), /*intermediate_value/after_lin_transform6_b_0*/ mload(0xe60), PRIME), /*intermediate_value/after_lin_transform6_b_0*/ mload(0xe60), PRIME)), PRIME) // Numerator: 1. // val *= 1. // val := mulmod(val, 1, PRIME). // Denominator: point^trace_length - 1. // val *= denominator_invs[0]. val := mulmod(val, mload(0xf80), PRIME) // res += val * (coefficients[26] + coefficients[27] * adjustments[0]). res := addmod(res, mulmod(val, add(/*coefficients[26]*/ mload(0x720), mulmod(/*coefficients[27]*/ mload(0x740), /*adjustments[0]*/mload(0x1060), PRIME)), PRIME), PRIME) } { // Constraint expression for step7_a: column8_row0 - after_lin_transform7_a_0 * after_lin_transform7_a_0 * after_lin_transform7_a_0. let val := addmod( /*column8_row0*/ mload(0xb00), sub( PRIME, mulmod( mulmod( /*intermediate_value/after_lin_transform7_a_0*/ mload(0xe80), /*intermediate_value/after_lin_transform7_a_0*/ mload(0xe80), PRIME), /*intermediate_value/after_lin_transform7_a_0*/ mload(0xe80), PRIME)), PRIME) // Numerator: 1. // val *= 1. // val := mulmod(val, 1, PRIME). // Denominator: point^trace_length - 1. // val *= denominator_invs[0]. val := mulmod(val, mload(0xf80), PRIME) // res += val * (coefficients[28] + coefficients[29] * adjustments[0]). res := addmod(res, mulmod(val, add(/*coefficients[28]*/ mload(0x760), mulmod(/*coefficients[29]*/ mload(0x780), /*adjustments[0]*/mload(0x1060), PRIME)), PRIME), PRIME) } { // Constraint expression for step7_b: column18_row0 - after_lin_transform7_b_0 * after_lin_transform7_b_0 * after_lin_transform7_b_0. let val := addmod( /*column18_row0*/ mload(0xc60), sub( PRIME, mulmod( mulmod( /*intermediate_value/after_lin_transform7_b_0*/ mload(0xea0), /*intermediate_value/after_lin_transform7_b_0*/ mload(0xea0), PRIME), /*intermediate_value/after_lin_transform7_b_0*/ mload(0xea0), PRIME)), PRIME) // Numerator: 1. // val *= 1. // val := mulmod(val, 1, PRIME). // Denominator: point^trace_length - 1. // val *= denominator_invs[0]. val := mulmod(val, mload(0xf80), PRIME) // res += val * (coefficients[30] + coefficients[31] * adjustments[0]). res := addmod(res, mulmod(val, add(/*coefficients[30]*/ mload(0x7a0), mulmod(/*coefficients[31]*/ mload(0x7c0), /*adjustments[0]*/mload(0x1060), PRIME)), PRIME), PRIME) } { // Constraint expression for step8_a: column9_row0 - after_lin_transform8_a_0 * after_lin_transform8_a_0 * after_lin_transform8_a_0. let val := addmod( /*column9_row0*/ mload(0xb20), sub( PRIME, mulmod( mulmod( /*intermediate_value/after_lin_transform8_a_0*/ mload(0xec0), /*intermediate_value/after_lin_transform8_a_0*/ mload(0xec0), PRIME), /*intermediate_value/after_lin_transform8_a_0*/ mload(0xec0), PRIME)), PRIME) // Numerator: 1. // val *= 1. // val := mulmod(val, 1, PRIME). // Denominator: point^trace_length - 1. // val *= denominator_invs[0]. val := mulmod(val, mload(0xf80), PRIME) // res += val * (coefficients[32] + coefficients[33] * adjustments[0]). res := addmod(res, mulmod(val, add(/*coefficients[32]*/ mload(0x7e0), mulmod(/*coefficients[33]*/ mload(0x800), /*adjustments[0]*/mload(0x1060), PRIME)), PRIME), PRIME) } { // Constraint expression for step8_b: column19_row0 - after_lin_transform8_b_0 * after_lin_transform8_b_0 * after_lin_transform8_b_0. let val := addmod( /*column19_row0*/ mload(0xc80), sub( PRIME, mulmod( mulmod( /*intermediate_value/after_lin_transform8_b_0*/ mload(0xee0), /*intermediate_value/after_lin_transform8_b_0*/ mload(0xee0), PRIME), /*intermediate_value/after_lin_transform8_b_0*/ mload(0xee0), PRIME)), PRIME) // Numerator: 1. // val *= 1. // val := mulmod(val, 1, PRIME). // Denominator: point^trace_length - 1. // val *= denominator_invs[0]. val := mulmod(val, mload(0xf80), PRIME) // res += val * (coefficients[34] + coefficients[35] * adjustments[0]). res := addmod(res, mulmod(val, add(/*coefficients[34]*/ mload(0x820), mulmod(/*coefficients[35]*/ mload(0x840), /*adjustments[0]*/mload(0x1060), PRIME)), PRIME), PRIME) } { // Constraint expression for step9_a: column0_row1 - after_lin_transform9_a_0 * after_lin_transform9_a_0 * after_lin_transform9_a_0. let val := addmod( /*column0_row1*/ mload(0xa00), sub( PRIME, mulmod( mulmod( /*intermediate_value/after_lin_transform9_a_0*/ mload(0xf00), /*intermediate_value/after_lin_transform9_a_0*/ mload(0xf00), PRIME), /*intermediate_value/after_lin_transform9_a_0*/ mload(0xf00), PRIME)), PRIME) // Numerator: point - trace_generator^(trace_length - 1). // val *= numerators[0]. val := mulmod(val, mload(0x1040), PRIME) // Denominator: point^trace_length - 1. // val *= denominator_invs[0]. val := mulmod(val, mload(0xf80), PRIME) // res += val * (coefficients[36] + coefficients[37] * adjustments[1]). res := addmod(res, mulmod(val, add(/*coefficients[36]*/ mload(0x860), mulmod(/*coefficients[37]*/ mload(0x880), /*adjustments[1]*/mload(0x1080), PRIME)), PRIME), PRIME) } { // Constraint expression for step9_b: column10_row1 - after_lin_transform9_b_0 * after_lin_transform9_b_0 * after_lin_transform9_b_0. let val := addmod( /*column10_row1*/ mload(0xb60), sub( PRIME, mulmod( mulmod( /*intermediate_value/after_lin_transform9_b_0*/ mload(0xf20), /*intermediate_value/after_lin_transform9_b_0*/ mload(0xf20), PRIME), /*intermediate_value/after_lin_transform9_b_0*/ mload(0xf20), PRIME)), PRIME) // Numerator: point - trace_generator^(trace_length - 1). // val *= numerators[0]. val := mulmod(val, mload(0x1040), PRIME) // Denominator: point^trace_length - 1. // val *= denominator_invs[0]. val := mulmod(val, mload(0xf80), PRIME) // res += val * (coefficients[38] + coefficients[39] * adjustments[1]). res := addmod(res, mulmod(val, add(/*coefficients[38]*/ mload(0x8a0), mulmod(/*coefficients[39]*/ mload(0x8c0), /*adjustments[1]*/mload(0x1080), PRIME)), PRIME), PRIME) } { // Constraint expression for input_a: column0_row0 - input_value_a. let val := addmod(/*column0_row0*/ mload(0x9e0), sub(PRIME, /*input_value_a*/ mload(0x320)), PRIME) // Numerator: 1. // val *= 1. // val := mulmod(val, 1, PRIME). // Denominator: point - 1. // val *= denominator_invs[1]. val := mulmod(val, mload(0xfa0), PRIME) // res += val * (coefficients[40] + coefficients[41] * adjustments[2]). res := addmod(res, mulmod(val, add(/*coefficients[40]*/ mload(0x8e0), mulmod(/*coefficients[41]*/ mload(0x900), /*adjustments[2]*/mload(0x10a0), PRIME)), PRIME), PRIME) } { // Constraint expression for output_a: column9_row0 - output_value_a. let val := addmod(/*column9_row0*/ mload(0xb20), sub(PRIME, /*output_value_a*/ mload(0x340)), PRIME) // Numerator: 1. // val *= 1. // val := mulmod(val, 1, PRIME). // Denominator: point - trace_generator^(trace_length - 1). // val *= denominator_invs[2]. val := mulmod(val, mload(0xfc0), PRIME) // res += val * (coefficients[42] + coefficients[43] * adjustments[2]). res := addmod(res, mulmod(val, add(/*coefficients[42]*/ mload(0x920), mulmod(/*coefficients[43]*/ mload(0x940), /*adjustments[2]*/mload(0x10a0), PRIME)), PRIME), PRIME) } { // Constraint expression for input_b: column10_row0 - input_value_b. let val := addmod(/*column10_row0*/ mload(0xb40), sub(PRIME, /*input_value_b*/ mload(0x360)), PRIME) // Numerator: 1. // val *= 1. // val := mulmod(val, 1, PRIME). // Denominator: point - 1. // val *= denominator_invs[1]. val := mulmod(val, mload(0xfa0), PRIME) // res += val * (coefficients[44] + coefficients[45] * adjustments[2]). res := addmod(res, mulmod(val, add(/*coefficients[44]*/ mload(0x960), mulmod(/*coefficients[45]*/ mload(0x980), /*adjustments[2]*/mload(0x10a0), PRIME)), PRIME), PRIME) } { // Constraint expression for output_b: column19_row0 - output_value_b. let val := addmod(/*column19_row0*/ mload(0xc80), sub(PRIME, /*output_value_b*/ mload(0x380)), PRIME) // Numerator: 1. // val *= 1. // val := mulmod(val, 1, PRIME). // Denominator: point - trace_generator^(trace_length - 1). // val *= denominator_invs[2]. val := mulmod(val, mload(0xfc0), PRIME) // res += val * (coefficients[46] + coefficients[47] * adjustments[2]). res := addmod(res, mulmod(val, add(/*coefficients[46]*/ mload(0x9a0), mulmod(/*coefficients[47]*/ mload(0x9c0), /*adjustments[2]*/mload(0x10a0), PRIME)), PRIME), PRIME) } mstore(0, res) return(0, 0x20) } } } } contract PeriodicColumnContract { function compute(uint256 x) external pure returns (uint256 result); } contract PrimeFieldElement6 { uint256 internal constant K_MODULUS = 0x30000003000000010000000000000001; uint256 internal constant K_MODULUS_MASK = 0x3fffffffffffffffffffffffffffffff; uint256 internal constant K_MONTGOMERY_R = 0xffffff0fffffffafffffffffffffffb; uint256 internal constant K_MONTGOMERY_R_INV = 0x9000001200000096000000600000001; uint256 internal constant GENERATOR_VAL = 3; uint256 internal constant ONE_VAL = 1; uint256 internal constant GEN1024_VAL = 0x2361be682e1cc2d366e86e194024739f; function fromMontgomery(uint256 val) internal pure returns (uint256 res) { // uint256 res = fmul(val, kMontgomeryRInv); assembly { res := mulmod( val, 0x9000001200000096000000600000001, 0x30000003000000010000000000000001 ) } return res; } function fromMontgomeryBytes(bytes32 bs) internal pure returns (uint256) { // Assuming bs is a 256bit bytes object, in Montgomery form, it is read into a field // element. uint256 res = uint256(bs); return fromMontgomery(res); } function toMontgomeryInt(uint256 val) internal pure returns (uint256 res) { //uint256 res = fmul(val, kMontgomeryR); assembly { res := mulmod( val, 0xffffff0fffffffafffffffffffffffb, 0x30000003000000010000000000000001 ) } return res; } function fmul(uint256 a, uint256 b) internal pure returns (uint256 res) { //uint256 res = mulmod(a, b, kModulus); assembly { res := mulmod(a, b, 0x30000003000000010000000000000001) } return res; } function fadd(uint256 a, uint256 b) internal pure returns (uint256 res) { // uint256 res = addmod(a, b, kModulus); assembly { res := addmod(a, b, 0x30000003000000010000000000000001) } return res; } function fsub(uint256 a, uint256 b) internal pure returns (uint256 res) { // uint256 res = addmod(a, kModulus - b, kModulus); assembly { res := addmod( a, sub(0x30000003000000010000000000000001, b), 0x30000003000000010000000000000001 ) } return res; } function fpow(uint256 val, uint256 exp) internal returns (uint256) { return expmod(val, exp, K_MODULUS); } function expmod(uint256 base, uint256 exponent, uint256 modulus) internal returns (uint256 res) { assembly { let p := mload(0x40) mstore(p, 0x20) // Length of Base. mstore(add(p, 0x20), 0x20) // Length of Exponent. mstore(add(p, 0x40), 0x20) // Length of Modulus. mstore(add(p, 0x60), base) // Base. mstore(add(p, 0x80), exponent) // Exponent. mstore(add(p, 0xa0), modulus) // Modulus. // Call modexp precompile. if iszero(call(not(0), 0x05, 0, p, 0xc0, p, 0x20)) { revert(0, 0) } res := mload(p) } } function inverse(uint256 val) internal returns (uint256) { return expmod(val, K_MODULUS - 2, K_MODULUS); } } contract Prng is PrimeFieldElement6 { function storePrng(uint256 statePtr, bytes32 digest, uint256 counter) internal pure { assembly { mstore(statePtr, digest) mstore(add(statePtr, 0x20), counter) } } function loadPrng(uint256 statePtr) internal pure returns (bytes32, uint256) { bytes32 digest; uint256 counter; assembly { digest := mload(statePtr) counter := mload(add(statePtr, 0x20)) } return (digest, counter); } function initPrng(uint256 prngPtr, bytes32 publicInputHash) internal pure { storePrng(prngPtr, /*keccak256(publicInput)*/ publicInputHash, 0); } /* Auxiliary function for getRandomBytes. */ function getRandomBytesInner(bytes32 digest, uint256 counter) internal pure returns (bytes32, uint256, bytes32) { // returns 32 bytes (for random field elements or four queries at a time). bytes32 randomBytes = keccak256(abi.encodePacked(digest, counter)); return (digest, counter + 1, randomBytes); } /* Returns 32 bytes. Used for a random field element, or for 4 query indices. */ function getRandomBytes(uint256 prngPtr) internal pure returns (bytes32 randomBytes) { bytes32 digest; uint256 counter; (digest, counter) = loadPrng(prngPtr); // returns 32 bytes (for random field elements or four queries at a time). (digest, counter, randomBytes) = getRandomBytesInner(digest, counter); storePrng(prngPtr, digest, counter); return randomBytes; } function mixSeedWithBytes(uint256 prngPtr, bytes memory dataBytes) internal pure { bytes32 digest; assembly { digest := mload(prngPtr) } initPrng(prngPtr, keccak256(abi.encodePacked(digest, dataBytes))); } function getPrngDigest(uint256 prngPtr) internal pure returns (bytes32 digest) { assembly { digest := mload(prngPtr) } } } contract PublicInputOffsets { // The following constants are offsets of data expected in the public input. uint256 internal constant OFFSET_LOG_TRACE_LENGTH = 0; uint256 internal constant OFFSET_VDF_OUTPUT_X = 1; uint256 internal constant OFFSET_VDF_OUTPUT_Y = 2; uint256 internal constant OFFSET_VDF_INPUT_X = 3; uint256 internal constant OFFSET_VDF_INPUT_Y = 4; // The Verifier derives the number of iterations from the log of the trace length. // The Vending contract uses the number of iterations. uint256 internal constant OFFSET_N_ITER = 0; } contract StarkParameters is PrimeFieldElement6 { uint256 constant internal N_COEFFICIENTS = 48; uint256 constant internal MASK_SIZE = 22; uint256 constant internal N_ROWS_IN_MASK = 2; uint256 constant internal N_COLUMNS_IN_MASK = 20; uint256 constant internal CONSTRAINTS_DEGREE_BOUND = 2; uint256 constant internal N_OODS_VALUES = MASK_SIZE + CONSTRAINTS_DEGREE_BOUND; uint256 constant internal N_OODS_COEFFICIENTS = N_OODS_VALUES; uint256 constant internal MAX_FRI_STEP = 3; } contract VerifierChannel is Prng { /* We store the state of the channel in uint256[3] as follows: [0] proof pointer. [1] prng digest. [2] prng counter. */ uint256 constant internal CHANNEL_STATE_SIZE = 3; event LogValue(bytes32 val); event SendRandomnessEvent(uint256 val); event ReadFieldElementEvent(uint256 val); event ReadHashEvent(bytes32 val); function getPrngPtr(uint256 channelPtr) internal pure returns (uint256) { return channelPtr + 0x20; } function initChannel(uint256 channelPtr, uint256 proofPtr, bytes32 publicInputHash) internal pure { assembly { // Skip 0x20 bytes length at the beginning of the proof. mstore(channelPtr, add(proofPtr, 0x20)) } initPrng(getPrngPtr(channelPtr), publicInputHash); } function sendFieldElements(uint256 channelPtr, uint256 nElements, uint256 targetPtr) internal pure { require(nElements < 0x1000000, "Overflow protection failed."); assembly { let PRIME := 0x30000003000000010000000000000001 let PRIME_MON_R_INV := 0x9000001200000096000000600000001 let PRIME_MASK := 0x3fffffffffffffffffffffffffffffff let digestPtr := add(channelPtr, 0x20) let counterPtr := add(channelPtr, 0x40) let endPtr := add(targetPtr, mul(nElements, 0x20)) for { } lt(targetPtr, endPtr) { targetPtr := add(targetPtr, 0x20) } { // *targetPtr = getRandomFieldElement(getPrngPtr(channelPtr)); let fieldElement := PRIME // while (fieldElement >= PRIME). for { } iszero(lt(fieldElement, PRIME)) { } { // keccak256(abi.encodePacked(digest, counter)); fieldElement := and(keccak256(digestPtr, 0x40), PRIME_MASK) // *counterPtr += 1; mstore(counterPtr, add(mload(counterPtr), 1)) } // *targetPtr = fromMontgomery(fieldElement); mstore(targetPtr, mulmod(fieldElement, PRIME_MON_R_INV, PRIME)) // emit ReadFieldElementEvent(fieldElement); // log1(targetPtr, 0x20, 0x4bfcc54f35095697be2d635fb0706801e13637312eff0cedcdfc254b3b8c385e); } } } /* Sends random queries and returns an array of queries sorted in ascending order. Generates count queries in the range [0, mask] and returns the number of unique queries. Note that mask is of the form 2^k-1 (for some k). Note that queriesOutPtr may be (and is) inteleaved with other arrays. The stride parameter is passed to indicate the distance between every two entries to the queries array, i.e. stride = 0x20*(number of interleaved arrays). */ function sendRandomQueries( uint256 channelPtr, uint256 count, uint256 mask, uint256 queriesOutPtr, uint256 stride) internal pure returns (uint256) { uint256 val; uint256 shift = 0; uint256 endPtr = queriesOutPtr; for (uint256 i = 0; i < count; i++) { if (shift == 0) { val = uint256(getRandomBytes(getPrngPtr(channelPtr))); shift = 0x100; } shift -= 0x40; uint256 queryIdx = (val >> shift) & mask; // emit sendRandomnessEvent(queryIdx); uint256 ptr = endPtr; uint256 curr; // Insert new queryIdx in the correct place like insertion sort. while (ptr > queriesOutPtr) { assembly { curr := mload(sub(ptr, stride)) } if (queryIdx >= curr) { break; } assembly { mstore(ptr, curr) } ptr -= stride; } if (queryIdx != curr) { assembly { mstore(ptr, queryIdx) } endPtr += stride; } else { // Revert right shuffling. while (ptr < endPtr) { assembly { mstore(ptr, mload(add(ptr, stride))) ptr := add(ptr, stride) } } } } return (endPtr - queriesOutPtr) / stride; } function readBytes(uint256 channelPtr, bool mix) internal pure returns (bytes32) { uint256 proofPtr; bytes32 val; assembly { proofPtr := mload(channelPtr) val := mload(proofPtr) mstore(channelPtr, add(proofPtr, 0x20)) } if (mix) { // inline: Prng.mixSeedWithBytes(getPrngPtr(channelPtr), abi.encodePacked(val)); assembly { let digestPtr := add(channelPtr, 0x20) let counterPtr := add(digestPtr, 0x20) mstore(counterPtr, val) // prng.digest := keccak256(digest||val), nonce was written earlier. mstore(digestPtr, keccak256(digestPtr, 0x40)) // prng.counter := 0. mstore(counterPtr, 0) } } return val; } function readHash(uint256 channelPtr, bool mix) internal pure returns (bytes32) { bytes32 val = readBytes(channelPtr, mix); // emit ReadHashEvent(val); return val; } function readFieldElement(uint256 channelPtr, bool mix) internal pure returns (uint256) { uint256 val = fromMontgomery(uint256(readBytes(channelPtr, mix))); // emit ReadFieldElementEvent(val); return val; } function verifyProofOfWork(uint256 channelPtr, uint256 proofOfWorkBits) internal pure { if (proofOfWorkBits == 0) { return; } uint256 proofOfWorkDigest; assembly { // [0:29] := 0123456789abcded || digest || workBits. mstore(0, 0x0123456789abcded000000000000000000000000000000000000000000000000) let digest := mload(add(channelPtr, 0x20)) mstore(0x8, digest) mstore8(0x28, proofOfWorkBits) mstore(0, keccak256(0, 0x29)) let proofPtr := mload(channelPtr) mstore(0x20, mload(proofPtr)) // proofOfWorkDigest:= keccak256(keccak256(0123456789abcded || digest || workBits) || nonce). proofOfWorkDigest := keccak256(0, 0x28) mstore(0, digest) // prng.digest := keccak256(digest||nonce), nonce was written earlier. mstore(add(channelPtr, 0x20), keccak256(0, 0x28)) // prng.counter := 0. mstore(add(channelPtr, 0x40), 0) mstore(channelPtr, add(proofPtr, 0x8)) } uint256 proofOfWorkThreshold = uint256(1) << (256 - proofOfWorkBits); require(proofOfWorkDigest < proofOfWorkThreshold, "Proof of work check failed."); } } contract FactRegistry is IQueryableFactRegistry { // Mapping: fact hash -> true. mapping (bytes32 => bool) private verifiedFact; // Indicates whether the Fact Registry has at least one fact registered. bool anyFactRegistered; /* Checks if a fact has been verified. */ function isValid(bytes32 fact) external view returns(bool) { return verifiedFact[fact]; } function registerFact( bytes32 factHash ) internal { // This function stores the testiment hash in the mapping. verifiedFact[factHash] = true; // Mark first time off. if (!anyFactRegistered) { anyFactRegistered = true; } } /* Indicates whether at least one fact was registered. */ function hasRegisteredFact() external view returns(bool) { return anyFactRegistered; } } contract FriLayer is MerkleVerifier, PrimeFieldElement6 { event LogGas(string name, uint256 val); uint256 constant internal FRI_MAX_FRI_STEP = 4; uint256 constant internal MAX_COSET_SIZE = 2**FRI_MAX_FRI_STEP; // Generator of the group of size MAX_COSET_SIZE: GENERATOR_VAL**((PRIME - 1)/MAX_COSET_SIZE). uint256 constant internal FRI_GROUP_GEN = 0x1388a7fd3b4b9599dc4b0691d6a5fcba; uint256 constant internal FRI_GROUP_SIZE = 0x20 * MAX_COSET_SIZE; uint256 constant internal FRI_CTX_TO_COSET_EVALUATIONS_OFFSET = 0; uint256 constant internal FRI_CTX_TO_FRI_GROUP_OFFSET = FRI_GROUP_SIZE; uint256 constant internal FRI_CTX_TO_FRI_HALF_INV_GROUP_OFFSET = FRI_CTX_TO_FRI_GROUP_OFFSET + FRI_GROUP_SIZE; uint256 constant internal FRI_CTX_SIZE = FRI_CTX_TO_FRI_HALF_INV_GROUP_OFFSET + (FRI_GROUP_SIZE / 2); function nextLayerElementFromTwoPreviousLayerElements( uint256 fX, uint256 fMinusX, uint256 evalPoint, uint256 xInv) internal pure returns (uint256 res) { // Folding formula: // f(x) = g(x^2) + xh(x^2) // f(-x) = g((-x)^2) - xh((-x)^2) = g(x^2) - xh(x^2) // => // 2g(x^2) = f(x) + f(-x) // 2h(x^2) = (f(x) - f(-x))/x // => The 2*interpolation at evalPoint is: // 2*(g(x^2) + evalPoint*h(x^2)) = f(x) + f(-x) + evalPoint*(f(x) - f(-x))*xInv. // // Note that multiplying by 2 doesn't affect the degree, // so we can just agree to do that on both the prover and verifier. assembly { // PRIME is PrimeFieldElement6.K_MODULUS. let PRIME := 0x30000003000000010000000000000001 // Note that whenever we call add(), the result is always less than 2*PRIME, // so there are no overflows. res := addmod(add(fX, fMinusX), mulmod(mulmod(evalPoint, xInv, PRIME), add(fX, /*-fMinusX*/sub(PRIME, fMinusX)), PRIME), PRIME) } } /* Reads 4 elements, and applies 2 + 1 FRI transformations to obtain a single element. FRI layer n: f0 f1 f2 f3 ----------------------------------------- \ / -- \ / ----------- FRI layer n+1: f0 f2 -------------------------------------------- \ ---/ ------------- FRI layer n+2: f0 The basic FRI transformation is described in nextLayerElementFromTwoPreviousLayerElements(). */ function do2FriSteps( uint256 friHalfInvGroupPtr, uint256 evaluationsOnCosetPtr, uint256 cosetOffset_, uint256 friEvalPoint) internal pure returns (uint256 nextLayerValue, uint256 nextXInv) { assembly { let PRIME := 0x30000003000000010000000000000001 let friEvalPointDivByX := mulmod(friEvalPoint, cosetOffset_, PRIME) let f0 := mload(evaluationsOnCosetPtr) { let f1 := mload(add(evaluationsOnCosetPtr, 0x20)) // f0 < 3P ( = 1 + 1 + 1). f0 := add(add(f0, f1), mulmod(friEvalPointDivByX, add(f0, /*-fMinusX*/sub(PRIME, f1)), PRIME)) } let f2 := mload(add(evaluationsOnCosetPtr, 0x40)) { let f3 := mload(add(evaluationsOnCosetPtr, 0x60)) f2 := addmod(add(f2, f3), mulmod(add(f2, /*-fMinusX*/sub(PRIME, f3)), mulmod(mload(add(friHalfInvGroupPtr, 0x20)), friEvalPointDivByX, PRIME), PRIME), PRIME) } { let newXInv := mulmod(cosetOffset_, cosetOffset_, PRIME) nextXInv := mulmod(newXInv, newXInv, PRIME) } // f0 + f2 < 4P ( = 3 + 1). nextLayerValue := addmod(add(f0, f2), mulmod(mulmod(friEvalPointDivByX, friEvalPointDivByX, PRIME), add(f0, /*-fMinusX*/sub(PRIME, f2)), PRIME), PRIME) } } /* Reads 8 elements, and applies 4 + 2 + 1 FRI transformation to obtain a single element. See do2FriSteps for more detailed explanation. */ function do3FriSteps( uint256 friHalfInvGroupPtr, uint256 evaluationsOnCosetPtr, uint256 cosetOffset_, uint256 friEvalPoint) internal pure returns (uint256 nextLayerValue, uint256 nextXInv) { assembly { let PRIME := 0x30000003000000010000000000000001 let MPRIME := 0x300000030000000100000000000000010 let f0 := mload(evaluationsOnCosetPtr) let friEvalPointDivByX := mulmod(friEvalPoint, cosetOffset_, PRIME) let friEvalPointDivByXSquared := mulmod(friEvalPointDivByX, friEvalPointDivByX, PRIME) let imaginaryUnit := mload(add(friHalfInvGroupPtr, 0x20)) { let f1 := mload(add(evaluationsOnCosetPtr, 0x20)) // f0 < 3P ( = 1 + 1 + 1). f0 := add(add(f0, f1), mulmod(friEvalPointDivByX, add(f0, /*-fMinusX*/sub(PRIME, f1)), PRIME)) } { let f2 := mload(add(evaluationsOnCosetPtr, 0x40)) { let f3 := mload(add(evaluationsOnCosetPtr, 0x60)) // f2 < 3P ( = 1 + 1 + 1). f2 := add(add(f2, f3), mulmod(add(f2, /*-fMinusX*/sub(PRIME, f3)), mulmod(friEvalPointDivByX, imaginaryUnit, PRIME), PRIME)) } // f0 < 7P ( = 3 + 3 + 1). f0 := add(add(f0, f2), mulmod(friEvalPointDivByXSquared, add(f0, /*-fMinusX*/sub(MPRIME, f2)), PRIME)) } { let f4 := mload(add(evaluationsOnCosetPtr, 0x80)) { let friEvalPointDivByX2 := mulmod(friEvalPointDivByX, mload(add(friHalfInvGroupPtr, 0x40)), PRIME) { let f5 := mload(add(evaluationsOnCosetPtr, 0xa0)) // f4 < 3P ( = 1 + 1 + 1). f4 := add(add(f4, f5), mulmod(friEvalPointDivByX2, add(f4, /*-fMinusX*/sub(PRIME, f5)), PRIME)) } let f6 := mload(add(evaluationsOnCosetPtr, 0xc0)) { let f7 := mload(add(evaluationsOnCosetPtr, 0xe0)) // f6 < 3P ( = 1 + 1 + 1). f6 := add(add(f6, f7), mulmod(add(f6, /*-fMinusX*/sub(PRIME, f7)), // friEvalPointDivByX2 * imaginaryUnit == // friEvalPointDivByX * mload(add(friHalfInvGroupPtr, 0x60)). mulmod(friEvalPointDivByX2, imaginaryUnit, PRIME), PRIME)) } // f4 < 7P ( = 3 + 3 + 1). f4 := add(add(f4, f6), mulmod(mulmod(friEvalPointDivByX2, friEvalPointDivByX2, PRIME), add(f4, /*-fMinusX*/sub(MPRIME, f6)), PRIME)) } // f0, f4 < 7P -> f0 + f4 < 14P && 9P < f0 + (MPRIME - f4) < 23P. nextLayerValue := addmod(add(f0, f4), mulmod(mulmod(friEvalPointDivByXSquared, friEvalPointDivByXSquared, PRIME), add(f0, /*-fMinusX*/sub(MPRIME, f4)), PRIME), PRIME) } { let xInv2 := mulmod(cosetOffset_, cosetOffset_, PRIME) let xInv4 := mulmod(xInv2, xInv2, PRIME) nextXInv := mulmod(xInv4, xInv4, PRIME) } } } /* This function reads 16 elements, and applies 8 + 4 + 2 + 1 fri transformation to obtain a single element. See do2FriSteps for more detailed explanation. */ function do4FriSteps( uint256 friHalfInvGroupPtr, uint256 evaluationsOnCosetPtr, uint256 cosetOffset_, uint256 friEvalPoint) internal pure returns (uint256 nextLayerValue, uint256 nextXInv) { assembly { let friEvalPointDivByXTessed let PRIME := 0x30000003000000010000000000000001 let MPRIME := 0x300000030000000100000000000000010 let f0 := mload(evaluationsOnCosetPtr) let friEvalPointDivByX := mulmod(friEvalPoint, cosetOffset_, PRIME) let imaginaryUnit := mload(add(friHalfInvGroupPtr, 0x20)) { let f1 := mload(add(evaluationsOnCosetPtr, 0x20)) // f0 < 3P ( = 1 + 1 + 1). f0 := add(add(f0, f1), mulmod(friEvalPointDivByX, add(f0, /*-fMinusX*/sub(PRIME, f1)), PRIME)) } { let f2 := mload(add(evaluationsOnCosetPtr, 0x40)) { let f3 := mload(add(evaluationsOnCosetPtr, 0x60)) // f2 < 3P ( = 1 + 1 + 1). f2 := add(add(f2, f3), mulmod(add(f2, /*-fMinusX*/sub(PRIME, f3)), mulmod(friEvalPointDivByX, imaginaryUnit, PRIME), PRIME)) } { let friEvalPointDivByXSquared := mulmod(friEvalPointDivByX, friEvalPointDivByX, PRIME) friEvalPointDivByXTessed := mulmod(friEvalPointDivByXSquared, friEvalPointDivByXSquared, PRIME) // f0 < 7P ( = 3 + 3 + 1). f0 := add(add(f0, f2), mulmod(friEvalPointDivByXSquared, add(f0, /*-fMinusX*/sub(MPRIME, f2)), PRIME)) } } { let f4 := mload(add(evaluationsOnCosetPtr, 0x80)) { let friEvalPointDivByX2 := mulmod(friEvalPointDivByX, mload(add(friHalfInvGroupPtr, 0x40)), PRIME) { let f5 := mload(add(evaluationsOnCosetPtr, 0xa0)) // f4 < 3P ( = 1 + 1 + 1). f4 := add(add(f4, f5), mulmod(friEvalPointDivByX2, add(f4, /*-fMinusX*/sub(PRIME, f5)), PRIME)) } let f6 := mload(add(evaluationsOnCosetPtr, 0xc0)) { let f7 := mload(add(evaluationsOnCosetPtr, 0xe0)) // f6 < 3P ( = 1 + 1 + 1). f6 := add(add(f6, f7), mulmod(add(f6, /*-fMinusX*/sub(PRIME, f7)), // friEvalPointDivByX2 * imaginaryUnit == // friEvalPointDivByX * mload(add(friHalfInvGroupPtr, 0x60)). mulmod(friEvalPointDivByX2, imaginaryUnit, PRIME), PRIME)) } // f4 < 7P ( = 3 + 3 + 1). f4 := add(add(f4, f6), mulmod(mulmod(friEvalPointDivByX2, friEvalPointDivByX2, PRIME), add(f4, /*-fMinusX*/sub(MPRIME, f6)), PRIME)) } // f0 < 15P ( = 7 + 7 + 1). f0 := add(add(f0, f4), mulmod(friEvalPointDivByXTessed, add(f0, /*-fMinusX*/sub(MPRIME, f4)), PRIME)) } { let f8 := mload(add(evaluationsOnCosetPtr, 0x100)) { let friEvalPointDivByX4 := mulmod(friEvalPointDivByX, mload(add(friHalfInvGroupPtr, 0x80)), PRIME) { let f9 := mload(add(evaluationsOnCosetPtr, 0x120)) // f8 < 3P ( = 1 + 1 + 1). f8 := add(add(f8, f9), mulmod(friEvalPointDivByX4, add(f8, /*-fMinusX*/sub(PRIME, f9)), PRIME)) } let f10 := mload(add(evaluationsOnCosetPtr, 0x140)) { let f11 := mload(add(evaluationsOnCosetPtr, 0x160)) // f10 < 3P ( = 1 + 1 + 1). f10 := add(add(f10, f11), mulmod(add(f10, /*-fMinusX*/sub(PRIME, f11)), // friEvalPointDivByX4 * imaginaryUnit == // friEvalPointDivByX * mload(add(friHalfInvGroupPtr, 0xa0)). mulmod(friEvalPointDivByX4, imaginaryUnit, PRIME), PRIME)) } // f8 < 7P ( = 3 + 3 + 1). f8 := add(add(f8, f10), mulmod(mulmod(friEvalPointDivByX4, friEvalPointDivByX4, PRIME), add(f8, /*-fMinusX*/sub(MPRIME, f10)), PRIME)) } { let f12 := mload(add(evaluationsOnCosetPtr, 0x180)) { let friEvalPointDivByX6 := mulmod(friEvalPointDivByX, mload(add(friHalfInvGroupPtr, 0xc0)), PRIME) { let f13 := mload(add(evaluationsOnCosetPtr, 0x1a0)) // f12 < 3P ( = 1 + 1 + 1). f12 := add(add(f12, f13), mulmod(friEvalPointDivByX6, add(f12, /*-fMinusX*/sub(PRIME, f13)), PRIME)) } let f14 := mload(add(evaluationsOnCosetPtr, 0x1c0)) { let f15 := mload(add(evaluationsOnCosetPtr, 0x1e0)) // f14 < 3P ( = 1 + 1 + 1). f14 := add(add(f14, f15), mulmod(add(f14, /*-fMinusX*/sub(PRIME, f15)), // friEvalPointDivByX6 * imaginaryUnit == // friEvalPointDivByX * mload(add(friHalfInvGroupPtr, 0xe0)). mulmod(friEvalPointDivByX6, imaginaryUnit, PRIME), PRIME)) } // f12 < 7P ( = 3 + 3 + 1). f12 := add(add(f12, f14), mulmod(mulmod(friEvalPointDivByX6, friEvalPointDivByX6, PRIME), add(f12, /*-fMinusX*/sub(MPRIME, f14)), PRIME)) } // f8 < 15P ( = 7 + 7 + 1). f8 := add(add(f8, f12), mulmod(mulmod(friEvalPointDivByXTessed, imaginaryUnit, PRIME), add(f8, /*-fMinusX*/sub(MPRIME, f12)), PRIME)) } // f0, f8 < 15P -> f0 + f8 < 30P && 16P < f0 + (MPRIME - f8) < 31P. nextLayerValue := addmod(add(f0, f8), mulmod(mulmod(friEvalPointDivByXTessed, friEvalPointDivByXTessed, PRIME), add(f0, /*-fMinusX*/sub(MPRIME, f8)), PRIME), PRIME) } { let xInv2 := mulmod(cosetOffset_, cosetOffset_, PRIME) let xInv4 := mulmod(xInv2, xInv2, PRIME) let xInv8 := mulmod(xInv4, xInv4, PRIME) nextXInv := mulmod(xInv8, xInv8, PRIME) } } } /* Gathers the "cosetSize" elements that belong to the same coset as the item at the top of the FRI queue and stores them in ctx[MM_FRI_STEP_VALUES:]. Returns friQueueHead - friQueueHead_ + 0x60 * (# elements that were taken from the queue). cosetIdx - the start index of the coset that was gathered. cosetOffset_ - the xInv field element that corresponds to cosetIdx. */ function gatherCosetInputs( uint256 channelPtr, uint256 friCtx, uint256 friQueueHead_, uint256 cosetSize) internal pure returns (uint256 friQueueHead, uint256 cosetIdx, uint256 cosetOffset_) { uint256 evaluationsOnCosetPtr = friCtx + FRI_CTX_TO_COSET_EVALUATIONS_OFFSET; uint256 friGroupPtr = friCtx + FRI_CTX_TO_FRI_GROUP_OFFSET; friQueueHead = friQueueHead_; assembly { let queueItemIdx := mload(friQueueHead) // The coset index is represented by the most significant bits of the queue item index. cosetIdx := and(queueItemIdx, not(sub(cosetSize, 1))) let nextCosetIdx := add(cosetIdx, cosetSize) let PRIME := 0x30000003000000010000000000000001 // Get the algebraic coset offset: // I.e. given c*g^(-k) compute c, where // g is the generator of the coset group. // k is bitReverse(offsetWithinCoset, log2(cosetSize)). // // To do this we multiply the algebraic coset offset at the top of the queue (c*g^(-k)) // by the group element that corresponds to the index inside the coset (g^k). cosetOffset_ := mulmod( /*(c*g^(-k)*/ mload(add(friQueueHead, 0x40)), /*(g^k)*/ mload(add(friGroupPtr, mul(/*offsetWithinCoset*/sub(queueItemIdx, cosetIdx), 0x20))), PRIME) let proofPtr := mload(channelPtr) for { let index := cosetIdx } lt(index, nextCosetIdx) { index := add(index, 1) } { // Inline channel operation: // Assume we are going to read the next element from the proof. // If this is not the case add(proofPtr, 0x20) will be reverted. let fieldElementPtr := proofPtr proofPtr := add(proofPtr, 0x20) // Load the next index from the queue and check if it is our sibling. if eq(index, queueItemIdx) { // Take element from the queue rather than from the proof // and convert it back to Montgomery form for Merkle verification. fieldElementPtr := add(friQueueHead, 0x20) // Revert the read from proof. proofPtr := sub(proofPtr, 0x20) // Reading the next index here is safe due to the // delimiter after the queries. friQueueHead := add(friQueueHead, 0x60) queueItemIdx := mload(friQueueHead) } // Note that we apply the modulo operation to convert the field elements we read // from the proof to canonical representation (in the range [0, PRIME - 1]). mstore(evaluationsOnCosetPtr, mod(mload(fieldElementPtr), PRIME)) evaluationsOnCosetPtr := add(evaluationsOnCosetPtr, 0x20) } mstore(channelPtr, proofPtr) } } /* Returns the bit reversal of num assuming it has the given number of bits. For example, if we have numberOfBits = 6 and num = (0b)1101 == (0b)001101, the function will return (0b)101100. */ function bitReverse(uint256 num, uint256 numberOfBits) internal pure returns(uint256 numReversed) { assert((numberOfBits == 256) || (num < 2 ** numberOfBits)); uint256 n = num; uint256 r = 0; for (uint256 k = 0; k < numberOfBits; k++) { r = (r * 2) | (n % 2); n = n / 2; } return r; } /* Initializes the FRI group and half inv group in the FRI context. */ function initFriGroups(uint256 friCtx) internal { uint256 friGroupPtr = friCtx + FRI_CTX_TO_FRI_GROUP_OFFSET; uint256 friHalfInvGroupPtr = friCtx + FRI_CTX_TO_FRI_HALF_INV_GROUP_OFFSET; // FRI_GROUP_GEN is the coset generator. // Raising it to the (MAX_COSET_SIZE - 1) power gives us the inverse. uint256 genFriGroup = FRI_GROUP_GEN; uint256 genFriGroupInv = fpow(genFriGroup, (MAX_COSET_SIZE - 1)); uint256 lastVal = ONE_VAL; uint256 lastValInv = ONE_VAL; uint256 prime = PrimeFieldElement6.K_MODULUS; assembly { // ctx[mmHalfFriInvGroup + 0] = ONE_VAL; mstore(friHalfInvGroupPtr, lastValInv) // ctx[mmFriGroup + 0] = ONE_VAL; mstore(friGroupPtr, lastVal) // ctx[mmFriGroup + 1] = fsub(0, ONE_VAL); mstore(add(friGroupPtr, 0x20), sub(prime, lastVal)) } // To compute [1, -1 (== g^n/2), g^n/4, -g^n/4, ...] // we compute half the elements and derive the rest using negation. uint256 halfCosetSize = MAX_COSET_SIZE / 2; for (uint256 i = 1; i < halfCosetSize; i++) { lastVal = fmul(lastVal, genFriGroup); lastValInv = fmul(lastValInv, genFriGroupInv); uint256 idx = bitReverse(i, FRI_MAX_FRI_STEP-1); assembly { // ctx[mmHalfFriInvGroup + idx] = lastValInv; mstore(add(friHalfInvGroupPtr, mul(idx, 0x20)), lastValInv) // ctx[mmFriGroup + 2*idx] = lastVal; mstore(add(friGroupPtr, mul(idx, 0x40)), lastVal) // ctx[mmFriGroup + 2*idx + 1] = fsub(0, lastVal); mstore(add(friGroupPtr, add(mul(idx, 0x40), 0x20)), sub(prime, lastVal)) } } } /* Operates on the coset of size friFoldedCosetSize that start at index. It produces 3 outputs: 1. The field elements that result from doing FRI reductions on the coset. 2. The pointInv elements for the location that corresponds to the first output. 3. The root of a Merkle tree for the input layer. The input is read either from the queue or from the proof depending on data availability. Since the function reads from the queue it returns an updated head pointer. */ function doFriSteps( uint256 friCtx, uint256 friQueueTail, uint256 cosetOffset_, uint256 friEvalPoint, uint256 friCosetSize, uint256 index, uint256 merkleQueuePtr) internal pure { uint256 friValue; uint256 evaluationsOnCosetPtr = friCtx + FRI_CTX_TO_COSET_EVALUATIONS_OFFSET; uint256 friHalfInvGroupPtr = friCtx + FRI_CTX_TO_FRI_HALF_INV_GROUP_OFFSET; // Compare to expected FRI step sizes in order of likelihood, step size 3 being most common. if (friCosetSize == 8) { (friValue, cosetOffset_) = do3FriSteps( friHalfInvGroupPtr, evaluationsOnCosetPtr, cosetOffset_, friEvalPoint); } else if (friCosetSize == 4) { (friValue, cosetOffset_) = do2FriSteps( friHalfInvGroupPtr, evaluationsOnCosetPtr, cosetOffset_, friEvalPoint); } else if (friCosetSize == 16) { (friValue, cosetOffset_) = do4FriSteps( friHalfInvGroupPtr, evaluationsOnCosetPtr, cosetOffset_, friEvalPoint); } else { require(false, "Only step sizes of 2, 3 or 4 are supported."); } uint256 lhashMask = getHashMask(); assembly { let indexInNextStep := div(index, friCosetSize) mstore(merkleQueuePtr, indexInNextStep) mstore(add(merkleQueuePtr, 0x20), and(lhashMask, keccak256(evaluationsOnCosetPtr, mul(0x20,friCosetSize)))) mstore(friQueueTail, indexInNextStep) mstore(add(friQueueTail, 0x20), friValue) mstore(add(friQueueTail, 0x40), cosetOffset_) } } /* Computes the FRI step with eta = log2(friCosetSize) for all the live queries. The input and output data is given in array of triplets: (query index, FRI value, FRI inversed point) in the address friQueuePtr (which is &ctx[mmFriQueue:]). The function returns the number of live queries remaining after computing the FRI step. The number of live queries decreases whenever multiple query points in the same coset are reduced to a single query in the next FRI layer. As the function computes the next layer it also collects that data from the previous layer for Merkle verification. */ function computeNextLayer( uint256 channelPtr, uint256 friQueuePtr, uint256 merkleQueuePtr, uint256 nQueries, uint256 friEvalPoint, uint256 friCosetSize, uint256 friCtx) internal pure returns (uint256 nLiveQueries) { uint256 merkleQueueTail = merkleQueuePtr; uint256 friQueueHead = friQueuePtr; uint256 friQueueTail = friQueuePtr; uint256 friQueueEnd = friQueueHead + (0x60 * nQueries); do { uint256 cosetOffset; uint256 index; (friQueueHead, index, cosetOffset) = gatherCosetInputs( channelPtr, friCtx, friQueueHead, friCosetSize); doFriSteps( friCtx, friQueueTail, cosetOffset, friEvalPoint, friCosetSize, index, merkleQueueTail); merkleQueueTail += 0x40; friQueueTail += 0x60; } while (friQueueHead < friQueueEnd); return (friQueueTail - friQueuePtr) / 0x60; } } contract HornerEvaluator is PrimeFieldElement6 { /* Computes the evaluation of a polynomial f(x) = sum(a_i * x^i) on the given point. The coefficients of the polynomial are given in a_0 = coefsStart[0], ..., a_{n-1} = coefsStart[n - 1] where n = nCoefs = friLastLayerDegBound. Note that coefsStart is not actually an array but a direct pointer. The function requires that n is divisible by 8. */ function hornerEval(uint256 coefsStart, uint256 point, uint256 nCoefs) internal pure returns (uint256) { uint256 result = 0; uint256 prime = PrimeFieldElement6.K_MODULUS; require(nCoefs % 8 == 0, "Number of polynomial coefficients must be divisible by 8"); require(nCoefs < 4096, "No more than 4096 coefficients are supported"); assembly { let coefsPtr := add(coefsStart, mul(nCoefs, 0x20)) for { } gt(coefsPtr, coefsStart) { } { // Reduce coefsPtr by 8 field elements. coefsPtr := sub(coefsPtr, 0x100) // Apply 4 Horner steps (result := result * point + coef). result := add(mload(add(coefsPtr, 0x80)), mulmod( add(mload(add(coefsPtr, 0xa0)), mulmod( add(mload(add(coefsPtr, 0xc0)), mulmod( add(mload(add(coefsPtr, 0xe0)), mulmod( result, point, prime)), point, prime)), point, prime)), point, prime)) // Apply 4 additional Horner steps. result := add(mload(coefsPtr), mulmod( add(mload(add(coefsPtr, 0x20)), mulmod( add(mload(add(coefsPtr, 0x40)), mulmod( add(mload(add(coefsPtr, 0x60)), mulmod( result, point, prime)), point, prime)), point, prime)), point, prime)) } } // Since the last operation was "add" (instead of "addmod"), we need to take result % prime. return result % prime; } } contract MemoryAccessUtils is MemoryMap { function getPtr(uint256[] memory ctx, uint256 offset) internal pure returns (uint256) { uint256 ctxPtr; require(offset < MM_CONTEXT_SIZE, "Overflow protection failed"); assembly { ctxPtr := add(ctx, 0x20) } return ctxPtr + offset * 0x20; } function getProofPtr(uint256[] memory proof) internal pure returns (uint256) { uint256 proofPtr; assembly { proofPtr := proof } return proofPtr; } function getChannelPtr(uint256[] memory ctx) internal pure returns (uint256) { uint256 ctxPtr; assembly { ctxPtr := add(ctx, 0x20) } return ctxPtr + MM_CHANNEL * 0x20; } function getQueries(uint256[] memory ctx) internal pure returns (uint256[] memory) { uint256[] memory queries; // Dynamic array holds length followed by values. uint256 offset = 0x20 + 0x20*MM_N_UNIQUE_QUERIES; assembly { queries := add(ctx, offset) } return queries; } function getMerkleQueuePtr(uint256[] memory ctx) internal pure returns (uint256) { return getPtr(ctx, MM_MERKLE_QUEUE); } function getFriSteps(uint256[] memory ctx) internal pure returns (uint256[] memory friSteps) { uint256 friStepsPtr = getPtr(ctx, MM_FRI_STEPS_PTR); assembly { friSteps := mload(friStepsPtr) } } } contract MimcOods is MemoryMap, StarkParameters { // For each query point we want to invert (2 + N_ROWS_IN_MASK) items: // The query point itself (x). // The denominator for the constraint polynomial (x-z^constraintDegree) // [(x-(g^rowNumber)z) for rowNumber in mask]. uint256 constant internal BATCH_INVERSE_CHUNK = (2 + N_ROWS_IN_MASK); uint256 constant internal BATCH_INVERSE_SIZE = MAX_N_QUERIES * BATCH_INVERSE_CHUNK; /* Builds and sums boundary constraints that check that the prover provided the proper evaluations out of domain evaluations for the trace and composition columns. The inputs to this function are: The verifier context. The boundary constraints for the trace enforce claims of the form f(g^k*z) = c by requiring the quotient (f(x) - c)/(x-g^k*z) to be a low degree polynomial. The boundary constraints for the composition enforce claims of the form h(z^d) = c by requiring the quotient (h(x) - c)/(x-z^d) to be a low degree polynomial. Where: f is a trace column. h is a composition column. z is the out of domain sampling point. g is the trace generator k is the offset in the mask. d is the degree of the composition polynomial. c is the evaluation sent by the prover. */ function() external { // This funciton assumes that the calldata contains the context as defined in MemoryMap.sol. // Note that ctx is a variable size array so the first uint256 cell contrains it's length. uint256[] memory ctx; assembly { let ctxSize := mul(add(calldataload(0), 1), 0x20) ctx := mload(0x40) mstore(0x40, add(ctx, ctxSize)) calldatacopy(ctx, 0, ctxSize) } uint256[] memory batchInverseArray = new uint256[](2 * BATCH_INVERSE_SIZE); oodsPrepareInverses(ctx, batchInverseArray); uint256 kMontgomeryRInv_ = PrimeFieldElement6.K_MONTGOMERY_R_INV; assembly { let PRIME := 0x30000003000000010000000000000001 let kMontgomeryRInv := kMontgomeryRInv_ let context := ctx let friQueue := /*friQueue*/ add(context, 0xda0) let friQueueEnd := add(friQueue, mul(/*n_unique_queries*/ mload(add(context, 0x120)), 0x60)) let traceQueryResponses := /*traceQueryQesponses*/ add(context, 0x3d80) let compositionQueryResponses := /*composition_query_responses*/ add(context, 0xb580) // Set denominatorsPtr to point to the batchInverseOut array. // The content of batchInverseOut is described in oodsPrepareInverses. let denominatorsPtr := add(batchInverseArray, 0x20) for {} lt(friQueue, friQueueEnd) {friQueue := add(friQueue, 0x60)} { // res accumulates numbers modulo PRIME. Since 1814839283484201961915354863390654471405*PRIME < 2**256, we may add up to // 1814839283484201961915354863390654471405 numbers without fear of overflow, and use addmod modulo PRIME only every // 1814839283484201961915354863390654471405 iterations, and once more at the very end. let res := 0 // Trace constraints. // Mask items for column #0. { // Read the next element. let columnValue := mulmod(mload(traceQueryResponses), kMontgomeryRInv, PRIME) // res += c_0*(f_0(x) - f_0(z)) / (x - z). res := add( res, mulmod(mulmod(/*(x - z)^(-1)*/ mload(denominatorsPtr), /*oods_coefficients[0]*/ mload(add(context, 0x3a80)), PRIME), add(columnValue, sub(PRIME, /*oods_values[0]*/ mload(add(context, 0x3180)))), PRIME)) // res += c_1*(f_0(x) - f_0(g * z)) / (x - g * z). res := add( res, mulmod(mulmod(/*(x - g * z)^(-1)*/ mload(add(denominatorsPtr, 0x20)), /*oods_coefficients[1]*/ mload(add(context, 0x3aa0)), PRIME), add(columnValue, sub(PRIME, /*oods_values[1]*/ mload(add(context, 0x31a0)))), PRIME)) } // Mask items for column #1. { // Read the next element. let columnValue := mulmod(mload(add(traceQueryResponses, 0x20)), kMontgomeryRInv, PRIME) // res += c_2*(f_1(x) - f_1(z)) / (x - z). res := add( res, mulmod(mulmod(/*(x - z)^(-1)*/ mload(denominatorsPtr), /*oods_coefficients[2]*/ mload(add(context, 0x3ac0)), PRIME), add(columnValue, sub(PRIME, /*oods_values[2]*/ mload(add(context, 0x31c0)))), PRIME)) } // Mask items for column #2. { // Read the next element. let columnValue := mulmod(mload(add(traceQueryResponses, 0x40)), kMontgomeryRInv, PRIME) // res += c_3*(f_2(x) - f_2(z)) / (x - z). res := add( res, mulmod(mulmod(/*(x - z)^(-1)*/ mload(denominatorsPtr), /*oods_coefficients[3]*/ mload(add(context, 0x3ae0)), PRIME), add(columnValue, sub(PRIME, /*oods_values[3]*/ mload(add(context, 0x31e0)))), PRIME)) } // Mask items for column #3. { // Read the next element. let columnValue := mulmod(mload(add(traceQueryResponses, 0x60)), kMontgomeryRInv, PRIME) // res += c_4*(f_3(x) - f_3(z)) / (x - z). res := add( res, mulmod(mulmod(/*(x - z)^(-1)*/ mload(denominatorsPtr), /*oods_coefficients[4]*/ mload(add(context, 0x3b00)), PRIME), add(columnValue, sub(PRIME, /*oods_values[4]*/ mload(add(context, 0x3200)))), PRIME)) } // Mask items for column #4. { // Read the next element. let columnValue := mulmod(mload(add(traceQueryResponses, 0x80)), kMontgomeryRInv, PRIME) // res += c_5*(f_4(x) - f_4(z)) / (x - z). res := add( res, mulmod(mulmod(/*(x - z)^(-1)*/ mload(denominatorsPtr), /*oods_coefficients[5]*/ mload(add(context, 0x3b20)), PRIME), add(columnValue, sub(PRIME, /*oods_values[5]*/ mload(add(context, 0x3220)))), PRIME)) } // Mask items for column #5. { // Read the next element. let columnValue := mulmod(mload(add(traceQueryResponses, 0xa0)), kMontgomeryRInv, PRIME) // res += c_6*(f_5(x) - f_5(z)) / (x - z). res := add( res, mulmod(mulmod(/*(x - z)^(-1)*/ mload(denominatorsPtr), /*oods_coefficients[6]*/ mload(add(context, 0x3b40)), PRIME), add(columnValue, sub(PRIME, /*oods_values[6]*/ mload(add(context, 0x3240)))), PRIME)) } // Mask items for column #6. { // Read the next element. let columnValue := mulmod(mload(add(traceQueryResponses, 0xc0)), kMontgomeryRInv, PRIME) // res += c_7*(f_6(x) - f_6(z)) / (x - z). res := add( res, mulmod(mulmod(/*(x - z)^(-1)*/ mload(denominatorsPtr), /*oods_coefficients[7]*/ mload(add(context, 0x3b60)), PRIME), add(columnValue, sub(PRIME, /*oods_values[7]*/ mload(add(context, 0x3260)))), PRIME)) } // Mask items for column #7. { // Read the next element. let columnValue := mulmod(mload(add(traceQueryResponses, 0xe0)), kMontgomeryRInv, PRIME) // res += c_8*(f_7(x) - f_7(z)) / (x - z). res := add( res, mulmod(mulmod(/*(x - z)^(-1)*/ mload(denominatorsPtr), /*oods_coefficients[8]*/ mload(add(context, 0x3b80)), PRIME), add(columnValue, sub(PRIME, /*oods_values[8]*/ mload(add(context, 0x3280)))), PRIME)) } // Mask items for column #8. { // Read the next element. let columnValue := mulmod(mload(add(traceQueryResponses, 0x100)), kMontgomeryRInv, PRIME) // res += c_9*(f_8(x) - f_8(z)) / (x - z). res := add( res, mulmod(mulmod(/*(x - z)^(-1)*/ mload(denominatorsPtr), /*oods_coefficients[9]*/ mload(add(context, 0x3ba0)), PRIME), add(columnValue, sub(PRIME, /*oods_values[9]*/ mload(add(context, 0x32a0)))), PRIME)) } // Mask items for column #9. { // Read the next element. let columnValue := mulmod(mload(add(traceQueryResponses, 0x120)), kMontgomeryRInv, PRIME) // res += c_10*(f_9(x) - f_9(z)) / (x - z). res := add( res, mulmod(mulmod(/*(x - z)^(-1)*/ mload(denominatorsPtr), /*oods_coefficients[10]*/ mload(add(context, 0x3bc0)), PRIME), add(columnValue, sub(PRIME, /*oods_values[10]*/ mload(add(context, 0x32c0)))), PRIME)) } // Mask items for column #10. { // Read the next element. let columnValue := mulmod(mload(add(traceQueryResponses, 0x140)), kMontgomeryRInv, PRIME) // res += c_11*(f_10(x) - f_10(z)) / (x - z). res := add( res, mulmod(mulmod(/*(x - z)^(-1)*/ mload(denominatorsPtr), /*oods_coefficients[11]*/ mload(add(context, 0x3be0)), PRIME), add(columnValue, sub(PRIME, /*oods_values[11]*/ mload(add(context, 0x32e0)))), PRIME)) // res += c_12*(f_10(x) - f_10(g * z)) / (x - g * z). res := add( res, mulmod(mulmod(/*(x - g * z)^(-1)*/ mload(add(denominatorsPtr, 0x20)), /*oods_coefficients[12]*/ mload(add(context, 0x3c00)), PRIME), add(columnValue, sub(PRIME, /*oods_values[12]*/ mload(add(context, 0x3300)))), PRIME)) } // Mask items for column #11. { // Read the next element. let columnValue := mulmod(mload(add(traceQueryResponses, 0x160)), kMontgomeryRInv, PRIME) // res += c_13*(f_11(x) - f_11(z)) / (x - z). res := add( res, mulmod(mulmod(/*(x - z)^(-1)*/ mload(denominatorsPtr), /*oods_coefficients[13]*/ mload(add(context, 0x3c20)), PRIME), add(columnValue, sub(PRIME, /*oods_values[13]*/ mload(add(context, 0x3320)))), PRIME)) } // Mask items for column #12. { // Read the next element. let columnValue := mulmod(mload(add(traceQueryResponses, 0x180)), kMontgomeryRInv, PRIME) // res += c_14*(f_12(x) - f_12(z)) / (x - z). res := add( res, mulmod(mulmod(/*(x - z)^(-1)*/ mload(denominatorsPtr), /*oods_coefficients[14]*/ mload(add(context, 0x3c40)), PRIME), add(columnValue, sub(PRIME, /*oods_values[14]*/ mload(add(context, 0x3340)))), PRIME)) } // Mask items for column #13. { // Read the next element. let columnValue := mulmod(mload(add(traceQueryResponses, 0x1a0)), kMontgomeryRInv, PRIME) // res += c_15*(f_13(x) - f_13(z)) / (x - z). res := add( res, mulmod(mulmod(/*(x - z)^(-1)*/ mload(denominatorsPtr), /*oods_coefficients[15]*/ mload(add(context, 0x3c60)), PRIME), add(columnValue, sub(PRIME, /*oods_values[15]*/ mload(add(context, 0x3360)))), PRIME)) } // Mask items for column #14. { // Read the next element. let columnValue := mulmod(mload(add(traceQueryResponses, 0x1c0)), kMontgomeryRInv, PRIME) // res += c_16*(f_14(x) - f_14(z)) / (x - z). res := add( res, mulmod(mulmod(/*(x - z)^(-1)*/ mload(denominatorsPtr), /*oods_coefficients[16]*/ mload(add(context, 0x3c80)), PRIME), add(columnValue, sub(PRIME, /*oods_values[16]*/ mload(add(context, 0x3380)))), PRIME)) } // Mask items for column #15. { // Read the next element. let columnValue := mulmod(mload(add(traceQueryResponses, 0x1e0)), kMontgomeryRInv, PRIME) // res += c_17*(f_15(x) - f_15(z)) / (x - z). res := add( res, mulmod(mulmod(/*(x - z)^(-1)*/ mload(denominatorsPtr), /*oods_coefficients[17]*/ mload(add(context, 0x3ca0)), PRIME), add(columnValue, sub(PRIME, /*oods_values[17]*/ mload(add(context, 0x33a0)))), PRIME)) } // Mask items for column #16. { // Read the next element. let columnValue := mulmod(mload(add(traceQueryResponses, 0x200)), kMontgomeryRInv, PRIME) // res += c_18*(f_16(x) - f_16(z)) / (x - z). res := add( res, mulmod(mulmod(/*(x - z)^(-1)*/ mload(denominatorsPtr), /*oods_coefficients[18]*/ mload(add(context, 0x3cc0)), PRIME), add(columnValue, sub(PRIME, /*oods_values[18]*/ mload(add(context, 0x33c0)))), PRIME)) } // Mask items for column #17. { // Read the next element. let columnValue := mulmod(mload(add(traceQueryResponses, 0x220)), kMontgomeryRInv, PRIME) // res += c_19*(f_17(x) - f_17(z)) / (x - z). res := add( res, mulmod(mulmod(/*(x - z)^(-1)*/ mload(denominatorsPtr), /*oods_coefficients[19]*/ mload(add(context, 0x3ce0)), PRIME), add(columnValue, sub(PRIME, /*oods_values[19]*/ mload(add(context, 0x33e0)))), PRIME)) } // Mask items for column #18. { // Read the next element. let columnValue := mulmod(mload(add(traceQueryResponses, 0x240)), kMontgomeryRInv, PRIME) // res += c_20*(f_18(x) - f_18(z)) / (x - z). res := add( res, mulmod(mulmod(/*(x - z)^(-1)*/ mload(denominatorsPtr), /*oods_coefficients[20]*/ mload(add(context, 0x3d00)), PRIME), add(columnValue, sub(PRIME, /*oods_values[20]*/ mload(add(context, 0x3400)))), PRIME)) } // Mask items for column #19. { // Read the next element. let columnValue := mulmod(mload(add(traceQueryResponses, 0x260)), kMontgomeryRInv, PRIME) // res += c_21*(f_19(x) - f_19(z)) / (x - z). res := add( res, mulmod(mulmod(/*(x - z)^(-1)*/ mload(denominatorsPtr), /*oods_coefficients[21]*/ mload(add(context, 0x3d20)), PRIME), add(columnValue, sub(PRIME, /*oods_values[21]*/ mload(add(context, 0x3420)))), PRIME)) } // Advance traceQueryResponses by amount read (0x20 * nTraceColumns). traceQueryResponses := add(traceQueryResponses, 0x280) // Composition constraints. { // Read the next element. let columnValue := mulmod(mload(compositionQueryResponses), kMontgomeryRInv, PRIME) // res += c_22*(h_0(x) - C_0(z^2)) / (x - z^2). res := add( res, mulmod(mulmod(/*(x - z^2)^(-1)*/ mload(add(denominatorsPtr, 0x40)), /*oods_coefficients[22]*/ mload(add(context, 0x3d40)), PRIME), add(columnValue, sub(PRIME, /*composition_oods_values[0]*/ mload(add(context, 0x3440)))), PRIME)) } { // Read the next element. let columnValue := mulmod(mload(add(compositionQueryResponses, 0x20)), kMontgomeryRInv, PRIME) // res += c_23*(h_1(x) - C_1(z^2)) / (x - z^2). res := add( res, mulmod(mulmod(/*(x - z^2)^(-1)*/ mload(add(denominatorsPtr, 0x40)), /*oods_coefficients[23]*/ mload(add(context, 0x3d60)), PRIME), add(columnValue, sub(PRIME, /*composition_oods_values[1]*/ mload(add(context, 0x3460)))), PRIME)) } // Advance compositionQueryResponses by amount read (0x20 * constraintDegree). compositionQueryResponses := add(compositionQueryResponses, 0x40) // Append the friValue, which is the sum of the out-of-domain-sampling boundary // constraints for the trace and composition polynomials, to the friQueue array. mstore(add(friQueue, 0x20), mod(res, PRIME)) // Append the friInvPoint of the current query to the friQueue array. mstore(add(friQueue, 0x40), /*friInvPoint*/ mload(add(denominatorsPtr,0x60))) // Advance denominatorsPtr by chunk size (0x20 * (2+N_ROWS_IN_MASK)). denominatorsPtr := add(denominatorsPtr, 0x80) } return(/*friQueue*/ add(context, 0xda0), 0x1200) } } /* Computes and performs batch inverse on all the denominators required for the out of domain sampling boundary constraints. Since the friEvalPoints are calculated during the computation of the denominators this function also adds those to the batch inverse in prepartion for the fri that follows. After this function returns, the batch_inverse_out array holds #queries chunks of size (2 + N_ROWS_IN_MASK) with the following structure: 0..(N_ROWS_IN_MASK-1): [(x - g^i * z)^(-1) for i in rowsInMask] N_ROWS_IN_MASK: (x - z^constraintDegree)^-1 N_ROWS_IN_MASK+1: friEvalPointInv. */ function oodsPrepareInverses( uint256[] memory context, uint256[] memory batchInverseArray) internal view { uint256 evalCosetOffset_ = PrimeFieldElement6.GENERATOR_VAL; // The array expmodsAndPoints stores subexpressions that are needed // for the denominators computation. // The array is segmented as follows: // expmodsAndPoints[0:0] (.expmods) expmods used during calculations of the points below. // expmodsAndPoints[0:2] (.points) points used during the denominators calculation. uint256[2] memory expmodsAndPoints; assembly { function expmod(base, exponent, modulus) -> res { let p := mload(0x40) mstore(p, 0x20) // Length of Base. mstore(add(p, 0x20), 0x20) // Length of Exponent. mstore(add(p, 0x40), 0x20) // Length of Modulus. mstore(add(p, 0x60), base) // Base. mstore(add(p, 0x80), exponent) // Exponent. mstore(add(p, 0xa0), modulus) // Modulus. // Call modexp precompile. if iszero(staticcall(not(0), 0x05, p, 0xc0, p, 0x20)) { revert(0, 0) } res := mload(p) } let traceGenerator := /*trace_generator*/ mload(add(context, 0x2b40)) let PRIME := 0x30000003000000010000000000000001 // Prepare expmods for computations of trace generator powers. let oodsPoint := /*oods_point*/ mload(add(context, 0x2b60)) { // point = -z. let point := sub(PRIME, oodsPoint) // Compute denominators for rows with nonconst mask expression. // We compute those first because for the const rows we modify the point variable. // Compute denominators for rows with const mask expression. // expmods_and_points.points[0] = -z. mstore(add(expmodsAndPoints, 0x0), point) // point *= g. point := mulmod(point, traceGenerator, PRIME) // expmods_and_points.points[1] = -(g * z). mstore(add(expmodsAndPoints, 0x20), point) } let evalPointsPtr := /*oodsEvalPoints*/ add(context, 0x3480) let evalPointsEndPtr := add(evalPointsPtr, mul(/*n_unique_queries*/ mload(add(context, 0x120)), 0x20)) let productsPtr := add(batchInverseArray, 0x20) let valuesPtr := add(add(batchInverseArray, 0x20), 0x1800) let partialProduct := 1 let minusPointPow := sub(PRIME, mulmod(oodsPoint, oodsPoint, PRIME)) for {} lt(evalPointsPtr, evalPointsEndPtr) {evalPointsPtr := add(evalPointsPtr, 0x20)} { let evalPoint := mload(evalPointsPtr) // Shift evalPoint to evaluation domain coset. let shiftedEvalPoint := mulmod(evalPoint, evalCosetOffset_, PRIME) { // Calculate denominator for row 0: x - z. let denominator := add(shiftedEvalPoint, mload(add(expmodsAndPoints, 0x0))) mstore(productsPtr, partialProduct) mstore(valuesPtr, denominator) partialProduct := mulmod(partialProduct, denominator, PRIME) } { // Calculate denominator for row 1: x - g * z. let denominator := add(shiftedEvalPoint, mload(add(expmodsAndPoints, 0x20))) mstore(add(productsPtr, 0x20), partialProduct) mstore(add(valuesPtr, 0x20), denominator) partialProduct := mulmod(partialProduct, denominator, PRIME) } { // Calculate the denominator for the composition polynomial columns: x - z^2. let denominator := add(shiftedEvalPoint, minusPointPow) mstore(add(productsPtr, 0x40), partialProduct) mstore(add(valuesPtr, 0x40), denominator) partialProduct := mulmod(partialProduct, denominator, PRIME) } // Add evalPoint to batch inverse inputs. // inverse(evalPoint) is going to be used by FRI. mstore(add(productsPtr, 0x60), partialProduct) mstore(add(valuesPtr, 0x60), evalPoint) partialProduct := mulmod(partialProduct, evalPoint, PRIME) // Advance pointers. productsPtr := add(productsPtr, 0x80) valuesPtr := add(valuesPtr, 0x80) } let productsToValuesOffset := 0x1800 let firstPartialProductPtr := add(batchInverseArray, 0x20) // Compute the inverse of the product. let prodInv := expmod(partialProduct, sub(PRIME, 2), PRIME) if eq(prodInv, 0) { // Solidity generates reverts with reason that look as follows: // 1. 4 bytes with the constant 0x08c379a0 (== Keccak256(b'Error(string)')[:4]). // 2. 32 bytes offset bytes (always 0x20 as far as i can tell). // 3. 32 bytes with the length of the revert reason. // 4. Revert reason string. mstore(0, 0x08c379a000000000000000000000000000000000000000000000000000000000) mstore(0x4, 0x20) mstore(0x24, 0x1e) mstore(0x44, "Batch inverse product is zero.") revert(0, 0x62) } // Compute the inverses. // Loop over denominator_invs in reverse order. // currentPartialProductPtr is initialized to one past the end. let currentPartialProductPtr := productsPtr // Loop in blocks of size 8 as much as possible: we can loop over a full block as long as // currentPartialProductPtr >= firstPartialProductPtr + 8*0x20, or equivalently, // currentPartialProductPtr > firstPartialProductPtr + 7*0x20. // We use the latter comparison since there is no >= evm opcode. let midPartialProductPtr := add(firstPartialProductPtr, 0xe0) for { } gt(currentPartialProductPtr, midPartialProductPtr) { } { currentPartialProductPtr := sub(currentPartialProductPtr, 0x20) // Store 1/d_{i} = (d_0 * ... * d_{i-1}) * 1/(d_0 * ... * d_{i}). mstore(currentPartialProductPtr, mulmod(mload(currentPartialProductPtr), prodInv, PRIME)) // Update prodInv to be 1/(d_0 * ... * d_{i-1}) by multiplying by d_i. prodInv := mulmod(prodInv, mload(add(currentPartialProductPtr, productsToValuesOffset)), PRIME) currentPartialProductPtr := sub(currentPartialProductPtr, 0x20) // Store 1/d_{i} = (d_0 * ... * d_{i-1}) * 1/(d_0 * ... * d_{i}). mstore(currentPartialProductPtr, mulmod(mload(currentPartialProductPtr), prodInv, PRIME)) // Update prodInv to be 1/(d_0 * ... * d_{i-1}) by multiplying by d_i. prodInv := mulmod(prodInv, mload(add(currentPartialProductPtr, productsToValuesOffset)), PRIME) currentPartialProductPtr := sub(currentPartialProductPtr, 0x20) // Store 1/d_{i} = (d_0 * ... * d_{i-1}) * 1/(d_0 * ... * d_{i}). mstore(currentPartialProductPtr, mulmod(mload(currentPartialProductPtr), prodInv, PRIME)) // Update prodInv to be 1/(d_0 * ... * d_{i-1}) by multiplying by d_i. prodInv := mulmod(prodInv, mload(add(currentPartialProductPtr, productsToValuesOffset)), PRIME) currentPartialProductPtr := sub(currentPartialProductPtr, 0x20) // Store 1/d_{i} = (d_0 * ... * d_{i-1}) * 1/(d_0 * ... * d_{i}). mstore(currentPartialProductPtr, mulmod(mload(currentPartialProductPtr), prodInv, PRIME)) // Update prodInv to be 1/(d_0 * ... * d_{i-1}) by multiplying by d_i. prodInv := mulmod(prodInv, mload(add(currentPartialProductPtr, productsToValuesOffset)), PRIME) currentPartialProductPtr := sub(currentPartialProductPtr, 0x20) // Store 1/d_{i} = (d_0 * ... * d_{i-1}) * 1/(d_0 * ... * d_{i}). mstore(currentPartialProductPtr, mulmod(mload(currentPartialProductPtr), prodInv, PRIME)) // Update prodInv to be 1/(d_0 * ... * d_{i-1}) by multiplying by d_i. prodInv := mulmod(prodInv, mload(add(currentPartialProductPtr, productsToValuesOffset)), PRIME) currentPartialProductPtr := sub(currentPartialProductPtr, 0x20) // Store 1/d_{i} = (d_0 * ... * d_{i-1}) * 1/(d_0 * ... * d_{i}). mstore(currentPartialProductPtr, mulmod(mload(currentPartialProductPtr), prodInv, PRIME)) // Update prodInv to be 1/(d_0 * ... * d_{i-1}) by multiplying by d_i. prodInv := mulmod(prodInv, mload(add(currentPartialProductPtr, productsToValuesOffset)), PRIME) currentPartialProductPtr := sub(currentPartialProductPtr, 0x20) // Store 1/d_{i} = (d_0 * ... * d_{i-1}) * 1/(d_0 * ... * d_{i}). mstore(currentPartialProductPtr, mulmod(mload(currentPartialProductPtr), prodInv, PRIME)) // Update prodInv to be 1/(d_0 * ... * d_{i-1}) by multiplying by d_i. prodInv := mulmod(prodInv, mload(add(currentPartialProductPtr, productsToValuesOffset)), PRIME) currentPartialProductPtr := sub(currentPartialProductPtr, 0x20) // Store 1/d_{i} = (d_0 * ... * d_{i-1}) * 1/(d_0 * ... * d_{i}). mstore(currentPartialProductPtr, mulmod(mload(currentPartialProductPtr), prodInv, PRIME)) // Update prodInv to be 1/(d_0 * ... * d_{i-1}) by multiplying by d_i. prodInv := mulmod(prodInv, mload(add(currentPartialProductPtr, productsToValuesOffset)), PRIME) } // Loop over the remainder. for { } gt(currentPartialProductPtr, firstPartialProductPtr) { } { currentPartialProductPtr := sub(currentPartialProductPtr, 0x20) // Store 1/d_{i} = (d_0 * ... * d_{i-1}) * 1/(d_0 * ... * d_{i}). mstore(currentPartialProductPtr, mulmod(mload(currentPartialProductPtr), prodInv, PRIME)) // Update prodInv to be 1/(d_0 * ... * d_{i-1}) by multiplying by d_i. prodInv := mulmod(prodInv, mload(add(currentPartialProductPtr, productsToValuesOffset)), PRIME) } } } } contract Fri is MemoryMap, MemoryAccessUtils, HornerEvaluator, FriLayer { event LogGas(string name, uint256 val); function verifyLastLayer(uint256[] memory ctx, uint256 nPoints) internal { uint256 friLastLayerDegBound = ctx[MM_FRI_LAST_LAYER_DEG_BOUND]; uint256 groupOrderMinusOne = friLastLayerDegBound * ctx[MM_BLOW_UP_FACTOR] - 1; uint256 coefsStart = ctx[MM_FRI_LAST_LAYER_PTR]; for (uint256 i = 0; i < nPoints; i++) { uint256 point = ctx[MM_FRI_QUEUE + 3*i + 2]; // Invert point using inverse(point) == fpow(point, ord(point) - 1). point = fpow(point, groupOrderMinusOne); require( hornerEval(coefsStart, point, friLastLayerDegBound) == ctx[MM_FRI_QUEUE + 3*i + 1], "Bad Last layer value."); } } /* Verifies FRI layers. Upon entry and every time we pass through the "if (index < layerSize)" condition, ctx[mmFriQueue:] holds an array of triplets (query index, FRI value, FRI inversed point), i.e. ctx[mmFriQueue::3] holds query indices. ctx[mmFriQueue + 1::3] holds the input for the next layer. ctx[mmFriQueue + 2::3] holds the inverses of the evaluation points: ctx[mmFriQueue + 3*i + 2] = inverse( fpow(layerGenerator, bitReverse(ctx[mmFriQueue + 3*i], logLayerSize)). */ function friVerifyLayers( uint256[] memory ctx) internal { uint256 friCtx = getPtr(ctx, MM_FRI_CTX); require( MAX_SUPPORTED_MAX_FRI_STEP == FRI_MAX_FRI_STEP, "Incosistent MAX_FRI_STEP between MemoryMap.sol and FriLayer.sol"); initFriGroups(friCtx); // emit LogGas("FRI offset precomputation", gasleft()); uint256 channelPtr = getChannelPtr(ctx); uint256 merkleQueuePtr = getMerkleQueuePtr(ctx); uint256 friStep = 1; uint256 nLiveQueries = ctx[MM_N_UNIQUE_QUERIES]; // Add 0 at the end of the queries array to avoid empty array check in readNextElment. ctx[MM_FRI_QUERIES_DELIMITER] = 0; // Rather than converting all the values from Montgomery to standard form, // we can just pretend that the values are in standard form but all // the committed polynomials are multiplied by MontgomeryR. // // The values in the proof are already multiplied by MontgomeryR, // but the inputs from the OODS oracle need to be fixed. for (uint256 i = 0; i < nLiveQueries; i++ ) { ctx[MM_FRI_QUEUE + 3*i + 1] = fmul(ctx[MM_FRI_QUEUE + 3*i + 1], K_MONTGOMERY_R); } uint256 friQueue = getPtr(ctx, MM_FRI_QUEUE); uint256[] memory friSteps = getFriSteps(ctx); uint256 nFriSteps = friSteps.length; while (friStep < nFriSteps) { uint256 friCosetSize = 2**friSteps[friStep]; nLiveQueries = computeNextLayer( channelPtr, friQueue, merkleQueuePtr, nLiveQueries, ctx[MM_FRI_EVAL_POINTS + friStep], friCosetSize, friCtx); // emit LogGas( // string(abi.encodePacked("FRI layer ", bytes1(uint8(48 + friStep)))), gasleft()); // Layer is done, verify the current layer and move to next layer. // ctx[mmMerkleQueue: merkleQueueIdx) holds the indices // and values of the merkle leaves that need verification. verify( channelPtr, merkleQueuePtr, bytes32(ctx[MM_FRI_COMMITMENTS + friStep - 1]), nLiveQueries); // emit LogGas( // string(abi.encodePacked("Merkle of FRI layer ", bytes1(uint8(48 + friStep)))), // gasleft()); friStep++; } verifyLastLayer(ctx, nLiveQueries); // emit LogGas("last FRI layer", gasleft()); } } contract StarkVerifier is MemoryMap, MemoryAccessUtils, VerifierChannel, IStarkVerifier, Fri { /* The work required to generate an invalid proof is 2^numSecurityBits. Typical values: 80-128. */ uint256 numSecurityBits; /* The secuirty of a proof is a composition of bits obtained by PoW and bits obtained by FRI queries. The verifier requires at least minProofOfWorkBits to be obtained by PoW. Typical values: 20-30. */ uint256 minProofOfWorkBits; constructor(uint256 numSecurityBits_, uint256 minProofOfWorkBits_) public { numSecurityBits = numSecurityBits_; minProofOfWorkBits = minProofOfWorkBits_; } /* To print LogDebug messages from assembly use code like the following: assembly { let val := 0x1234 mstore(0, val) // uint256 val // log to the LogDebug(uint256) topic log1(0, 0x20, 0x2feb477e5c8c82cfb95c787ed434e820b1a28fa84d68bbf5aba5367382f5581c) } Note that you can't use log in a contract that was called with staticcall (ContraintPoly, Oods,...) If logging is needed replace the staticcall to call and add a third argument of 0. */ event LogBool(bool val); event LogDebug(uint256 val); address oodsContractAddress; function airSpecificInit(uint256[] memory publicInput) internal returns (uint256[] memory ctx, uint256 logTraceLength); uint256 constant internal PROOF_PARAMS_N_QUERIES_OFFSET = 0; uint256 constant internal PROOF_PARAMS_LOG_BLOWUP_FACTOR_OFFSET = 1; uint256 constant internal PROOF_PARAMS_PROOF_OF_WORK_BITS_OFFSET = 2; uint256 constant internal PROOF_PARAMS_FRI_LAST_LAYER_DEG_BOUND_OFFSET = 3; uint256 constant internal PROOF_PARAMS_N_FRI_STEPS_OFFSET = 4; uint256 constant internal PROOF_PARAMS_FRI_STEPS_OFFSET = 5; function validateFriParams( uint256[] memory friSteps, uint256 logTraceLength, uint256 logFriLastLayerDegBound) internal pure { require (friSteps[0] == 0, "Only eta0 == 0 is currently supported"); uint256 expectedLogDegBound = logFriLastLayerDegBound; uint256 nFriSteps = friSteps.length; for (uint256 i = 1; i < nFriSteps; i++) { uint256 friStep = friSteps[i]; require(friStep > 0, "Only the first fri step can be 0"); require(friStep <= 4, "Max supported fri step is 4."); expectedLogDegBound += friStep; } // FRI starts with a polynomial of degree 'traceLength'. // After applying all the FRI steps we expect to get a polynomial of degree less // than friLastLayerDegBound. require ( expectedLogDegBound == logTraceLength, "Fri params do not match trace length"); } function initVerifierParams(uint256[] memory publicInput, uint256[] memory proofParams) internal returns (uint256[] memory ctx) { require (proofParams.length > PROOF_PARAMS_FRI_STEPS_OFFSET, "Invalid proofParams."); require ( proofParams.length == ( PROOF_PARAMS_FRI_STEPS_OFFSET + proofParams[PROOF_PARAMS_N_FRI_STEPS_OFFSET]), "Invalid proofParams."); uint256 logBlowupFactor = proofParams[PROOF_PARAMS_LOG_BLOWUP_FACTOR_OFFSET]; require (logBlowupFactor <= 16, "logBlowupFactor must be at most 16"); require (logBlowupFactor >= 1, "logBlowupFactor must be at least 1"); uint256 proofOfWorkBits = proofParams[PROOF_PARAMS_PROOF_OF_WORK_BITS_OFFSET]; require (proofOfWorkBits <= 50, "proofOfWorkBits must be at most 50"); require (proofOfWorkBits >= minProofOfWorkBits, "minimum proofOfWorkBits not satisfied"); require (proofOfWorkBits < numSecurityBits, "Proofs may not be purely based on PoW."); uint256 logFriLastLayerDegBound = ( proofParams[PROOF_PARAMS_FRI_LAST_LAYER_DEG_BOUND_OFFSET] ); require ( logFriLastLayerDegBound <= 10, "logFriLastLayerDegBound must be at most 10."); uint256 nFriSteps = proofParams[PROOF_PARAMS_N_FRI_STEPS_OFFSET]; require (nFriSteps <= 10, "Too many fri steps."); require (nFriSteps > 1, "Not enough fri steps."); uint256[] memory friSteps = new uint256[](nFriSteps); for (uint256 i = 0; i < nFriSteps; i++) { friSteps[i] = proofParams[PROOF_PARAMS_FRI_STEPS_OFFSET + i]; } uint256 logTraceLength; (ctx, logTraceLength) = airSpecificInit(publicInput); validateFriParams(friSteps, logTraceLength, logFriLastLayerDegBound); uint256 friStepsPtr = getPtr(ctx, MM_FRI_STEPS_PTR); assembly { mstore(friStepsPtr, friSteps) } ctx[MM_FRI_LAST_LAYER_DEG_BOUND] = 2**logFriLastLayerDegBound; ctx[MM_TRACE_LENGTH] = 2 ** logTraceLength; ctx[MM_BLOW_UP_FACTOR] = 2**logBlowupFactor; ctx[MM_PROOF_OF_WORK_BITS] = proofOfWorkBits; uint256 nQueries = proofParams[PROOF_PARAMS_N_QUERIES_OFFSET]; require (nQueries > 0, "Number of queries must be at least one"); require (nQueries <= MAX_N_QUERIES, "Too many queries."); require ( nQueries * logBlowupFactor + proofOfWorkBits >= numSecurityBits, "Proof params do not satisfy security requirements."); ctx[MM_N_UNIQUE_QUERIES] = nQueries; // We start with log_evalDomainSize = logTraceSize and update it here. ctx[MM_LOG_EVAL_DOMAIN_SIZE] = logTraceLength + logBlowupFactor; ctx[MM_EVAL_DOMAIN_SIZE] = 2**ctx[MM_LOG_EVAL_DOMAIN_SIZE]; uint256 gen_evalDomain = fpow(GENERATOR_VAL, (K_MODULUS - 1) / ctx[MM_EVAL_DOMAIN_SIZE]); ctx[MM_EVAL_DOMAIN_GENERATOR] = gen_evalDomain; uint256 genTraceDomain = fpow(gen_evalDomain, ctx[MM_BLOW_UP_FACTOR]); ctx[MM_TRACE_GENERATOR] = genTraceDomain; } function getPublicInputHash(uint256[] memory publicInput) internal pure returns (bytes32); function oodsConsistencyCheck(uint256[] memory ctx) internal; function getNColumnsInTrace() internal pure returns(uint256); function getNColumnsInComposition() internal pure returns(uint256); function getMmCoefficients() internal pure returns(uint256); function getMmOodsValues() internal pure returns(uint256); function getMmOodsCoefficients() internal pure returns(uint256); function getNCoefficients() internal pure returns(uint256); function getNOodsValues() internal pure returns(uint256); function getNOodsCoefficients() internal pure returns(uint256); function hashRow(uint256[] memory ctx, uint256 offset, uint256 length) internal pure returns (uint256 res) { assembly { res := keccak256(add(add(ctx, 0x20), offset), length) } res &= getHashMask(); } /* Adjusts the query indices and generates evaluation points for each query index. The operations above are independent but we can save gas by combining them as both operations require us to iterate the queries array. Indices adjustment: The query indices adjustment is needed because both the Merkle verification and FRI expect queries "full binary tree in array" indices. The adjustment is simply adding evalDomainSize to each query. Note that evalDomainSize == 2^(#FRI layers) == 2^(Merkle tree hight). evalPoints generation: for each query index "idx" we compute the corresponding evaluation point: g^(bitReverse(idx, log_evalDomainSize). */ function adjustQueryIndicesAndPrepareEvalPoints(uint256[] memory ctx) internal { uint256 nUniqueQueries = ctx[MM_N_UNIQUE_QUERIES]; uint256 friQueue = getPtr(ctx, MM_FRI_QUEUE); uint256 friQueueEnd = friQueue + nUniqueQueries * 0x60; uint256 evalPointsPtr = getPtr(ctx, MM_OODS_EVAL_POINTS); uint256 log_evalDomainSize = ctx[MM_LOG_EVAL_DOMAIN_SIZE]; uint256 evalDomainSize = ctx[MM_EVAL_DOMAIN_SIZE]; uint256 evalDomainGenerator = ctx[MM_EVAL_DOMAIN_GENERATOR]; assembly { /* Returns the bit reversal of value assuming it has the given number of bits. numberOfBits must be <= 64. */ function bitReverse(value, numberOfBits) -> res { // Bit reverse value by swapping 1 bit chunks then 2 bit chunks and so forth. // Each swap is done by masking out and shifting one of the chunks by twice its size. // Finally, we use div to align the result to the right. res := value // Swap 1 bit chunks. res := or(mul(and(res, 0x5555555555555555), 0x4), and(res, 0xaaaaaaaaaaaaaaaa)) // Swap 2 bit chunks. res := or(mul(and(res, 0x6666666666666666), 0x10), and(res, 0x19999999999999998)) // Swap 4 bit chunks. res := or(mul(and(res, 0x7878787878787878), 0x100), and(res, 0x78787878787878780)) // Swap 8 bit chunks. res := or(mul(and(res, 0x7f807f807f807f80), 0x10000), and(res, 0x7f807f807f807f8000)) // Swap 16 bit chunks. res := or(mul(and(res, 0x7fff80007fff8000), 0x100000000), and(res, 0x7fff80007fff80000000)) // Swap 32 bit chunks. res := or(mul(and(res, 0x7fffffff80000000), 0x10000000000000000), and(res, 0x7fffffff8000000000000000)) // Right align the result. res := div(res, exp(2, sub(127, numberOfBits))) } function expmod(base, exponent, modulus) -> res { let p := mload(0x40) mstore(p, 0x20) // Length of Base. mstore(add(p, 0x20), 0x20) // Length of Exponent. mstore(add(p, 0x40), 0x20) // Length of Modulus. mstore(add(p, 0x60), base) // Base. mstore(add(p, 0x80), exponent) // Exponent. mstore(add(p, 0xa0), modulus) // Modulus. // Call modexp precompile. if iszero(call(not(0), 0x05, 0, p, 0xc0, p, 0x20)) { revert(0, 0) } res := mload(p) } let PRIME := 0x30000003000000010000000000000001 for {} lt(friQueue, friQueueEnd) {friQueue := add(friQueue, 0x60)} { let queryIdx := mload(friQueue) // Adjust queryIdx, see comment in function description. let adjustedQueryIdx := add(queryIdx, evalDomainSize) mstore(friQueue, adjustedQueryIdx) // Compute the evaluation point corresponding to the current queryIdx. mstore(evalPointsPtr, expmod(evalDomainGenerator, bitReverse(queryIdx, log_evalDomainSize), PRIME)) evalPointsPtr := add(evalPointsPtr, 0x20) } } } function readQueryResponsesAndDecommit( uint256[] memory ctx, uint256 nColumns, uint256 proofDataPtr, bytes32 merkleRoot) internal view { require(nColumns <= getNColumnsInTrace() + getNColumnsInComposition(), "Too many columns."); uint256 nUniqueQueries = ctx[MM_N_UNIQUE_QUERIES]; uint256 channelPtr = getPtr(ctx, MM_CHANNEL); uint256 friQueue = getPtr(ctx, MM_FRI_QUEUE); uint256 friQueueEnd = friQueue + nUniqueQueries * 0x60; uint256 merkleQueuePtr = getPtr(ctx, MM_MERKLE_QUEUE); uint256 rowSize = 0x20 * nColumns; uint256 lhashMask = getHashMask(); assembly { let proofPtr := mload(channelPtr) let merklePtr := merkleQueuePtr for {} lt(friQueue, friQueueEnd) {friQueue := add(friQueue, 0x60)} { let merkleLeaf := and(keccak256(proofPtr, rowSize), lhashMask) if eq(rowSize, 0x20) { // If a leaf contains only 1 field element we don't hash it. merkleLeaf := mload(proofPtr) } // push(queryIdx, hash(row)) to merkleQueue. mstore(merklePtr, mload(friQueue)) mstore(add(merklePtr, 0x20), merkleLeaf) merklePtr := add(merklePtr, 0x40) // Copy query responses to proofData array. // This array will be sent to the OODS contract. for {let proofDataChunk_end := add(proofPtr, rowSize)} lt(proofPtr, proofDataChunk_end) {proofPtr := add(proofPtr, 0x20)} { mstore(proofDataPtr, mload(proofPtr)) proofDataPtr := add(proofDataPtr, 0x20) } } mstore(channelPtr, proofPtr) } verify(channelPtr, merkleQueuePtr, merkleRoot, nUniqueQueries); } /* Computes the first FRI layer by reading the query responses and calling the OODS contract. The OODS contract will build and sum boundary constraints that check that the prover provided the proper evaluations for the Out of Domain Sampling. I.e. if the prover said that f(z) = c, the first FRI layer will include the term (f(x) - c)/(x-z). */ function computeFirstFriLayer(uint256[] memory ctx) internal { adjustQueryIndicesAndPrepareEvalPoints(ctx); // emit LogGas("Prepare evaluation points", gasleft()); readQueryResponsesAndDecommit( ctx, getNColumnsInTrace(), getPtr(ctx, MM_TRACE_QUERY_RESPONSES), bytes32(ctx[MM_TRACE_COMMITMENT])); // emit LogGas("Read and decommit trace", gasleft()); readQueryResponsesAndDecommit( ctx, getNColumnsInComposition(), getPtr(ctx, MM_COMPOSITION_QUERY_RESPONSES), bytes32(ctx[MM_OODS_COMMITMENT])); // emit LogGas("Read and decommit composition", gasleft()); address oodsAddress = oodsContractAddress; uint256 friQueue = getPtr(ctx, MM_FRI_QUEUE); uint256 returnDataSize = MAX_N_QUERIES * 0x60; assembly { // Call the OODS contract. if iszero(staticcall(not(0), oodsAddress, ctx, /*sizeof(ctx)*/ mul(add(mload(ctx), 1), 0x20), friQueue, returnDataSize)) { returndatacopy(0, 0, returndatasize) revert(0, returndatasize) } } // emit LogGas("OODS virtual oracle", gasleft()); } /* Reads the last FRI layer (i.e. the polynomial's coefficients) from the channel. This differs from standard reading of channel field elements in several ways: -- The digest is updated by hashing it once with all coefficients simultaneously, rather than iteratively one by one. -- The coefficients are kept in Montgomery form, as is the case throughout the FRI computation. -- The coefficients are not actually read and copied elsewhere, but rather only a pointer to their location in the channel is stored. */ function readLastFriLayer(uint256[] memory ctx) internal pure { uint256 lmmChannel = MM_CHANNEL; uint256 friLastLayerDegBound = ctx[MM_FRI_LAST_LAYER_DEG_BOUND]; uint256 lastLayerPtr; uint256 badInput = 0; assembly { let primeMinusOne := 0x30000003000000010000000000000000 let channelPtr := add(add(ctx, 0x20), mul(lmmChannel, 0x20)) lastLayerPtr := mload(channelPtr) // Make sure all the values are valid field elements. let length := mul(friLastLayerDegBound, 0x20) let lastLayerEnd := add(lastLayerPtr, length) for { let coefsPtr := lastLayerPtr } lt(coefsPtr, lastLayerEnd) { coefsPtr := add(coefsPtr, 0x20) } { badInput := or(badInput, gt(mload(coefsPtr), primeMinusOne)) } // Copy the digest to the proof area // (store it before the coefficients - this is done because // keccak256 needs all data to be consecutive), // then hash and place back in digestPtr. let newDigestPtr := sub(lastLayerPtr, 0x20) let digestPtr := add(channelPtr, 0x20) // Overwriting the proof to minimize copying of data. mstore(newDigestPtr, mload(digestPtr)) // prng.digest := keccak256(digest||lastLayerCoefs). mstore(digestPtr, keccak256(newDigestPtr, add(length, 0x20))) // prng.counter := 0. mstore(add(channelPtr, 0x40), 0) // Note: proof pointer is not incremented until this point. mstore(channelPtr, lastLayerEnd) } require(badInput == 0, "Invalid field element."); ctx[MM_FRI_LAST_LAYER_PTR] = lastLayerPtr; } function verifyProof( uint256[] memory proofParams, uint256[] memory proof, uint256[] memory publicInput) internal { // emit LogGas("Transmission", gasleft()); uint256[] memory ctx = initVerifierParams(publicInput, proofParams); uint256 channelPtr = getChannelPtr(ctx); initChannel(channelPtr, getProofPtr(proof), getPublicInputHash(publicInput)); // emit LogGas("Initializations", gasleft()); // Read trace commitment. ctx[MM_TRACE_COMMITMENT] = uint256(readHash(channelPtr, true)); VerifierChannel.sendFieldElements( channelPtr, getNCoefficients(), getPtr(ctx, getMmCoefficients())); // emit LogGas("Generate coefficients", gasleft()); ctx[MM_OODS_COMMITMENT] = uint256(readHash(channelPtr, true)); // Send Out of Domain Sampling point. VerifierChannel.sendFieldElements(channelPtr, 1, getPtr(ctx, MM_OODS_POINT)); // Read the answers to the Out of Domain Sampling. uint256 lmmOodsValues = getMmOodsValues(); for (uint256 i = lmmOodsValues; i < lmmOodsValues+getNOodsValues(); i++) { ctx[i] = VerifierChannel.readFieldElement(channelPtr, true); } // emit LogGas("Read OODS commitments", gasleft()); oodsConsistencyCheck(ctx); // emit LogGas("OODS consistency check", gasleft()); VerifierChannel.sendFieldElements( channelPtr, getNOodsCoefficients(), getPtr(ctx, getMmOodsCoefficients())); // emit LogGas("Generate OODS coefficients", gasleft()); ctx[MM_FRI_COMMITMENTS] = uint256(VerifierChannel.readHash(channelPtr, true)); uint256 nFriSteps = getFriSteps(ctx).length; uint256 fri_evalPointPtr = getPtr(ctx, MM_FRI_EVAL_POINTS); for (uint256 i = 1; i < nFriSteps - 1; i++) { VerifierChannel.sendFieldElements(channelPtr, 1, fri_evalPointPtr + i * 0x20); ctx[MM_FRI_COMMITMENTS + i] = uint256(VerifierChannel.readHash(channelPtr, true)); } // Send last random FRI evaluation point. VerifierChannel.sendFieldElements( channelPtr, 1, getPtr(ctx, MM_FRI_EVAL_POINTS + nFriSteps - 1)); // Read FRI last layer commitment. readLastFriLayer(ctx); // Generate queries. // emit LogGas("Read FRI commitments", gasleft()); VerifierChannel.verifyProofOfWork(channelPtr, ctx[MM_PROOF_OF_WORK_BITS]); ctx[MM_N_UNIQUE_QUERIES] = VerifierChannel.sendRandomQueries( channelPtr, ctx[MM_N_UNIQUE_QUERIES], ctx[MM_EVAL_DOMAIN_SIZE] - 1, getPtr(ctx, MM_FRI_QUEUE), 0x60); // emit LogGas("Send queries", gasleft()); computeFirstFriLayer(ctx); friVerifyLayers(ctx); } } contract MimcVerifier is StarkParameters, StarkVerifier, FactRegistry, PublicInputOffsets{ MimcConstraintPoly constraintPoly; PeriodicColumnContract[20] constantsCols; uint256 internal constant PUBLIC_INPUT_SIZE = 5; constructor( address[] memory auxPolynomials, MimcOods oodsContract, uint256 numSecurityBits_, uint256 minProofOfWorkBits_) StarkVerifier( numSecurityBits_, minProofOfWorkBits_ ) public { constraintPoly = MimcConstraintPoly(auxPolynomials[0]); for (uint256 i = 0; i < 20; i++) { constantsCols[i] = PeriodicColumnContract(auxPolynomials[i+1]); } oodsContractAddress = address(oodsContract); } function verifyProofAndRegister( uint256[] calldata proofParams, uint256[] calldata proof, uint256[] calldata publicInput ) external { verifyProof(proofParams, proof, publicInput); registerFact( keccak256( abi.encodePacked( 10 * 2**publicInput[OFFSET_LOG_TRACE_LENGTH] - 1, publicInput[OFFSET_VDF_OUTPUT_X], publicInput[OFFSET_VDF_OUTPUT_Y], publicInput[OFFSET_VDF_INPUT_X], publicInput[OFFSET_VDF_INPUT_Y] ) ) ); } function getNColumnsInTrace() internal pure returns (uint256) { return N_COLUMNS_IN_MASK; } function getNColumnsInComposition() internal pure returns (uint256) { return CONSTRAINTS_DEGREE_BOUND; } function getMmCoefficients() internal pure returns (uint256) { return MM_COEFFICIENTS; } function getMmOodsValues() internal pure returns (uint256) { return MM_OODS_VALUES; } function getMmOodsCoefficients() internal pure returns (uint256) { return MM_OODS_COEFFICIENTS; } function getNCoefficients() internal pure returns (uint256) { return N_COEFFICIENTS; } function getNOodsValues() internal pure returns (uint256) { return N_OODS_VALUES; } function getNOodsCoefficients() internal pure returns (uint256) { return N_OODS_COEFFICIENTS; } function airSpecificInit(uint256[] memory publicInput) internal returns (uint256[] memory ctx, uint256 logTraceLength) { require(publicInput.length == PUBLIC_INPUT_SIZE, "INVALID_PUBLIC_INPUT_LENGTH" ); ctx = new uint256[](MM_CONTEXT_SIZE); // Note that the prover does the VDF computation the other way around (uses the inverse // function), hence vdf_output is the input for its calculation, and vdf_input should be the // result of the calculation. ctx[MM_INPUT_VALUE_A] = publicInput[OFFSET_VDF_OUTPUT_X]; ctx[MM_INPUT_VALUE_B] = publicInput[OFFSET_VDF_OUTPUT_Y]; ctx[MM_OUTPUT_VALUE_A] = publicInput[OFFSET_VDF_INPUT_X]; ctx[MM_OUTPUT_VALUE_B] = publicInput[OFFSET_VDF_INPUT_Y]; // Initialize the MDS matrix values with fixed predefined values. ctx[MM_MAT00] = 0x109bbc181e07a285856e0d8bde02619; ctx[MM_MAT01] = 0x1eb8859b1b789cd8a80927a32fdf41f7; ctx[MM_MAT10] = 0xdc8eaac802c8f9cb9dff6ed0728012d; ctx[MM_MAT11] = 0x2c18506f35eab63b58143a34181c89e; logTraceLength = publicInput[OFFSET_LOG_TRACE_LENGTH]; require(logTraceLength <= 50, "logTraceLength must not exceed 50."); } function getPublicInputHash(uint256[] memory publicInput) internal pure returns (bytes32) { return keccak256( abi.encodePacked( uint64(2 ** publicInput[OFFSET_LOG_TRACE_LENGTH]), publicInput[OFFSET_VDF_OUTPUT_X], publicInput[OFFSET_VDF_OUTPUT_Y], publicInput[OFFSET_VDF_INPUT_X], publicInput[OFFSET_VDF_INPUT_Y]) ); } /* Checks that the trace and the composition agree on the Out of Domain Sampling point, assuming the prover provided us with the proper evaluations. Later, we use boundary constraints to check that those evaluations are actually consistent with the committed trace and composition polynomials. */ function oodsConsistencyCheck(uint256[] memory ctx) internal { uint256 oodsPoint = ctx[MM_OODS_POINT]; uint256 nRows = 256; uint256 zPointPow = fpow(oodsPoint, ctx[MM_TRACE_LENGTH] / nRows); ctx[MM_PERIODIC_COLUMN__CONSTS0_A] = constantsCols[0].compute(zPointPow); ctx[MM_PERIODIC_COLUMN__CONSTS1_A] = constantsCols[1].compute(zPointPow); ctx[MM_PERIODIC_COLUMN__CONSTS2_A] = constantsCols[2].compute(zPointPow); ctx[MM_PERIODIC_COLUMN__CONSTS3_A] = constantsCols[3].compute(zPointPow); ctx[MM_PERIODIC_COLUMN__CONSTS4_A] = constantsCols[4].compute(zPointPow); ctx[MM_PERIODIC_COLUMN__CONSTS5_A] = constantsCols[5].compute(zPointPow); ctx[MM_PERIODIC_COLUMN__CONSTS6_A] = constantsCols[6].compute(zPointPow); ctx[MM_PERIODIC_COLUMN__CONSTS7_A] = constantsCols[7].compute(zPointPow); ctx[MM_PERIODIC_COLUMN__CONSTS8_A] = constantsCols[8].compute(zPointPow); ctx[MM_PERIODIC_COLUMN__CONSTS9_A] = constantsCols[9].compute(zPointPow); ctx[MM_PERIODIC_COLUMN__CONSTS0_B] = constantsCols[10].compute(zPointPow); ctx[MM_PERIODIC_COLUMN__CONSTS1_B] = constantsCols[11].compute(zPointPow); ctx[MM_PERIODIC_COLUMN__CONSTS2_B] = constantsCols[12].compute(zPointPow); ctx[MM_PERIODIC_COLUMN__CONSTS3_B] = constantsCols[13].compute(zPointPow); ctx[MM_PERIODIC_COLUMN__CONSTS4_B] = constantsCols[14].compute(zPointPow); ctx[MM_PERIODIC_COLUMN__CONSTS5_B] = constantsCols[15].compute(zPointPow); ctx[MM_PERIODIC_COLUMN__CONSTS6_B] = constantsCols[16].compute(zPointPow); ctx[MM_PERIODIC_COLUMN__CONSTS7_B] = constantsCols[17].compute(zPointPow); ctx[MM_PERIODIC_COLUMN__CONSTS8_B] = constantsCols[18].compute(zPointPow); ctx[MM_PERIODIC_COLUMN__CONSTS9_B] = constantsCols[19].compute(zPointPow); uint256 compositionFromTraceValue; address lconstraintPoly = address(constraintPoly); uint256 offset = 0x20 * (1 + MM_CONSTRAINT_POLY_ARGS_START); uint256 size = 0x20 * (MM_CONSTRAINT_POLY_ARGS_END - MM_CONSTRAINT_POLY_ARGS_START); assembly { // Call MimcConstraintPoly contract. let p := mload(0x40) if iszero(staticcall(not(0), lconstraintPoly, add(ctx, offset), size, p, 0x20)) { returndatacopy(0, 0, returndatasize) revert(0, returndatasize) } compositionFromTraceValue := mload(p) } uint256 claimedComposition = fadd( ctx[MM_OODS_VALUES + MASK_SIZE], fmul(oodsPoint, ctx[MM_OODS_VALUES + MASK_SIZE + 1])); require( compositionFromTraceValue == claimedComposition, "claimedComposition does not match trace"); } }
/ The array expmodsAndPoints stores subexpressions that are needed for the denominators computation. The array is segmented as follows: expmodsAndPoints[0:0] (.expmods) expmods used during calculations of the points below. expmodsAndPoints[0:2] (.points) points used during the denominators calculation.
internal view { uint256 evalCosetOffset_ = PrimeFieldElement6.GENERATOR_VAL; uint256[2] memory expmodsAndPoints; this function also adds those to the batch inverse in prepartion for the fri that follows. After this function returns, the batch_inverse_out array holds #queries chunks of size (2 + N_ROWS_IN_MASK) with the following structure: 0..(N_ROWS_IN_MASK-1): [(x - g^i * z)^(-1) for i in rowsInMask] N_ROWS_IN_MASK: (x - z^constraintDegree)^-1 N_ROWS_IN_MASK+1: friEvalPointInv. function oodsPrepareInverses( uint256[] memory context, uint256[] memory batchInverseArray) assembly { function expmod(base, exponent, modulus) -> res { let p := mload(0x40) if iszero(staticcall(not(0), 0x05, p, 0xc0, p, 0x20)) { revert(0, 0) } res := mload(p) } let traceGenerator := /*trace_generator*/ mload(add(context, 0x2b40)) let PRIME := 0x30000003000000010000000000000001 let oodsPoint := /*oods_point*/ mload(add(context, 0x2b60)) { let point := sub(PRIME, oodsPoint) mstore(add(expmodsAndPoints, 0x0), point) point := mulmod(point, traceGenerator, PRIME) mstore(add(expmodsAndPoints, 0x20), point) } let evalPointsPtr := /*oodsEvalPoints*/ add(context, 0x3480) let evalPointsEndPtr := add(evalPointsPtr, mul(/*n_unique_queries*/ mload(add(context, 0x120)), 0x20)) let productsPtr := add(batchInverseArray, 0x20) let valuesPtr := add(add(batchInverseArray, 0x20), 0x1800) let partialProduct := 1 let minusPointPow := sub(PRIME, mulmod(oodsPoint, oodsPoint, PRIME)) let evalPoint := mload(evalPointsPtr) let shiftedEvalPoint := mulmod(evalPoint, evalCosetOffset_, PRIME) { let denominator := add(shiftedEvalPoint, mload(add(expmodsAndPoints, 0x0))) mstore(productsPtr, partialProduct) mstore(valuesPtr, denominator) partialProduct := mulmod(partialProduct, denominator, PRIME) } { let denominator := add(shiftedEvalPoint, mload(add(expmodsAndPoints, 0x20))) mstore(add(productsPtr, 0x20), partialProduct) mstore(add(valuesPtr, 0x20), denominator) partialProduct := mulmod(partialProduct, denominator, PRIME) } { let denominator := add(shiftedEvalPoint, minusPointPow) mstore(add(productsPtr, 0x40), partialProduct) mstore(add(valuesPtr, 0x40), denominator) partialProduct := mulmod(partialProduct, denominator, PRIME) } mstore(add(productsPtr, 0x60), partialProduct) mstore(add(valuesPtr, 0x60), evalPoint) partialProduct := mulmod(partialProduct, evalPoint, PRIME) productsPtr := add(productsPtr, 0x80) valuesPtr := add(valuesPtr, 0x80) } let productsToValuesOffset := 0x1800 let firstPartialProductPtr := add(batchInverseArray, 0x20) let prodInv := expmod(partialProduct, sub(PRIME, 2), PRIME) this function also adds those to the batch inverse in prepartion for the fri that follows. After this function returns, the batch_inverse_out array holds #queries chunks of size (2 + N_ROWS_IN_MASK) with the following structure: 0..(N_ROWS_IN_MASK-1): [(x - g^i * z)^(-1) for i in rowsInMask] N_ROWS_IN_MASK: (x - z^constraintDegree)^-1 N_ROWS_IN_MASK+1: friEvalPointInv. function oodsPrepareInverses( uint256[] memory context, uint256[] memory batchInverseArray) assembly { function expmod(base, exponent, modulus) -> res { let p := mload(0x40) if iszero(staticcall(not(0), 0x05, p, 0xc0, p, 0x20)) { revert(0, 0) } res := mload(p) } let traceGenerator := /*trace_generator*/ mload(add(context, 0x2b40)) let PRIME := 0x30000003000000010000000000000001 let oodsPoint := /*oods_point*/ mload(add(context, 0x2b60)) { let point := sub(PRIME, oodsPoint) mstore(add(expmodsAndPoints, 0x0), point) point := mulmod(point, traceGenerator, PRIME) mstore(add(expmodsAndPoints, 0x20), point) } let evalPointsPtr := /*oodsEvalPoints*/ add(context, 0x3480) let evalPointsEndPtr := add(evalPointsPtr, mul(/*n_unique_queries*/ mload(add(context, 0x120)), 0x20)) let productsPtr := add(batchInverseArray, 0x20) let valuesPtr := add(add(batchInverseArray, 0x20), 0x1800) let partialProduct := 1 let minusPointPow := sub(PRIME, mulmod(oodsPoint, oodsPoint, PRIME)) let evalPoint := mload(evalPointsPtr) let shiftedEvalPoint := mulmod(evalPoint, evalCosetOffset_, PRIME) { let denominator := add(shiftedEvalPoint, mload(add(expmodsAndPoints, 0x0))) mstore(productsPtr, partialProduct) mstore(valuesPtr, denominator) partialProduct := mulmod(partialProduct, denominator, PRIME) } { let denominator := add(shiftedEvalPoint, mload(add(expmodsAndPoints, 0x20))) mstore(add(productsPtr, 0x20), partialProduct) mstore(add(valuesPtr, 0x20), denominator) partialProduct := mulmod(partialProduct, denominator, PRIME) } { let denominator := add(shiftedEvalPoint, minusPointPow) mstore(add(productsPtr, 0x40), partialProduct) mstore(add(valuesPtr, 0x40), denominator) partialProduct := mulmod(partialProduct, denominator, PRIME) } mstore(add(productsPtr, 0x60), partialProduct) mstore(add(valuesPtr, 0x60), evalPoint) partialProduct := mulmod(partialProduct, evalPoint, PRIME) productsPtr := add(productsPtr, 0x80) valuesPtr := add(valuesPtr, 0x80) } let productsToValuesOffset := 0x1800 let firstPartialProductPtr := add(batchInverseArray, 0x20) let prodInv := expmod(partialProduct, sub(PRIME, 2), PRIME) this function also adds those to the batch inverse in prepartion for the fri that follows. After this function returns, the batch_inverse_out array holds #queries chunks of size (2 + N_ROWS_IN_MASK) with the following structure: 0..(N_ROWS_IN_MASK-1): [(x - g^i * z)^(-1) for i in rowsInMask] N_ROWS_IN_MASK: (x - z^constraintDegree)^-1 N_ROWS_IN_MASK+1: friEvalPointInv. function oodsPrepareInverses( uint256[] memory context, uint256[] memory batchInverseArray) assembly { function expmod(base, exponent, modulus) -> res { let p := mload(0x40) if iszero(staticcall(not(0), 0x05, p, 0xc0, p, 0x20)) { revert(0, 0) } res := mload(p) } let traceGenerator := /*trace_generator*/ mload(add(context, 0x2b40)) let PRIME := 0x30000003000000010000000000000001 let oodsPoint := /*oods_point*/ mload(add(context, 0x2b60)) { let point := sub(PRIME, oodsPoint) mstore(add(expmodsAndPoints, 0x0), point) point := mulmod(point, traceGenerator, PRIME) mstore(add(expmodsAndPoints, 0x20), point) } let evalPointsPtr := /*oodsEvalPoints*/ add(context, 0x3480) let evalPointsEndPtr := add(evalPointsPtr, mul(/*n_unique_queries*/ mload(add(context, 0x120)), 0x20)) let productsPtr := add(batchInverseArray, 0x20) let valuesPtr := add(add(batchInverseArray, 0x20), 0x1800) let partialProduct := 1 let minusPointPow := sub(PRIME, mulmod(oodsPoint, oodsPoint, PRIME)) let evalPoint := mload(evalPointsPtr) let shiftedEvalPoint := mulmod(evalPoint, evalCosetOffset_, PRIME) { let denominator := add(shiftedEvalPoint, mload(add(expmodsAndPoints, 0x0))) mstore(productsPtr, partialProduct) mstore(valuesPtr, denominator) partialProduct := mulmod(partialProduct, denominator, PRIME) } { let denominator := add(shiftedEvalPoint, mload(add(expmodsAndPoints, 0x20))) mstore(add(productsPtr, 0x20), partialProduct) mstore(add(valuesPtr, 0x20), denominator) partialProduct := mulmod(partialProduct, denominator, PRIME) } { let denominator := add(shiftedEvalPoint, minusPointPow) mstore(add(productsPtr, 0x40), partialProduct) mstore(add(valuesPtr, 0x40), denominator) partialProduct := mulmod(partialProduct, denominator, PRIME) } mstore(add(productsPtr, 0x60), partialProduct) mstore(add(valuesPtr, 0x60), evalPoint) partialProduct := mulmod(partialProduct, evalPoint, PRIME) productsPtr := add(productsPtr, 0x80) valuesPtr := add(valuesPtr, 0x80) } let productsToValuesOffset := 0x1800 let firstPartialProductPtr := add(batchInverseArray, 0x20) let prodInv := expmod(partialProduct, sub(PRIME, 2), PRIME) this function also adds those to the batch inverse in prepartion for the fri that follows. After this function returns, the batch_inverse_out array holds #queries chunks of size (2 + N_ROWS_IN_MASK) with the following structure: 0..(N_ROWS_IN_MASK-1): [(x - g^i * z)^(-1) for i in rowsInMask] N_ROWS_IN_MASK: (x - z^constraintDegree)^-1 N_ROWS_IN_MASK+1: friEvalPointInv. function oodsPrepareInverses( uint256[] memory context, uint256[] memory batchInverseArray) assembly { function expmod(base, exponent, modulus) -> res { let p := mload(0x40) if iszero(staticcall(not(0), 0x05, p, 0xc0, p, 0x20)) { revert(0, 0) } res := mload(p) } let traceGenerator := /*trace_generator*/ mload(add(context, 0x2b40)) let PRIME := 0x30000003000000010000000000000001 let oodsPoint := /*oods_point*/ mload(add(context, 0x2b60)) { let point := sub(PRIME, oodsPoint) mstore(add(expmodsAndPoints, 0x0), point) point := mulmod(point, traceGenerator, PRIME) mstore(add(expmodsAndPoints, 0x20), point) } let evalPointsPtr := /*oodsEvalPoints*/ add(context, 0x3480) let evalPointsEndPtr := add(evalPointsPtr, mul(/*n_unique_queries*/ mload(add(context, 0x120)), 0x20)) let productsPtr := add(batchInverseArray, 0x20) let valuesPtr := add(add(batchInverseArray, 0x20), 0x1800) let partialProduct := 1 let minusPointPow := sub(PRIME, mulmod(oodsPoint, oodsPoint, PRIME)) let evalPoint := mload(evalPointsPtr) let shiftedEvalPoint := mulmod(evalPoint, evalCosetOffset_, PRIME) { let denominator := add(shiftedEvalPoint, mload(add(expmodsAndPoints, 0x0))) mstore(productsPtr, partialProduct) mstore(valuesPtr, denominator) partialProduct := mulmod(partialProduct, denominator, PRIME) } { let denominator := add(shiftedEvalPoint, mload(add(expmodsAndPoints, 0x20))) mstore(add(productsPtr, 0x20), partialProduct) mstore(add(valuesPtr, 0x20), denominator) partialProduct := mulmod(partialProduct, denominator, PRIME) } { let denominator := add(shiftedEvalPoint, minusPointPow) mstore(add(productsPtr, 0x40), partialProduct) mstore(add(valuesPtr, 0x40), denominator) partialProduct := mulmod(partialProduct, denominator, PRIME) } mstore(add(productsPtr, 0x60), partialProduct) mstore(add(valuesPtr, 0x60), evalPoint) partialProduct := mulmod(partialProduct, evalPoint, PRIME) productsPtr := add(productsPtr, 0x80) valuesPtr := add(valuesPtr, 0x80) } let productsToValuesOffset := 0x1800 let firstPartialProductPtr := add(batchInverseArray, 0x20) let prodInv := expmod(partialProduct, sub(PRIME, 2), PRIME) for {} lt(evalPointsPtr, evalPointsEndPtr) {evalPointsPtr := add(evalPointsPtr, 0x20)} { this function also adds those to the batch inverse in prepartion for the fri that follows. After this function returns, the batch_inverse_out array holds #queries chunks of size (2 + N_ROWS_IN_MASK) with the following structure: 0..(N_ROWS_IN_MASK-1): [(x - g^i * z)^(-1) for i in rowsInMask] N_ROWS_IN_MASK: (x - z^constraintDegree)^-1 N_ROWS_IN_MASK+1: friEvalPointInv. function oodsPrepareInverses( uint256[] memory context, uint256[] memory batchInverseArray) assembly { function expmod(base, exponent, modulus) -> res { let p := mload(0x40) if iszero(staticcall(not(0), 0x05, p, 0xc0, p, 0x20)) { revert(0, 0) } res := mload(p) } let traceGenerator := /*trace_generator*/ mload(add(context, 0x2b40)) let PRIME := 0x30000003000000010000000000000001 let oodsPoint := /*oods_point*/ mload(add(context, 0x2b60)) { let point := sub(PRIME, oodsPoint) mstore(add(expmodsAndPoints, 0x0), point) point := mulmod(point, traceGenerator, PRIME) mstore(add(expmodsAndPoints, 0x20), point) } let evalPointsPtr := /*oodsEvalPoints*/ add(context, 0x3480) let evalPointsEndPtr := add(evalPointsPtr, mul(/*n_unique_queries*/ mload(add(context, 0x120)), 0x20)) let productsPtr := add(batchInverseArray, 0x20) let valuesPtr := add(add(batchInverseArray, 0x20), 0x1800) let partialProduct := 1 let minusPointPow := sub(PRIME, mulmod(oodsPoint, oodsPoint, PRIME)) let evalPoint := mload(evalPointsPtr) let shiftedEvalPoint := mulmod(evalPoint, evalCosetOffset_, PRIME) { let denominator := add(shiftedEvalPoint, mload(add(expmodsAndPoints, 0x0))) mstore(productsPtr, partialProduct) mstore(valuesPtr, denominator) partialProduct := mulmod(partialProduct, denominator, PRIME) } { let denominator := add(shiftedEvalPoint, mload(add(expmodsAndPoints, 0x20))) mstore(add(productsPtr, 0x20), partialProduct) mstore(add(valuesPtr, 0x20), denominator) partialProduct := mulmod(partialProduct, denominator, PRIME) } { let denominator := add(shiftedEvalPoint, minusPointPow) mstore(add(productsPtr, 0x40), partialProduct) mstore(add(valuesPtr, 0x40), denominator) partialProduct := mulmod(partialProduct, denominator, PRIME) } mstore(add(productsPtr, 0x60), partialProduct) mstore(add(valuesPtr, 0x60), evalPoint) partialProduct := mulmod(partialProduct, evalPoint, PRIME) productsPtr := add(productsPtr, 0x80) valuesPtr := add(valuesPtr, 0x80) } let productsToValuesOffset := 0x1800 let firstPartialProductPtr := add(batchInverseArray, 0x20) let prodInv := expmod(partialProduct, sub(PRIME, 2), PRIME) this function also adds those to the batch inverse in prepartion for the fri that follows. After this function returns, the batch_inverse_out array holds #queries chunks of size (2 + N_ROWS_IN_MASK) with the following structure: 0..(N_ROWS_IN_MASK-1): [(x - g^i * z)^(-1) for i in rowsInMask] N_ROWS_IN_MASK: (x - z^constraintDegree)^-1 N_ROWS_IN_MASK+1: friEvalPointInv. function oodsPrepareInverses( uint256[] memory context, uint256[] memory batchInverseArray) assembly { function expmod(base, exponent, modulus) -> res { let p := mload(0x40) if iszero(staticcall(not(0), 0x05, p, 0xc0, p, 0x20)) { revert(0, 0) } res := mload(p) } let traceGenerator := /*trace_generator*/ mload(add(context, 0x2b40)) let PRIME := 0x30000003000000010000000000000001 let oodsPoint := /*oods_point*/ mload(add(context, 0x2b60)) { let point := sub(PRIME, oodsPoint) mstore(add(expmodsAndPoints, 0x0), point) point := mulmod(point, traceGenerator, PRIME) mstore(add(expmodsAndPoints, 0x20), point) } let evalPointsPtr := /*oodsEvalPoints*/ add(context, 0x3480) let evalPointsEndPtr := add(evalPointsPtr, mul(/*n_unique_queries*/ mload(add(context, 0x120)), 0x20)) let productsPtr := add(batchInverseArray, 0x20) let valuesPtr := add(add(batchInverseArray, 0x20), 0x1800) let partialProduct := 1 let minusPointPow := sub(PRIME, mulmod(oodsPoint, oodsPoint, PRIME)) let evalPoint := mload(evalPointsPtr) let shiftedEvalPoint := mulmod(evalPoint, evalCosetOffset_, PRIME) { let denominator := add(shiftedEvalPoint, mload(add(expmodsAndPoints, 0x0))) mstore(productsPtr, partialProduct) mstore(valuesPtr, denominator) partialProduct := mulmod(partialProduct, denominator, PRIME) } { let denominator := add(shiftedEvalPoint, mload(add(expmodsAndPoints, 0x20))) mstore(add(productsPtr, 0x20), partialProduct) mstore(add(valuesPtr, 0x20), denominator) partialProduct := mulmod(partialProduct, denominator, PRIME) } { let denominator := add(shiftedEvalPoint, minusPointPow) mstore(add(productsPtr, 0x40), partialProduct) mstore(add(valuesPtr, 0x40), denominator) partialProduct := mulmod(partialProduct, denominator, PRIME) } mstore(add(productsPtr, 0x60), partialProduct) mstore(add(valuesPtr, 0x60), evalPoint) partialProduct := mulmod(partialProduct, evalPoint, PRIME) productsPtr := add(productsPtr, 0x80) valuesPtr := add(valuesPtr, 0x80) } let productsToValuesOffset := 0x1800 let firstPartialProductPtr := add(batchInverseArray, 0x20) let prodInv := expmod(partialProduct, sub(PRIME, 2), PRIME) this function also adds those to the batch inverse in prepartion for the fri that follows. After this function returns, the batch_inverse_out array holds #queries chunks of size (2 + N_ROWS_IN_MASK) with the following structure: 0..(N_ROWS_IN_MASK-1): [(x - g^i * z)^(-1) for i in rowsInMask] N_ROWS_IN_MASK: (x - z^constraintDegree)^-1 N_ROWS_IN_MASK+1: friEvalPointInv. function oodsPrepareInverses( uint256[] memory context, uint256[] memory batchInverseArray) assembly { function expmod(base, exponent, modulus) -> res { let p := mload(0x40) if iszero(staticcall(not(0), 0x05, p, 0xc0, p, 0x20)) { revert(0, 0) } res := mload(p) } let traceGenerator := /*trace_generator*/ mload(add(context, 0x2b40)) let PRIME := 0x30000003000000010000000000000001 let oodsPoint := /*oods_point*/ mload(add(context, 0x2b60)) { let point := sub(PRIME, oodsPoint) mstore(add(expmodsAndPoints, 0x0), point) point := mulmod(point, traceGenerator, PRIME) mstore(add(expmodsAndPoints, 0x20), point) } let evalPointsPtr := /*oodsEvalPoints*/ add(context, 0x3480) let evalPointsEndPtr := add(evalPointsPtr, mul(/*n_unique_queries*/ mload(add(context, 0x120)), 0x20)) let productsPtr := add(batchInverseArray, 0x20) let valuesPtr := add(add(batchInverseArray, 0x20), 0x1800) let partialProduct := 1 let minusPointPow := sub(PRIME, mulmod(oodsPoint, oodsPoint, PRIME)) let evalPoint := mload(evalPointsPtr) let shiftedEvalPoint := mulmod(evalPoint, evalCosetOffset_, PRIME) { let denominator := add(shiftedEvalPoint, mload(add(expmodsAndPoints, 0x0))) mstore(productsPtr, partialProduct) mstore(valuesPtr, denominator) partialProduct := mulmod(partialProduct, denominator, PRIME) } { let denominator := add(shiftedEvalPoint, mload(add(expmodsAndPoints, 0x20))) mstore(add(productsPtr, 0x20), partialProduct) mstore(add(valuesPtr, 0x20), denominator) partialProduct := mulmod(partialProduct, denominator, PRIME) } { let denominator := add(shiftedEvalPoint, minusPointPow) mstore(add(productsPtr, 0x40), partialProduct) mstore(add(valuesPtr, 0x40), denominator) partialProduct := mulmod(partialProduct, denominator, PRIME) } mstore(add(productsPtr, 0x60), partialProduct) mstore(add(valuesPtr, 0x60), evalPoint) partialProduct := mulmod(partialProduct, evalPoint, PRIME) productsPtr := add(productsPtr, 0x80) valuesPtr := add(valuesPtr, 0x80) } let productsToValuesOffset := 0x1800 let firstPartialProductPtr := add(batchInverseArray, 0x20) let prodInv := expmod(partialProduct, sub(PRIME, 2), PRIME) if eq(prodInv, 0) { mstore(0, 0x08c379a000000000000000000000000000000000000000000000000000000000) mstore(0x4, 0x20) mstore(0x24, 0x1e) mstore(0x44, "Batch inverse product is zero.") revert(0, 0x62) } let currentPartialProductPtr := productsPtr let midPartialProductPtr := add(firstPartialProductPtr, 0xe0) currentPartialProductPtr := sub(currentPartialProductPtr, 0x20) mstore(currentPartialProductPtr, mulmod(mload(currentPartialProductPtr), prodInv, PRIME)) prodInv := mulmod(prodInv, mload(add(currentPartialProductPtr, productsToValuesOffset)), PRIME) currentPartialProductPtr := sub(currentPartialProductPtr, 0x20) mstore(currentPartialProductPtr, mulmod(mload(currentPartialProductPtr), prodInv, PRIME)) prodInv := mulmod(prodInv, mload(add(currentPartialProductPtr, productsToValuesOffset)), PRIME) currentPartialProductPtr := sub(currentPartialProductPtr, 0x20) mstore(currentPartialProductPtr, mulmod(mload(currentPartialProductPtr), prodInv, PRIME)) prodInv := mulmod(prodInv, mload(add(currentPartialProductPtr, productsToValuesOffset)), PRIME) currentPartialProductPtr := sub(currentPartialProductPtr, 0x20) mstore(currentPartialProductPtr, mulmod(mload(currentPartialProductPtr), prodInv, PRIME)) prodInv := mulmod(prodInv, mload(add(currentPartialProductPtr, productsToValuesOffset)), PRIME) currentPartialProductPtr := sub(currentPartialProductPtr, 0x20) mstore(currentPartialProductPtr, mulmod(mload(currentPartialProductPtr), prodInv, PRIME)) prodInv := mulmod(prodInv, mload(add(currentPartialProductPtr, productsToValuesOffset)), PRIME) currentPartialProductPtr := sub(currentPartialProductPtr, 0x20) mstore(currentPartialProductPtr, mulmod(mload(currentPartialProductPtr), prodInv, PRIME)) prodInv := mulmod(prodInv, mload(add(currentPartialProductPtr, productsToValuesOffset)), PRIME) currentPartialProductPtr := sub(currentPartialProductPtr, 0x20) mstore(currentPartialProductPtr, mulmod(mload(currentPartialProductPtr), prodInv, PRIME)) prodInv := mulmod(prodInv, mload(add(currentPartialProductPtr, productsToValuesOffset)), PRIME) currentPartialProductPtr := sub(currentPartialProductPtr, 0x20) mstore(currentPartialProductPtr, mulmod(mload(currentPartialProductPtr), prodInv, PRIME)) prodInv := mulmod(prodInv, mload(add(currentPartialProductPtr, productsToValuesOffset)), PRIME) for { } gt(currentPartialProductPtr, midPartialProductPtr) { } { }
7,338,195
// SPDX-License-Identifier: MIT pragma solidity ^0.8.2; import "@openzeppelin/contracts/token/ERC721/ERC721.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/utils/Counters.sol"; /// @title ERC721 NFT for TP /// @author PonziCoin, Kyle Stargarden, penguin /// @dev Built using output from the OpenZeppelin Contracts Wizard: https://wizard.openzeppelin.com/#erc721 /// @notice Rainbow Roll (ROLLS) NFTs are in short supply. Get them while they last. interface FungibleTokens { function balanceOf(address account) external view returns (uint256); } contract NFTP is ERC721, Ownable { using Counters for Counters.Counter; Counters.Counter private _tokenIdCounter; string public baseTokenURI; string public METADATA_PROVENANCE_HASH; uint256 public maxMint = 20; uint256 public price = 1337 * 10**14; //0.1337 ETH; bool public salePaused = true; bool public presalePaused = true; uint public constant MAX_ENTRIES = 10000; uint public constant MAX_PRESALE = 1520; address promoAddress; address[] public whitelistERC721; address[] public whitelistERC20; uint[] public requiredERC20; constructor() ERC721("Rainbow Rolls", "ROLLS") { setBaseURI("http://nftp.fun/rolls/"); // Team gets 25 and 75 are minted for promo and giveaways _tokenIdCounter.increment(); promoAddress = 0x48B8cB893429D97F3fECbFe6301bdA1c6936d8d9; mint(promoAddress, 100); whitelistERC721 = [ 0xf1eF40f5aEa5D1501C1B8BCD216CF305764fca40, 0xBC4CA0EdA7647A8aB7C2061c2E118A18a936f13D, 0x711d2aC13b86BE157795B576dE4bbe6827564111, 0x30d5977e4C9B159C2d44461868Bdc7353C2e425b, 0x7F0AB6a57cfD191a202aB3F813eF9B851C77e618, 0xE203cDC6011879CDe80c6a1DcF322489e4786eB3, 0x8b13e88EAd7EF8075b58c94a7EB18A89FD729B18, 0xf7E1FEEf85B9c2337A087439AbF364b9DD21a562]; whitelistERC20 = [ 0x1e3a2446C729D34373B87FD2C9CBb39A93198658, 0xa6610Ed604047e7B76C1DA288172D15BcdA57596, 0x26FA3fFFB6EfE8c1E69103aCb4044C26B9A106a9, 0x2d94AA3e47d9D5024503Ca8491fcE9A2fB4DA198, 0xDe30da39c46104798bB5aA3fe8B9e0e1F348163F, 0x5dD57Da40e6866C9FcC34F4b6DDC89F1BA740DfE, 0xD56daC73A4d6766464b38ec6D91eB45Ce7457c44, 0x87b008E57F640D94Ee44Fd893F0323AF933F9195, 0x3472A5A71965499acd81997a54BBA8D852C6E53d, 0x34A01C0A95B0592cc818Cd846c3Cf285d6C85A31, 0x6b4d5e9ec2aceA23D4110F4803Da99E25443c5Df]; requiredERC20 = [ 200000000000000000000, 1000000000000000000, 100000000000000000000000, 10000000000000000000000, 100000000000000000000, 500000000000000000000, 2000000000000000000000, 100000000000000000000, 40000000000000000000, 8000000000000000000, 1000000000000000000]; } /** * @dev Public function for purchasing {num} amount of tokens. Checks for current price. * Calls mint() for minting processs * @param _to recipient of the NFT minted * @param _num number of NFTs minted (Max is 20) */ function buy(address _to, uint256 _num) public payable { require(!salePaused, "Sale hasn't started"); require(_num < (maxMint+1),"You can mint a maximum of 20 NFTPs at a time"); require(msg.value >= price * _num,"Ether amount sent is not correct"); mint(_to, _num); } /** * @dev Public function for purchasing presale {num} amount of tokens. Requires whitelistEligible() * Calls mint() for minting processs * @param _to recipient of the NFT minted * @param _num number of NFTs minted (Max is 20) */ function presale(address _to, uint256 _num) public payable { require(!presalePaused, "Presale hasn't started"); require(whitelistEligible(_to), "You're not eligible for the presale"); require(_num < (maxMint+1),"You can mint a maximum of 20 NFTPs at a time"); require(msg.value >= price * _num,"Ether amount sent is not correct"); mint(_to, _num); } /** * @dev Private function for minting. Should not be called outside of buy(), presale() or the constructor * Wraps around _safeMint() to enable batch minting * @param _to recipient of the NFT minted * @param _num number of NFTs minted */ function mint(address _to, uint256 _num) private { require(_tokenIdCounter.current() + _num < MAX_ENTRIES, "Exceeds maximum supply"); for(uint256 i; i < _num; i++){ _safeMint( _to, _tokenIdCounter.current()); _tokenIdCounter.increment(); } } /** * @dev Public function for checking whitelist eligibility. * Called in the presale() function * @param _to verify address is eligible for presale */ function whitelistEligible(address _to) public view returns (bool) { if(_ERC721Eligible(_to) || _ERC20Eligible(_to)) { return true; } else { return false; } } /** * @dev Private helper function returning eligibility for presale * @param _to address to check balanceOf() ERC721 */ function _ERC721Eligible(address _to) private view returns (bool) { for (uint i=0; i < whitelistERC721.length; i++) { if (IERC721(whitelistERC721[i]).balanceOf(_to) > 0) { return true; } } return false; } /** * @dev Private helper function returning eligibility for presale * @param _to address to check balanceOf() ERC20 against requirements */ function _ERC20Eligible(address _to) private view returns (bool) { for (uint i=0; i < whitelistERC20.length; i++) { if (FungibleTokens(whitelistERC20[i]).balanceOf(_to) >= requiredERC20[i]) { return true; } } return false; } /** * @dev Function for setting the BaseURI. * Intended for onlyOwner to call in the case the URI details need to be relocated */ function setBaseURI(string memory _baseTokenURI) public onlyOwner { baseTokenURI = _baseTokenURI; } /** * @dev Function for reading total minted Rainbow Rolls * Intended for displaying Rainbow Roll minting stats during sale */ function totalCount() external view returns (uint256) { return _tokenIdCounter.current(); } /** * @dev Function for overriding behavior of _baseURI() virtual function from ERC721 base contract */ function _baseURI() internal view override returns (string memory) { return baseTokenURI; } /** * @dev Function for setting provenance hash which verifies no data was altered during or after sale * Helps provide added security for staged metadata and asset uploading during sale * @param _hash signature of the entire collection's assets and metadata */ function setProvenanceHash(string memory _hash) public onlyOwner { METADATA_PROVENANCE_HASH = _hash; } /** @dev Function for withdrawing sale ETH * Allows hungry monkeys to taste the bananas */ function withdrawAll() public onlyOwner { require(payable(owner()).send(address(this).balance)); } /** * @dev Function for the owner to start or pause the sale depending on {bool}. */ function setSalePauseStatus(bool val) public onlyOwner { salePaused = val; } /** * @dev Function for the owner to start or pause the presale depending on {bool}. */ function setPresalePauseStatus(bool val) public onlyOwner { presalePaused = val; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @title Counters * @author Matt Condon (@shrugs) * @dev Provides counters that can only be incremented, decremented or reset. This can be used e.g. to track the number * of elements in a mapping, issuing ERC721 ids, or counting request ids. * * Include with `using Counters for Counters.Counter;` */ library Counters { struct Counter { // This variable should never be directly accessed by users of the library: interactions must be restricted to // the library's function. As of Solidity v0.5.2, this cannot be enforced, though there is a proposal to add // this feature: see https://github.com/ethereum/solidity/issues/4637 uint256 _value; // default: 0 } function current(Counter storage counter) internal view returns (uint256) { return counter._value; } function increment(Counter storage counter) internal { unchecked { counter._value += 1; } } function decrement(Counter storage counter) internal { uint256 value = counter._value; require(value > 0, "Counter: decrement overflow"); unchecked { counter._value = value - 1; } } function reset(Counter storage counter) internal { counter._value = 0; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../utils/Context.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() { _setOwner(_msgSender()); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { _setOwner(address(0)); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); _setOwner(newOwner); } function _setOwner(address newOwner) private { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./IERC721.sol"; import "./IERC721Receiver.sol"; import "./extensions/IERC721Metadata.sol"; import "../../utils/Address.sol"; import "../../utils/Context.sol"; import "../../utils/Strings.sol"; import "../../utils/introspection/ERC165.sol"; /** * @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including * the Metadata extension, but not including the Enumerable extension, which is available separately as * {ERC721Enumerable}. */ contract ERC721 is Context, ERC165, IERC721, IERC721Metadata { using Address for address; using Strings for uint256; // Token name string private _name; // Token symbol string private _symbol; // Mapping from token ID to owner address mapping(uint256 => address) private _owners; // Mapping owner address to token count mapping(address => uint256) private _balances; // Mapping from token ID to approved address mapping(uint256 => address) private _tokenApprovals; // Mapping from owner to operator approvals mapping(address => mapping(address => bool)) private _operatorApprovals; /** * @dev Initializes the contract by setting a `name` and a `symbol` to the token collection. */ constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { return interfaceId == type(IERC721).interfaceId || interfaceId == type(IERC721Metadata).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) public view virtual override returns (uint256) { require(owner != address(0), "ERC721: balance query for the zero address"); return _balances[owner]; } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view virtual override returns (address) { address owner = _owners[tokenId]; require(owner != address(0), "ERC721: owner query for nonexistent token"); return owner; } /** * @dev See {IERC721Metadata-name}. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev See {IERC721Metadata-symbol}. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); string memory baseURI = _baseURI(); return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : ""; } /** * @dev Base URI for computing {tokenURI}. If set, the resulting URI for each * token will be the concatenation of the `baseURI` and the `tokenId`. Empty * by default, can be overriden in child contracts. */ function _baseURI() internal view virtual returns (string memory) { return ""; } /** * @dev See {IERC721-approve}. */ function approve(address to, uint256 tokenId) public virtual override { address owner = ERC721.ownerOf(tokenId); require(to != owner, "ERC721: approval to current owner"); require( _msgSender() == owner || isApprovedForAll(owner, _msgSender()), "ERC721: approve caller is not owner nor approved for all" ); _approve(to, tokenId); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view virtual override returns (address) { require(_exists(tokenId), "ERC721: approved query for nonexistent token"); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { require(operator != _msgSender(), "ERC721: approve to caller"); _operatorApprovals[_msgSender()][operator] = approved; emit ApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC721-isApprovedForAll}. */ function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev See {IERC721-transferFrom}. */ function transferFrom( address from, address to, uint256 tokenId ) public virtual override { //solhint-disable-next-line max-line-length require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _transfer(from, to, tokenId); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId ) public virtual override { safeTransferFrom(from, to, tokenId, ""); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory _data ) public virtual override { require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _safeTransfer(from, to, tokenId, _data); } /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * `_data` is additional data, it has no specified format and it is sent in call to `to`. * * This internal function is equivalent to {safeTransferFrom}, and can be used to e.g. * implement alternative mechanisms to perform token transfer, such as signature-based. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeTransfer( address from, address to, uint256 tokenId, bytes memory _data ) internal virtual { _transfer(from, to, tokenId); require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); } /** * @dev Returns whether `tokenId` exists. * * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}. * * Tokens start existing when they are minted (`_mint`), * and stop existing when they are burned (`_burn`). */ function _exists(uint256 tokenId) internal view virtual returns (bool) { return _owners[tokenId] != address(0); } /** * @dev Returns whether `spender` is allowed to manage `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) { require(_exists(tokenId), "ERC721: operator query for nonexistent token"); address owner = ERC721.ownerOf(tokenId); return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender)); } /** * @dev Safely mints `tokenId` and transfers it to `to`. * * Requirements: * * - `tokenId` must not exist. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeMint(address to, uint256 tokenId) internal virtual { _safeMint(to, tokenId, ""); } /** * @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is * forwarded in {IERC721Receiver-onERC721Received} to contract recipients. */ function _safeMint( address to, uint256 tokenId, bytes memory _data ) internal virtual { _mint(to, tokenId); require( _checkOnERC721Received(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer" ); } /** * @dev Mints `tokenId` and transfers it to `to`. * * WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible * * Requirements: * * - `tokenId` must not exist. * - `to` cannot be the zero address. * * Emits a {Transfer} event. */ function _mint(address to, uint256 tokenId) internal virtual { require(to != address(0), "ERC721: mint to the zero address"); require(!_exists(tokenId), "ERC721: token already minted"); _beforeTokenTransfer(address(0), to, tokenId); _balances[to] += 1; _owners[tokenId] = to; emit Transfer(address(0), to, tokenId); } /** * @dev Destroys `tokenId`. * The approval is cleared when the token is burned. * * Requirements: * * - `tokenId` must exist. * * Emits a {Transfer} event. */ function _burn(uint256 tokenId) internal virtual { address owner = ERC721.ownerOf(tokenId); _beforeTokenTransfer(owner, address(0), tokenId); // Clear approvals _approve(address(0), tokenId); _balances[owner] -= 1; delete _owners[tokenId]; emit Transfer(owner, address(0), tokenId); } /** * @dev Transfers `tokenId` from `from` to `to`. * As opposed to {transferFrom}, this imposes no restrictions on msg.sender. * * Requirements: * * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * * Emits a {Transfer} event. */ function _transfer( address from, address to, uint256 tokenId ) internal virtual { require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own"); require(to != address(0), "ERC721: transfer to the zero address"); _beforeTokenTransfer(from, to, tokenId); // Clear approvals from the previous owner _approve(address(0), tokenId); _balances[from] -= 1; _balances[to] += 1; _owners[tokenId] = to; emit Transfer(from, to, tokenId); } /** * @dev Approve `to` to operate on `tokenId` * * Emits a {Approval} event. */ function _approve(address to, uint256 tokenId) internal virtual { _tokenApprovals[tokenId] = to; emit Approval(ERC721.ownerOf(tokenId), to, tokenId); } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address. * The call is not executed if the target address is not a contract. * * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function _checkOnERC721Received( address from, address to, uint256 tokenId, bytes memory _data ) private returns (bool) { if (to.isContract()) { try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) { return retval == IERC721Receiver.onERC721Received.selector; } catch (bytes memory reason) { if (reason.length == 0) { revert("ERC721: transfer to non ERC721Receiver implementer"); } else { assembly { revert(add(32, reason), mload(reason)) } } } } else { return true; } } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual {} } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./IERC165.sol"; /** * @dev Implementation of the {IERC165} interface. * * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check * for the additional interface id that will be supported. For example: * * ```solidity * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId); * } * ``` * * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation. */ abstract contract ERC165 is IERC165 { /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165).interfaceId; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev String operations. */ library Strings { bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef"; /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0x00"; } uint256 temp = value; uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return toHexString(value, length); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = _HEX_SYMBOLS[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); (bool success, bytes memory returndata) = target.delegatecall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../IERC721.sol"; /** * @title ERC-721 Non-Fungible Token Standard, optional metadata extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Metadata is IERC721 { /** * @dev Returns the token collection name. */ function name() external view returns (string memory); /** * @dev Returns the token collection symbol. */ function symbol() external view returns (string memory); /** * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token. */ function tokenURI(uint256 tokenId) external view returns (string memory); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ interface IERC721Receiver { /** * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom} * by `operator` from `from`, this function is called. * * It must return its Solidity selector to confirm the token transfer. * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted. * * The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`. */ function onERC721Received( address operator, address from, uint256 tokenId, bytes calldata data ) external returns (bytes4); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../../utils/introspection/IERC165.sol"; /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721 is IERC165 { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes calldata data ) external; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @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); }
Private helper function returning eligibility for presale _to address to check balanceOf() ERC721/
function _ERC721Eligible(address _to) private view returns (bool) { for (uint i=0; i < whitelistERC721.length; i++) { if (IERC721(whitelistERC721[i]).balanceOf(_to) > 0) { return true; } } return false; }
1,356,885
./full_match/80001/0xD238dD70E5376DA21274717eaa6053075c8b62b4/sources/contracts/TraderBalanceVault/TraderBalanceVault.sol
Interface checker _interfaceId The interface id to check/
function supportsInterface(bytes4 _interfaceId) public view virtual override returns (bool) { return super.supportsInterface(_interfaceId) || _interfaceId == type(ITraderBalanceVault).interfaceId; }
9,522,283
pragma solidity ^0.5.8; // pragma experimental ABIEncoderV2; contract MarkSheet { address public dean; address[] public teachers; address[] public students; // address[] public alumini; uint128[] allSubjects; string[] allBranches; // uint8[] public allSem; constructor() public { dean = msg.sender; teachers.push(0x29f6d395EF6c3f825734de2ac89535B94F7521Ce); checkTeacher[0x29f6d395EF6c3f825734de2ac89535B94F7521Ce].isTeacher = true; students.push(0x078928D9DEA17d88745d502e5C818B99FA8FD3fb); checkStudent[0x078928D9DEA17d88745d502e5C818B99FA8FD3fb].isStudent = true; } modifier _isDean { require(msg.sender == dean, "Not a dean"); _; } /*Write all test getters here*/ // function getAllBranches() public view returns(string[] memory){ // return allBranches; // } // function getAllSubjects() public view returns(uint128[] memory){ // return allSubjects; // } /* End test getters*/ /* Subject subDetails */ struct subjectDetails{ string subjectName; string subjectCode; bool isSubject; } // mapping subject ID with struct mapping(uint128 => subjectDetails) public subDetails; // adding subject details using above mapping function addSubDetails(uint128 _subID, string memory _subName, string memory _subCode) public _isDean returns(bool) { require(subDetails[_subID].isSubject != true, "Subject already present"); subDetails[_subID].subjectName = _subName; subDetails[_subID].subjectCode = _subCode; allSubjects.push(_subID); subDetails[_subID].isSubject = true; return true; } /*End of subject details*/ /* branch+sem details*/ // struct containing subjects in each branch struct branch{ uint128[] branchSubjects; uint8[] subjectSem; bool isBranch; } // add new branch (by admin/dean) function addBranch(string memory _branch) public _isDean returns(bool){ require(subInBranch[_branch].isBranch != true, "Branch already present"); allBranches.push(_branch); subInBranch[_branch].isBranch = true; return true; } // maps branch name with struct mapping(string => branch) subInBranch; // maps branch with id to check for duplicacy mapping(string => mapping(uint128 => bool)) checkSubInBranch; // maps Semester(1-8) with struct to store subjects mapping(uint8 => uint128[]) subInSem; // maps for duplicacy check mapping(string => mapping(uint8 => mapping(uint128 => bool))) checkSubInSemBranch; // adding subject in each branch function addSubInBranch(string memory _branch, uint128 _subID, uint8 _sem) public _isDean returns(bool){ require(subInBranch[_branch].isBranch == true, "Invalid branch"); require(subDetails[_subID].isSubject == true, "Invalid subject"); require(_sem>0&&_sem<=8, "Invalid semester"); require(checkSubInBranch[_branch][_subID] != true, "Subject already added in branch"); require(checkSubInSemBranch[_branch][_sem][_subID] != true, "Subject already added"); subInSem[_sem].push(_subID); checkSubInSemBranch[_branch][_sem][_subID] = true; subInBranch[_branch].branchSubjects.push(_subID); subInBranch[_branch].subjectSem.push(_sem); checkSubInBranch[_branch][_subID] = true; return true; } // getting subject of each branch function getSubFromBranch(string memory _branch) public view returns(uint128[] memory){ return subInBranch[_branch].branchSubjects; } //get subjects of each semester function getSubFromSem(uint8 _sem) public view returns(uint128[] memory){ return subInSem[_sem]; } /*end of branch/sem details*/ /* Working to get subjects if branch and semester are known*/ // mapping to store subjects with branch and semester // mapping(string => mapping(uint8 => uint128[])) getID; uint128[] public getID; // get subjects with known branch and semester function getSub(string memory _branch, uint8 _sem) public returns(uint128[] memory){ require(subInBranch[_branch].isBranch == true, "Invalid branch"); require(_sem>0&&_sem<=8, "Invalid sem"); uint128[] memory bSub = subInBranch[_branch].branchSubjects; // uint128[] memory semSub = subInSem[_sem]; uint8[] memory branchSemSub = subInBranch[_branch].subjectSem; delete getID; for(uint8 i = 0; i<bSub.length; i++){ // for(uint8 j=0; j<branchSemSub.length; j++){ if(branchSemSub[i] == _sem){ getID.push(bSub[i]); } else { continue; } // } } return getID; } /* end of working to get subjects with known branch and semester*/ /*Teachers details*/ //teacher struct struct teach{ string name; string branchIn; uint128[] subjects; bool isTeacher; } //checks teachers' address mapping(address => teach) public checkTeacher; // check duplicacy of subjects in each teacher's address mapping(address => mapping(uint128 => bool)) checkTeachSub; // add teacher function addTeacher(address _ad, string memory _name, string memory _branchIn, uint128 _subjects) public _isDean returns (bool){ require(checkTeacher[_ad].isTeacher != true, "Teacher already present"); require(subInBranch[_branchIn].isBranch == true, "Invalid branch"); require(subDetails[_subjects].isSubject == true, "Invalid subject"); require(checkSubInBranch[_branchIn][_subjects] == true, "Subject not in branch"); require(checkTeachSub[_ad][_subjects] != true, "Subject already alotted"); checkTeacher[_ad].name = _name; checkTeacher[_ad].branchIn = _branchIn; checkTeacher[_ad].subjects.push(_subjects); checkTeacher[_ad].isTeacher = true; checkTeachSub[_ad][_subjects] = true; teachers.push(_ad); return true; } // get all teachers' addresses function getTeachers() public view returns(address[] memory){ return teachers; } /*end of teachers details*/ /*Students details*/ //student struct struct student{ string name; string branchIn; string batch; uint8 sem; string class; bool isStudent; } //checks students' address mapping(address => student) public checkStudent; // student list according to branch mapping(string => address[]) branchStudent; // student list according to class mapping(string => address[]) classStudent; // student list according to sem mapping(uint8 => address[]) semStudent; // add student function addStudent(address _ad, string memory _name, string memory _branchIn, string memory _batch, string memory _class) public _isDean returns (bool){ require(checkStudent[_ad].isStudent != true, "Student already present"); require(subInBranch[_branchIn].isBranch == true, "Invalid branch"); // require(subDetails[_subjects].isSubject == true); checkStudent[_ad].name = _name; checkStudent[_ad].branchIn = _branchIn; checkStudent[_ad].batch = _batch; checkStudent[_ad].sem = 1; checkStudent[_ad].class = _class; checkStudent[_ad].isStudent = true; students.push(_ad); branchStudent[_branchIn].push(_ad); classStudent[_class].push(_ad); // semStudent[_].push(_ad); return true; } // get all students' addresses function getStudents() public view returns(address[] memory){ return students; } // get student from on branch function getBranchStudent(string memory _branch) public view returns(address[] memory){ return branchStudent[_branch]; } // get student from on branch function getClassStudent(string memory _class) public view returns(address[] memory){ return classStudent[_class]; } // store subjects mapping(address => uint128[]) public studentSubjects; // store subjects mapping(address => mapping(uint128 => bool)) public checkStudentSubjects; // get students subjects function getStudentSubs(address _studAd) public returns(uint128[] memory){ require(checkStudent[_studAd].isStudent == true, "Invalid student"); studentSubjects[_studAd] = getSub(checkStudent[_studAd].branchIn, checkStudent[_studAd].sem); for(uint128 i = 0 ; i < studentSubjects[_studAd].length; i++){ checkStudentSubjects[_studAd][studentSubjects[_studAd][i]] = true; } return studentSubjects[_studAd]; } /*end of students details*/ /*Student Marks*/ // store students' subjects' marks mapping(address=>mapping(uint128 => uint8)) public studentSubjectMarks; //enter subject marks by teacher function marks(address _studAd, uint128 _subject, uint8 _marks) public returns(bool){ require(checkTeacher[msg.sender].isTeacher == true, "Not a teacher"); require(checkStudent[_studAd].isStudent == true, "Invalid student"); require(checkTeachSub[msg.sender][_subject] == true, "Teacher dont have this subject"); require(checkStudentSubjects[_studAd][_subject] == true, "Student does not study this subject"); studentSubjectMarks[_studAd][_subject] = _marks; return true; } //display marks uint8[] public disMarks; function showMarks(address _studAd) public returns(uint8[] memory){ require(checkStudent[_studAd].isStudent == true, "Invalid student"); delete disMarks; for(uint8 i = 0; i<studentSubjects[_studAd].length; i++){ disMarks.push(studentSubjectMarks[_studAd][studentSubjects[_studAd][i]]); } return disMarks; } /*end of student marks*/ }
adding subject details using above mapping
function addSubDetails(uint128 _subID, string memory _subName, string memory _subCode) public _isDean returns(bool) { require(subDetails[_subID].isSubject != true, "Subject already present"); subDetails[_subID].subjectName = _subName; subDetails[_subID].subjectCode = _subCode; allSubjects.push(_subID); subDetails[_subID].isSubject = true; return true; }
14,057,038
./partial_match/1/0x8e07dCEA5c57e2b0b71f7BBf514A3cc5bAb2E96e/sources/LuminalUniverse.sol
leaf for allowlist merkle root
function _allowlistLeaf(address account) internal pure returns (bytes32) { return keccak256(abi.encodePacked(account)); }
15,769,192
pragma solidity ^0.5.11; import "openzeppelin-solidity/contracts/payment/escrow/RefundEscrow.sol"; import "openzeppelin-solidity/contracts/math/SafeMath.sol"; import "./lifecycle/Finalizable.sol"; import "./lifecycle/Timelock.sol"; /** * @title RefundableTask * @dev Allows creation of refundable task contract. */ contract RefundableTask is Finalizable, Timelock { using SafeMath for uint256; // Task state enum State { Active, Dispute, Success, Failure } event StateChanged(State oldState, State newState); event TaskFinished(string solutionUri); // Task uri string private _uri; // Task solution uri string private _solutionUri; // Task state State private _state; // Arbitrator that is going to close or enableRefunds for this task address private _arbitrator; // Refund escrow used to hold funds while task is running RefundEscrow private _escrow; /** * @dev Constructor, creates RefundableTask contract. * @param uri String URI where task info is located. * @param endTime The timestamp when lock release is enabled. * @param beneficiary address of the beneficiary to whom task is addressed. * @param arbitrator address of the arbitrator who will intervene in case od dispute. */ constructor (string memory uri, uint256 endTime, address payable beneficiary, address arbitrator) public Timelock(endTime) { require(bytes(uri).length != 0, "RefundableTask: task URI should not be empty"); require(beneficiary != address(0), "RefundableTask: Beneficiary address should not be 0x0"); require(arbitrator != address(0), "RefundableTask: Arbitrator address should not be 0x0"); require(beneficiary != arbitrator, "RefundableTask: Beneficiary and arbitrator should not be the same account"); _uri = uri; _state = State.Active; _arbitrator = arbitrator; _escrow = new RefundEscrow(beneficiary); } /// @return Checks if provided state Success or Failure. function isFinalState(State nextState) private pure returns (bool) { return nextState == State.Success || nextState == State.Failure; } /// @dev Throws if called with any state other than Success or Failure. modifier onlyFinalState(State nextState) { require(isFinalState(nextState), "RefundableTask: final state can only be Success or Failure"); _; } /// @dev Throws if called by any account other than the beneficiary. modifier onlyBeneficiary() { require(msg.sender == _escrow.beneficiary(), "RefundableTask: caller is not the beneficiary"); _; } /// @dev Throws if called by any account other than the arbitrator. modifier onlyArbitrer() { require(msg.sender == _arbitrator, "RefundableTask: caller is not the arbitrator"); _; } /// @return The URI that holds information for this task. function uri() public view returns (string memory) { return _uri; } /// @return The URI that holds information for this task's solution. function solutionUri() public view returns (string memory) { return _solutionUri; } /// @return The current state of the escrow. function state() public view returns (State) { return _state; } /// @return The beneficiary of the task. function beneficiary() public view returns (address) { return _escrow.beneficiary(); } /// @return The arbitrator of the task. function arbitrator() public view returns (address) { return _arbitrator; } /// @return Whether task is finished. function isFinished() public view returns (bool) { return bytes(_solutionUri).length > 0; } /// @return Whether task is resolved. function isResolved() public view returns (bool) { return isFinalState(_state); } /// @return Returns task total allocated funds. function taskBalance() public view returns (uint256) { return address(_escrow).balance; } /// @dev Fallback function used for ask fund forwarding. function () external payable { require(!isResolved(), "RefundableTask: can only accept funds while task in progress"); if (_state == State.Active) { fundTask(msg.sender); } else { fundDisputeResolution(); } } /** * @dev Task fund forwarding, sending funds to escrow. * @param refundee The address funds will be sent to if a refund occurs. */ function fundTask(address refundee) public payable { require(_state == State.Active, "RefundableTask: can only fund task while active"); require(refundee != address(0), "RefundableTask: refundee address should not be 0x0"); _escrow.deposit.value(msg.value)(refundee); } /// @dev Dispute resolution fund forwarding. function fundDisputeResolution() public payable { require(_state == State.Dispute, "RefundableTask: can only fund dispute resolution while in dispute"); } /** * @dev Investors can claim refunds here if task is unsuccessful. * @param refundee Whose refund will be claimed. */ function claimRefund(address payable refundee) public { require(isFinalized(), "RefundableTask: task contract should be finalized"); require(_state == State.Failure, "RefundableTask: refunds available only if task was a failure"); _escrow.withdraw(refundee); } /** * @dev Finish this task providing a solution. * @param solutionUri_ Solution URI for this task. */ function finish(string memory solutionUri_) public onlyBeneficiary { require(_state == State.Active, "RefundableTask: can only finish task while active"); require(bytes(solutionUri_).length != 0, "RefundableTask: solution URI should not be empty"); _solutionUri = solutionUri_; emit TaskFinished(_solutionUri); } /// @dev Accept this task on owner request. function accept() public onlyOwner { require(_state == State.Active, "RefundableTask: can only accept task while active"); require(isFinished(), "RefundableTask: can only accept task if finished"); finalize(State.Success); } /// @dev Fail this task because of timeout. function timeout() public { require(!isResolved(), "RefundableTask: can not timeout if task already resolved"); require(!isLocked(), "RefundableTask: can not timeout if task is still locked"); finalize(State.Failure); } /// @dev Fail this task on beneficiary request. function cancel() public onlyBeneficiary { require(_state == State.Active, "RefundableTask: can only cancel task while active"); finalize(State.Failure); } /// @dev Raise dispute for this task on beneficiary request. function raiseDispute() public payable onlyBeneficiary { require(_state == State.Active, "RefundableTask: can only raise dispute while active"); require(isFinished(), "RefundableTask: can only raise dispute if task finished"); emit StateChanged(_state, State.Dispute); _state = State.Dispute; } /** * @dev Resolve dispute for this task. * @param newState The new state that will solve the dispute. */ function resolveDispute(State newState) public onlyArbitrer { require(_state == State.Dispute, "RefundableTask: can only resolve dispute while in dispute"); finalize(newState); } /// @dev Transfer all Ether held by the contract to the owner. function reclaimEther() external onlyOwner onlyFinalState(_state) { address payable _owner = address(uint160(owner())); _owner.transfer(address(this).balance); } /** * @dev Move contract to a final state. * @param newState The final state. */ function finalize(State newState) private { emit StateChanged(_state, newState); _state = newState; _transferOwnership(msg.sender); finalize(); } /// @dev Finalization task, called when finalize() is called. function _finalization() internal onlyFinalState(_state) { if (_state == State.Success) { _escrow.close(); _escrow.beneficiaryWithdraw(); } else { _escrow.enableRefunds(); } super._finalization(); } }
return The beneficiary of the task.
function beneficiary() public view returns (address) { return _escrow.beneficiary(); }
5,511,573
// Copyright (c) 2018 Devnetwork // license that can be found in the LICENSE file. pragma solidity ^0.4.18; import "zeppelin-solidity/contracts/token/ERC20/StandardToken.sol"; import "zeppelin-solidity/contracts/token/ERC20/BurnableToken.sol"; import "zeppelin-solidity/contracts/token/ERC20/TokenTimelock.sol"; import "zeppelin-solidity/contracts/ownership/Ownable.sol"; contract DEVToken is StandardToken, BurnableToken, Ownable { using SafeMath for uint256; // Constants string public name = "DEVToken"; string public symbol = "DEV"; uint8 public decimals = 18; uint256 public constant INITIAL_SUPPLY = 400000000 * (10 ** uint256(decimals)); bool public transferEnabled = false; // indicates that tokens can transfer or not function DEVToken() public { totalSupply_ = INITIAL_SUPPLY; // mint token balances[msg.sender] = INITIAL_SUPPLY; Transfer(address(0x0), msg.sender, INITIAL_SUPPLY); } /** * @dev Method for spreading devnetwork token to many addresses * @param _to multiple address for sending token to * @param _valueInWei amounts of devnetwork token in wei */ function spreadTokenAddresses(address[] _to, uint256[] _valueInWei) public onlyOwner { for (uint256 i = 0 ; i < _to.length ; i++) { spreadToken(_to[i], _valueInWei[i]); } } /** * @dev Method for spreading devnetwork token to one address * @param _to address for sending token to * @param _valueInWei amount of devnetwork token in wei */ function spreadToken(address _to, uint256 _valueInWei) public onlyOwner { balances[_to] = balances[_to].add(_valueInWei); balances[msg.sender] = balances[msg.sender].sub(_valueInWei); Transfer(msg.sender, _to, _valueInWei); } /** * @dev Enable transfer, and it is not possible to disable transfer again */ function enableTransfer() external onlyOwner { transferEnabled = true; } /** * @dev Overrides ERC20 transfer function with modifier that prevents the * ability to transfer tokens until after transfers have been enabled. */ function transfer(address _to, uint256 _value) public returns (bool) { require(transferEnabled); return super.transfer(_to, _value); } /** * @dev Overrides ERC20 transfer function with modifier that prevents the * ability to transfer tokens until after transfers have been enabled. */ function transferFrom(address _from, address _to, uint256 _value) public returns (bool) { require(transferEnabled); return super.transferFrom(_from, _to, _value); } /** * Overrides the burn function so that it cannot be called until after * transfers have been enabled. * @param _value The amount of devnetwork tokens in wei */ function burn(uint256 _value) public { require(transferEnabled || msg.sender == owner); super.burn(_value); } }
Overrides ERC20 transfer function with modifier that prevents the ability to transfer tokens until after transfers have been enabled./
function transferFrom(address _from, address _to, uint256 _value) public returns (bool) { require(transferEnabled); return super.transferFrom(_from, _to, _value); }
1,042,525
// SPDX-License-Identifier: MIT pragma solidity =0.8.10; pragma experimental ABIEncoderV2; abstract contract IDFSRegistry { function getAddr(bytes4 _id) public view virtual returns (address); function addNewContract( bytes32 _id, address _contractAddr, uint256 _waitPeriod ) public virtual; function startContractChange(bytes32 _id, address _newContractAddr) public virtual; function approveContractChange(bytes32 _id) public virtual; function cancelContractChange(bytes32 _id) public virtual; function changeWaitPeriod(bytes32 _id, uint256 _newWaitPeriod) public virtual; } interface IERC20 { function name() external view returns (string memory); function symbol() external view returns (string memory); function decimals() external view returns (uint256 digits); function totalSupply() external view returns (uint256 supply); function balanceOf(address _owner) external view returns (uint256 balance); function transfer(address _to, uint256 _value) external returns (bool success); function transferFrom( address _from, address _to, uint256 _value ) external returns (bool success); function approve(address _spender, uint256 _value) external returns (bool success); function allowance(address _owner, address _spender) external view returns (uint256 remaining); event Approval(address indexed _owner, address indexed _spender, uint256 _value); } library Address { //insufficient balance error InsufficientBalance(uint256 available, uint256 required); //unable to send value, recipient may have reverted error SendingValueFail(); //insufficient balance for call error InsufficientBalanceForCall(uint256 available, uint256 required); //call to non-contract error NonContractCall(); 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 { uint256 balance = address(this).balance; if (balance < amount){ revert InsufficientBalance(balance, amount); } // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{value: amount}(""); if (!(success)){ revert SendingValueFail(); } } 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) { uint256 balance = address(this).balance; if (balance < value){ revert InsufficientBalanceForCall(balance, value); } return _functionCallWithValue(target, data, value, errorMessage); } function _functionCallWithValue( address target, bytes memory data, uint256 weiValue, string memory errorMessage ) private returns (bytes memory) { if (!(isContract(target))){ revert NonContractCall(); } // 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); } } } } 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) { // 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; } 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; } } 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 Edited so it always first approves 0 and then the value, because of non standard tokens function safeApprove( IERC20 token, address spender, uint256 value ) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, 0)); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance( IERC20 token, address spender, uint256 value ) internal { uint256 newAllowance = token.allowance(address(this), spender).add(value); _callOptionalReturn( token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance) ); } function safeDecreaseAllowance( IERC20 token, address spender, uint256 value ) internal { uint256 newAllowance = token.allowance(address(this), spender).sub( value, "SafeERC20: decreased allowance below zero" ); _callOptionalReturn( token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance) ); } function _callOptionalReturn(IERC20 token, bytes memory data) private { bytes memory returndata = address(token).functionCall( data, "SafeERC20: low-level call failed" ); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } contract MainnetAuthAddresses { address internal constant ADMIN_VAULT_ADDR = 0xCCf3d848e08b94478Ed8f46fFead3008faF581fD; address internal constant FACTORY_ADDRESS = 0x5a15566417e6C1c9546523066500bDDBc53F88C7; address internal constant ADMIN_ADDR = 0x25eFA336886C74eA8E282ac466BdCd0199f85BB9; // USED IN ADMIN VAULT CONSTRUCTOR } contract AuthHelper is MainnetAuthAddresses { } contract AdminVault is AuthHelper { address public owner; address public admin; error SenderNotAdmin(); constructor() { owner = msg.sender; admin = ADMIN_ADDR; } /// @notice Admin is able to change owner /// @param _owner Address of new owner function changeOwner(address _owner) public { if (admin != msg.sender){ revert SenderNotAdmin(); } owner = _owner; } /// @notice Admin is able to set new admin /// @param _admin Address of multisig that becomes new admin function changeAdmin(address _admin) public { if (admin != msg.sender){ revert SenderNotAdmin(); } admin = _admin; } } contract AdminAuth is AuthHelper { using SafeERC20 for IERC20; AdminVault public constant adminVault = AdminVault(ADMIN_VAULT_ADDR); error SenderNotOwner(); error SenderNotAdmin(); modifier onlyOwner() { if (adminVault.owner() != msg.sender){ revert SenderNotOwner(); } _; } modifier onlyAdmin() { if (adminVault.admin() != msg.sender){ revert SenderNotAdmin(); } _; } /// @notice withdraw stuck funds function withdrawStuckFunds(address _token, address _receiver, uint256 _amount) public onlyOwner { if (_token == 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE) { payable(_receiver).transfer(_amount); } else { IERC20(_token).safeTransfer(_receiver, _amount); } } /// @notice Destroy the contract function kill() public onlyAdmin { selfdestruct(payable(msg.sender)); } } contract DFSRegistry is AdminAuth { error EntryAlreadyExistsError(bytes4); error EntryNonExistentError(bytes4); error EntryNotInChangeError(bytes4); error ChangeNotReadyError(uint256,uint256); error EmptyPrevAddrError(bytes4); error AlreadyInContractChangeError(bytes4); error AlreadyInWaitPeriodChangeError(bytes4); event AddNewContract(address,bytes4,address,uint256); event RevertToPreviousAddress(address,bytes4,address,address); event StartContractChange(address,bytes4,address,address); event ApproveContractChange(address,bytes4,address,address); event CancelContractChange(address,bytes4,address,address); event StartWaitPeriodChange(address,bytes4,uint256); event ApproveWaitPeriodChange(address,bytes4,uint256,uint256); event CancelWaitPeriodChange(address,bytes4,uint256,uint256); struct Entry { address contractAddr; uint256 waitPeriod; uint256 changeStartTime; bool inContractChange; bool inWaitPeriodChange; bool exists; } mapping(bytes4 => Entry) public entries; mapping(bytes4 => address) public previousAddresses; mapping(bytes4 => address) public pendingAddresses; mapping(bytes4 => uint256) public pendingWaitTimes; /// @notice Given an contract id returns the registered address /// @dev Id is keccak256 of the contract name /// @param _id Id of contract function getAddr(bytes4 _id) public view returns (address) { return entries[_id].contractAddr; } /// @notice Helper function to easily query if id is registered /// @param _id Id of contract function isRegistered(bytes4 _id) public view returns (bool) { return entries[_id].exists; } /////////////////////////// OWNER ONLY FUNCTIONS /////////////////////////// /// @notice Adds a new contract to the registry /// @param _id Id of contract /// @param _contractAddr Address of the contract /// @param _waitPeriod Amount of time to wait before a contract address can be changed function addNewContract( bytes4 _id, address _contractAddr, uint256 _waitPeriod ) public onlyOwner { if (entries[_id].exists){ revert EntryAlreadyExistsError(_id); } entries[_id] = Entry({ contractAddr: _contractAddr, waitPeriod: _waitPeriod, changeStartTime: 0, inContractChange: false, inWaitPeriodChange: false, exists: true }); emit AddNewContract(msg.sender, _id, _contractAddr, _waitPeriod); } /// @notice Reverts to the previous address immediately /// @dev In case the new version has a fault, a quick way to fallback to the old contract /// @param _id Id of contract function revertToPreviousAddress(bytes4 _id) public onlyOwner { if (!(entries[_id].exists)){ revert EntryNonExistentError(_id); } if (previousAddresses[_id] == address(0)){ revert EmptyPrevAddrError(_id); } address currentAddr = entries[_id].contractAddr; entries[_id].contractAddr = previousAddresses[_id]; emit RevertToPreviousAddress(msg.sender, _id, currentAddr, previousAddresses[_id]); } /// @notice Starts an address change for an existing entry /// @dev Can override a change that is currently in progress /// @param _id Id of contract /// @param _newContractAddr Address of the new contract function startContractChange(bytes4 _id, address _newContractAddr) public onlyOwner { if (!entries[_id].exists){ revert EntryNonExistentError(_id); } if (entries[_id].inWaitPeriodChange){ revert AlreadyInWaitPeriodChangeError(_id); } entries[_id].changeStartTime = block.timestamp; // solhint-disable-line entries[_id].inContractChange = true; pendingAddresses[_id] = _newContractAddr; emit StartContractChange(msg.sender, _id, entries[_id].contractAddr, _newContractAddr); } /// @notice Changes new contract address, correct time must have passed /// @param _id Id of contract function approveContractChange(bytes4 _id) public onlyOwner { if (!entries[_id].exists){ revert EntryNonExistentError(_id); } if (!entries[_id].inContractChange){ revert EntryNotInChangeError(_id); } if (block.timestamp < (entries[_id].changeStartTime + entries[_id].waitPeriod)){// solhint-disable-line revert ChangeNotReadyError(block.timestamp, (entries[_id].changeStartTime + entries[_id].waitPeriod)); } address oldContractAddr = entries[_id].contractAddr; entries[_id].contractAddr = pendingAddresses[_id]; entries[_id].inContractChange = false; entries[_id].changeStartTime = 0; pendingAddresses[_id] = address(0); previousAddresses[_id] = oldContractAddr; emit ApproveContractChange(msg.sender, _id, oldContractAddr, entries[_id].contractAddr); } /// @notice Cancel pending change /// @param _id Id of contract function cancelContractChange(bytes4 _id) public onlyOwner { if (!entries[_id].exists){ revert EntryNonExistentError(_id); } if (!entries[_id].inContractChange){ revert EntryNotInChangeError(_id); } address oldContractAddr = pendingAddresses[_id]; pendingAddresses[_id] = address(0); entries[_id].inContractChange = false; entries[_id].changeStartTime = 0; emit CancelContractChange(msg.sender, _id, oldContractAddr, entries[_id].contractAddr); } /// @notice Starts the change for waitPeriod /// @param _id Id of contract /// @param _newWaitPeriod New wait time function startWaitPeriodChange(bytes4 _id, uint256 _newWaitPeriod) public onlyOwner { if (!entries[_id].exists){ revert EntryNonExistentError(_id); } if (entries[_id].inContractChange){ revert AlreadyInContractChangeError(_id); } pendingWaitTimes[_id] = _newWaitPeriod; entries[_id].changeStartTime = block.timestamp; // solhint-disable-line entries[_id].inWaitPeriodChange = true; emit StartWaitPeriodChange(msg.sender, _id, _newWaitPeriod); } /// @notice Changes new wait period, correct time must have passed /// @param _id Id of contract function approveWaitPeriodChange(bytes4 _id) public onlyOwner { if (!entries[_id].exists){ revert EntryNonExistentError(_id); } if (!entries[_id].inWaitPeriodChange){ revert EntryNotInChangeError(_id); } if (block.timestamp < (entries[_id].changeStartTime + entries[_id].waitPeriod)){ // solhint-disable-line revert ChangeNotReadyError(block.timestamp, (entries[_id].changeStartTime + entries[_id].waitPeriod)); } uint256 oldWaitTime = entries[_id].waitPeriod; entries[_id].waitPeriod = pendingWaitTimes[_id]; entries[_id].inWaitPeriodChange = false; entries[_id].changeStartTime = 0; pendingWaitTimes[_id] = 0; emit ApproveWaitPeriodChange(msg.sender, _id, oldWaitTime, entries[_id].waitPeriod); } /// @notice Cancel wait period change /// @param _id Id of contract function cancelWaitPeriodChange(bytes4 _id) public onlyOwner { if (!entries[_id].exists){ revert EntryNonExistentError(_id); } if (!entries[_id].inWaitPeriodChange){ revert EntryNotInChangeError(_id); } uint256 oldWaitPeriod = pendingWaitTimes[_id]; pendingWaitTimes[_id] = 0; entries[_id].inWaitPeriodChange = false; entries[_id].changeStartTime = 0; emit CancelWaitPeriodChange(msg.sender, _id, oldWaitPeriod, entries[_id].waitPeriod); } } abstract contract DSAuthority { function canCall( address src, address dst, bytes4 sig ) public view virtual returns (bool); } contract DSAuthEvents { event LogSetAuthority(address indexed authority); event LogSetOwner(address indexed owner); } contract DSAuth is DSAuthEvents { DSAuthority public authority; address public owner; constructor() { owner = msg.sender; emit LogSetOwner(msg.sender); } function setOwner(address owner_) public auth { owner = owner_; emit LogSetOwner(owner); } function setAuthority(DSAuthority authority_) public auth { authority = authority_; emit LogSetAuthority(address(authority)); } modifier auth { require(isAuthorized(msg.sender, msg.sig), "Not authorized"); _; } function isAuthorized(address src, bytes4 sig) internal view returns (bool) { if (src == address(this)) { return true; } else if (src == owner) { return true; } else if (authority == DSAuthority(address(0))) { return false; } else { return authority.canCall(src, address(this), sig); } } } contract DSNote { event LogNote( bytes4 indexed sig, address indexed guy, bytes32 indexed foo, bytes32 indexed bar, uint256 wad, bytes fax ) anonymous; modifier note { bytes32 foo; bytes32 bar; assembly { foo := calldataload(4) bar := calldataload(36) } emit LogNote(msg.sig, msg.sender, foo, bar, msg.value, msg.data); _; } } abstract contract DSProxy is DSAuth, DSNote { DSProxyCache public cache; // global cache for contracts constructor(address _cacheAddr) { if (!(setCache(_cacheAddr))){ require(isAuthorized(msg.sender, msg.sig), "Not authorized"); } } // solhint-disable-next-line no-empty-blocks receive() external payable {} // use the proxy to execute calldata _data on contract _code function execute(bytes memory _code, bytes memory _data) public payable virtual returns (address target, bytes32 response); function execute(address _target, bytes memory _data) public payable virtual returns (bytes32 response); //set new cache function setCache(address _cacheAddr) public payable virtual returns (bool); } contract DSProxyCache { mapping(bytes32 => address) cache; function read(bytes memory _code) public view returns (address) { bytes32 hash = keccak256(_code); return cache[hash]; } function write(bytes memory _code) public returns (address target) { assembly { target := create(0, add(_code, 0x20), mload(_code)) switch iszero(extcodesize(target)) case 1 { // throw if contract failed to deploy revert(0, 0) } } bytes32 hash = keccak256(_code); cache[hash] = target; } } contract DefisaverLogger { event RecipeEvent( address indexed caller, string indexed logName ); event ActionDirectEvent( address indexed caller, string indexed logName, bytes data ); function logRecipeEvent( string memory _logName ) public { emit RecipeEvent(msg.sender, _logName); } function logActionDirectEvent( string memory _logName, bytes memory _data ) public { emit ActionDirectEvent(msg.sender, _logName, _data); } } contract MainnetActionsUtilAddresses { address internal constant DFS_REG_CONTROLLER_ADDR = 0xF8f8B3C98Cf2E63Df3041b73f80F362a4cf3A576; address internal constant REGISTRY_ADDR = 0x287778F121F134C66212FB16c9b53eC991D32f5b; address internal constant DFS_LOGGER_ADDR = 0xcE7a977Cac4a481bc84AC06b2Da0df614e621cf3; } contract ActionsUtilHelper is MainnetActionsUtilAddresses { } abstract contract ActionBase is AdminAuth, ActionsUtilHelper { event ActionEvent( string indexed logName, bytes data ); DFSRegistry public constant registry = DFSRegistry(REGISTRY_ADDR); DefisaverLogger public constant logger = DefisaverLogger( DFS_LOGGER_ADDR ); //Wrong sub index value error SubIndexValueError(); //Wrong return index value error ReturnIndexValueError(); /// @dev Subscription params index range [128, 255] uint8 public constant SUB_MIN_INDEX_VALUE = 128; uint8 public constant SUB_MAX_INDEX_VALUE = 255; /// @dev Return params index range [1, 127] uint8 public constant RETURN_MIN_INDEX_VALUE = 1; uint8 public constant RETURN_MAX_INDEX_VALUE = 127; /// @dev If the input value should not be replaced uint8 public constant NO_PARAM_MAPPING = 0; /// @dev We need to parse Flash loan actions in a different way enum ActionType { FL_ACTION, STANDARD_ACTION, FEE_ACTION, CHECK_ACTION, CUSTOM_ACTION } /// @notice Parses inputs and runs the implemented action through a proxy /// @dev Is called by the RecipeExecutor chaining actions together /// @param _callData Array of input values each value encoded as bytes /// @param _subData Array of subscribed vales, replaces input values if specified /// @param _paramMapping Array that specifies how return and subscribed values are mapped in input /// @param _returnValues Returns values from actions before, which can be injected in inputs /// @return Returns a bytes32 value through DSProxy, each actions implements what that value is function executeAction( bytes memory _callData, bytes32[] memory _subData, uint8[] memory _paramMapping, bytes32[] memory _returnValues ) public payable virtual returns (bytes32); /// @notice Parses inputs and runs the single implemented action through a proxy /// @dev Used to save gas when executing a single action directly function executeActionDirect(bytes memory _callData) public virtual payable; /// @notice Returns the type of action we are implementing function actionType() public pure virtual returns (uint8); //////////////////////////// HELPER METHODS //////////////////////////// /// @notice Given an uint256 input, injects return/sub values if specified /// @param _param The original input value /// @param _mapType Indicated the type of the input in paramMapping /// @param _subData Array of subscription data we can replace the input value with /// @param _returnValues Array of subscription data we can replace the input value with function _parseParamUint( uint _param, uint8 _mapType, bytes32[] memory _subData, bytes32[] memory _returnValues ) internal pure returns (uint) { if (isReplaceable(_mapType)) { if (isReturnInjection(_mapType)) { _param = uint(_returnValues[getReturnIndex(_mapType)]); } else { _param = uint256(_subData[getSubIndex(_mapType)]); } } return _param; } /// @notice Given an addr input, injects return/sub values if specified /// @param _param The original input value /// @param _mapType Indicated the type of the input in paramMapping /// @param _subData Array of subscription data we can replace the input value with /// @param _returnValues Array of subscription data we can replace the input value with function _parseParamAddr( address _param, uint8 _mapType, bytes32[] memory _subData, bytes32[] memory _returnValues ) internal view returns (address) { if (isReplaceable(_mapType)) { if (isReturnInjection(_mapType)) { _param = address(bytes20((_returnValues[getReturnIndex(_mapType)]))); } else { /// @dev The last two values are specially reserved for proxy addr and owner addr if (_mapType == 254) return address(this); //DSProxy address if (_mapType == 255) return DSProxy(payable(address(this))).owner(); // owner of DSProxy _param = address(uint160(uint256(_subData[getSubIndex(_mapType)]))); } } return _param; } /// @notice Given an bytes32 input, injects return/sub values if specified /// @param _param The original input value /// @param _mapType Indicated the type of the input in paramMapping /// @param _subData Array of subscription data we can replace the input value with /// @param _returnValues Array of subscription data we can replace the input value with function _parseParamABytes32( bytes32 _param, uint8 _mapType, bytes32[] memory _subData, bytes32[] memory _returnValues ) internal pure returns (bytes32) { if (isReplaceable(_mapType)) { if (isReturnInjection(_mapType)) { _param = (_returnValues[getReturnIndex(_mapType)]); } else { _param = _subData[getSubIndex(_mapType)]; } } return _param; } /// @notice Checks if the paramMapping value indicated that we need to inject values /// @param _type Indicated the type of the input function isReplaceable(uint8 _type) internal pure returns (bool) { return _type != NO_PARAM_MAPPING; } /// @notice Checks if the paramMapping value is in the return value range /// @param _type Indicated the type of the input function isReturnInjection(uint8 _type) internal pure returns (bool) { return (_type >= RETURN_MIN_INDEX_VALUE) && (_type <= RETURN_MAX_INDEX_VALUE); } /// @notice Transforms the paramMapping value to the index in return array value /// @param _type Indicated the type of the input function getReturnIndex(uint8 _type) internal pure returns (uint8) { if (!(isReturnInjection(_type))){ revert SubIndexValueError(); } return (_type - RETURN_MIN_INDEX_VALUE); } /// @notice Transforms the paramMapping value to the index in sub array value /// @param _type Indicated the type of the input function getSubIndex(uint8 _type) internal pure returns (uint8) { if (_type < SUB_MIN_INDEX_VALUE){ revert ReturnIndexValueError(); } return (_type - SUB_MIN_INDEX_VALUE); } } abstract contract IWETH { function allowance(address, address) public virtual view returns (uint256); function balanceOf(address) public virtual view returns (uint256); function approve(address, uint256) public virtual; function transfer(address, uint256) public virtual returns (bool); function transferFrom( address, address, uint256 ) public virtual returns (bool); function deposit() public payable virtual; function withdraw(uint256) public virtual; } library TokenUtils { using SafeERC20 for IERC20; address public constant WETH_ADDR = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2; address public constant ETH_ADDR = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; function approveToken( address _tokenAddr, address _to, uint256 _amount ) internal { if (_tokenAddr == ETH_ADDR) return; if (IERC20(_tokenAddr).allowance(address(this), _to) < _amount) { IERC20(_tokenAddr).safeApprove(_to, _amount); } } function pullTokensIfNeeded( address _token, address _from, uint256 _amount ) internal returns (uint256) { // handle max uint amount if (_amount == type(uint256).max) { _amount = getBalance(_token, _from); } if (_from != address(0) && _from != address(this) && _token != ETH_ADDR && _amount != 0) { IERC20(_token).safeTransferFrom(_from, address(this), _amount); } return _amount; } function withdrawTokens( address _token, address _to, uint256 _amount ) internal returns (uint256) { if (_amount == type(uint256).max) { _amount = getBalance(_token, address(this)); } if (_to != address(0) && _to != address(this) && _amount != 0) { if (_token != ETH_ADDR) { IERC20(_token).safeTransfer(_to, _amount); } else { payable(_to).transfer(_amount); } } return _amount; } function depositWeth(uint256 _amount) internal { IWETH(WETH_ADDR).deposit{value: _amount}(); } function withdrawWeth(uint256 _amount) internal { IWETH(WETH_ADDR).withdraw(_amount); } function getBalance(address _tokenAddr, address _acc) internal view returns (uint256) { if (_tokenAddr == ETH_ADDR) { return _acc.balance; } else { return IERC20(_tokenAddr).balanceOf(_acc); } } function getTokenDecimals(address _token) internal view returns (uint256) { if (_token == ETH_ADDR) return 18; return IERC20(_token).decimals(); } } contract DSMath { function add(uint256 x, uint256 y) internal pure returns (uint256 z) { z = x + y; } function sub(uint256 x, uint256 y) internal pure returns (uint256 z) { z = x - y; } function mul(uint256 x, uint256 y) internal pure returns (uint256 z) { z = x * y; } function div(uint256 x, uint256 y) internal pure returns (uint256 z) { return x / y; } function min(uint256 x, uint256 y) internal pure returns (uint256 z) { return x <= y ? x : y; } function max(uint256 x, uint256 y) internal pure returns (uint256 z) { return x >= y ? x : y; } function imin(int256 x, int256 y) internal pure returns (int256 z) { return x <= y ? x : y; } function imax(int256 x, int256 y) internal pure returns (int256 z) { return x >= y ? x : y; } uint256 constant WAD = 10**18; uint256 constant RAY = 10**27; function wmul(uint256 x, uint256 y) internal pure returns (uint256 z) { z = add(mul(x, y), WAD / 2) / WAD; } function rmul(uint256 x, uint256 y) internal pure returns (uint256 z) { z = add(mul(x, y), RAY / 2) / RAY; } function wdiv(uint256 x, uint256 y) internal pure returns (uint256 z) { z = add(mul(x, WAD), y / 2) / y; } function rdiv(uint256 x, uint256 y) internal pure returns (uint256 z) { z = add(mul(x, RAY), y / 2) / y; } // This famous algorithm is called "exponentiation by squaring" // and calculates x^n with x as fixed-point and n as regular unsigned. // // It's O(log n), instead of O(n) for naive repeated multiplication. // // These facts are why it works: // // If n is even, then x^n = (x^2)^(n/2). // If n is odd, then x^n = x * x^(n-1), // and applying the equation for even x gives // x^n = x * (x^2)^((n-1) / 2). // // Also, EVM division is flooring and // floor[(n-1) / 2] = floor[n / 2]. // function rpow(uint256 x, uint256 n) internal pure returns (uint256 z) { z = n % 2 != 0 ? x : RAY; for (n /= 2; n != 0; n /= 2) { x = rmul(x, x); if (n % 2 != 0) { z = rmul(z, x); } } } } interface IWStEth { function wrap(uint256 _stETHAmount) external returns (uint256); function unwrap(uint256 _wstETHAmount) external returns (uint256); } contract MainnetLidoAddresses { address public constant lidoWrappedStEth = 0x7f39C581F595B53c5cb19bD0b3f8dA6c935E2Ca0; address public constant lidoStEth = 0xae7ab96520DE3A18E5e111B5EaAb095312D7fE84; } contract LidoHelper is MainnetLidoAddresses{ } contract LidoWrap is ActionBase, DSMath, LidoHelper { using TokenUtils for address; /// @param amount - amount to pull /// @param from - address from which to pull token from /// @param to - address where received WStEth will be sent to /// @param useWeth - true for using WETH, false for using stEth struct Params { uint256 amount; address from; address to; bool useWeth; } /// @inheritdoc ActionBase function executeAction( bytes memory _callData, bytes32[] memory _subData, uint8[] memory _paramMapping, bytes32[] memory _returnValues ) public payable virtual override returns (bytes32) { Params memory inputData = parseInputs(_callData); inputData.amount = _parseParamUint( inputData.amount, _paramMapping[0], _subData, _returnValues ); inputData.from = _parseParamAddr(inputData.from, _paramMapping[1], _subData, _returnValues); inputData.to = _parseParamAddr(inputData.to, _paramMapping[2], _subData, _returnValues); (uint256 wStEthReceivedAmount, bytes memory logData) = _lidoWrap(inputData); emit ActionEvent("LidoWrap", logData); return bytes32(wStEthReceivedAmount); } /// @inheritdoc ActionBase function executeActionDirect(bytes memory _callData) public payable override { Params memory inputData = parseInputs(_callData); (, bytes memory logData) = _lidoWrap(inputData); logger.logActionDirectEvent("LidoWrap", logData); } /// @inheritdoc ActionBase function actionType() public pure virtual override returns (uint8) { return uint8(ActionType.STANDARD_ACTION); } //////////////////////////// ACTION LOGIC //////////////////////////// function _lidoWrap(Params memory _inputData) internal returns (uint256 wStEthReceivedAmount, bytes memory logData){ require(_inputData.to != address(0), "Can't be sent to burn address"); require(_inputData.amount > 0, "Amount to wrap can't be 0"); if (_inputData.useWeth){ wStEthReceivedAmount = _lidoStakeAndWrapWETH(_inputData); }else{ wStEthReceivedAmount = _lidoWrapStEth(_inputData); } lidoWrappedStEth.withdrawTokens(_inputData.to, wStEthReceivedAmount); logData = abi.encode(_inputData, wStEthReceivedAmount); } function _lidoStakeAndWrapWETH(Params memory _inputData) internal returns (uint256 wStEthReceivedAmount){ _inputData.amount = TokenUtils.WETH_ADDR.pullTokensIfNeeded(_inputData.from, _inputData.amount); TokenUtils.withdrawWeth(_inputData.amount); uint256 wStEthBalanceBefore = lidoWrappedStEth.getBalance(address(this)); (bool sent, ) = payable(lidoWrappedStEth).call{value: _inputData.amount}(""); require(sent, "Failed to send Ether"); uint256 wStEthBalanceAfter = lidoWrappedStEth.getBalance(address(this)); wStEthReceivedAmount = sub(wStEthBalanceAfter, wStEthBalanceBefore); } function _lidoWrapStEth(Params memory _inputData) internal returns (uint256 wStEthReceivedAmount){ _inputData.amount = lidoStEth.pullTokensIfNeeded(_inputData.from, _inputData.amount); lidoStEth.approveToken(lidoWrappedStEth, _inputData.amount); wStEthReceivedAmount = IWStEth(lidoWrappedStEth).wrap(_inputData.amount); } function parseInputs(bytes memory _callData) internal pure returns (Params memory inputData) { inputData = abi.decode(_callData, (Params)); } }
@inheritdoc ActionBase
function executeAction( bytes memory _callData, bytes32[] memory _subData, uint8[] memory _paramMapping, bytes32[] memory _returnValues ) public payable virtual override returns (bytes32) { Params memory inputData = parseInputs(_callData); inputData.amount = _parseParamUint( inputData.amount, _paramMapping[0], _subData, _returnValues ); inputData.from = _parseParamAddr(inputData.from, _paramMapping[1], _subData, _returnValues); inputData.to = _parseParamAddr(inputData.to, _paramMapping[2], _subData, _returnValues); (uint256 wStEthReceivedAmount, bytes memory logData) = _lidoWrap(inputData); emit ActionEvent("LidoWrap", logData); return bytes32(wStEthReceivedAmount); }
10,150,119
./full_match/4/0x412CaD145f63cD1884b8bAE4F2413F2604709231/sources/contracts/ERC721.sol
Unchecked because the only math done is incrementing the owner's nonce which cannot realistically overflow.
function permitAll( address owner, address operator, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) public virtual { require(block.timestamp <= deadline, "PERMIT_DEADLINE_EXPIRED"); unchecked { bytes32 digest = keccak256( abi.encodePacked( "\x19\x01", DOMAIN_SEPARATOR(), keccak256(abi.encode(PERMIT_ALL_TYPEHASH, owner, operator, noncesForAll[owner]++, deadline)) ) ); address recoveredAddress = ecrecover(digest, v, r, s); require( (recoveredAddress != address(0) && recoveredAddress == owner) || isApprovedForAll[owner][recoveredAddress], 'INVALID_PERMIT_SIGNATURE' ); } isApprovedForAll[owner][operator] = true; emit ApprovalForAll(owner, operator, true); }
13,365,643
// SPDX-License-Identifier: MIT // .d8888b. 888 888 // d88P Y88b 888 888 // Y88b. 888 888 // "Y888b. 88888b. .d88b. 888 888 // "Y88b. 888 "88b d8P Y8b 888 888 // "888 888 888 88888888 888 888 // Y88b d88P 888 d88P Y8b. 888 888 // "Y8888P" 88888P" "Y8888 888 888 // 888 // 888 // 888 // Special thanks to: // @BoringCrypto for his great libraries @ https://github.com/boringcrypto/BoringSolidity pragma solidity 0.6.12; // Contract: BoringOwnable // Audit on 5-Jan-2021 by Keno and BoringCrypto // Source: https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/access/Ownable.sol + Claimable.sol // Edited by BoringCrypto contract BoringOwnableData { address public owner; address public pendingOwner; } contract BoringOwnable is BoringOwnableData { event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /// @notice `owner` defaults to msg.sender on construction. constructor() public { owner = msg.sender; emit OwnershipTransferred(address(0), msg.sender); } /// @notice Transfers ownership to `newOwner`. Either directly or claimable by the new pending owner. /// Can only be invoked by the current `owner`. /// @param newOwner Address of the new owner. /// @param direct True if `newOwner` should be set immediately. False if `newOwner` needs to use `claimOwnership`. /// @param renounce Allows the `newOwner` to be `address(0)` if `direct` and `renounce` is True. Has no effect otherwise. function transferOwnership( address newOwner, bool direct, bool renounce ) public onlyOwner { if (direct) { // Checks require(newOwner != address(0) || renounce, "Ownable: zero address"); // Effects emit OwnershipTransferred(owner, newOwner); owner = newOwner; pendingOwner = address(0); } else { // Effects pendingOwner = newOwner; } } /// @notice Needs to be called by `pendingOwner` to claim ownership. function claimOwnership() public { address _pendingOwner = pendingOwner; // Checks require(msg.sender == _pendingOwner, "Ownable: caller != pending owner"); // Effects emit OwnershipTransferred(owner, _pendingOwner); owner = _pendingOwner; pendingOwner = address(0); } /// @notice Only allows the `owner` to execute the function. modifier onlyOwner() { require(msg.sender == owner, "Ownable: caller is not the owner"); _; } } contract Domain { bytes32 private constant DOMAIN_SEPARATOR_SIGNATURE_HASH = keccak256("EIP712Domain(uint256 chainId,address verifyingContract)"); // See https://eips.ethereum.org/EIPS/eip-191 string private constant EIP191_PREFIX_FOR_EIP712_STRUCTURED_DATA = "\x19\x01"; // solhint-disable var-name-mixedcase bytes32 private immutable _DOMAIN_SEPARATOR; uint256 private immutable DOMAIN_SEPARATOR_CHAIN_ID; /// @dev Calculate the DOMAIN_SEPARATOR function _calculateDomainSeparator(uint256 chainId) private view returns (bytes32) { return keccak256( abi.encode( DOMAIN_SEPARATOR_SIGNATURE_HASH, chainId, address(this) ) ); } constructor() public { uint256 chainId; assembly {chainId := chainid()} _DOMAIN_SEPARATOR = _calculateDomainSeparator(DOMAIN_SEPARATOR_CHAIN_ID = chainId); } /// @dev Return the DOMAIN_SEPARATOR // It's named internal to allow making it public from the contract that uses it by creating a simple view function // with the desired public name, such as DOMAIN_SEPARATOR or domainSeparator. // solhint-disable-next-line func-name-mixedcase function _domainSeparator() internal view returns (bytes32) { uint256 chainId; assembly {chainId := chainid()} return chainId == DOMAIN_SEPARATOR_CHAIN_ID ? _DOMAIN_SEPARATOR : _calculateDomainSeparator(chainId); } function _getDigest(bytes32 dataHash) internal view returns (bytes32 digest) { digest = keccak256( abi.encodePacked( EIP191_PREFIX_FOR_EIP712_STRUCTURED_DATA, _domainSeparator(), dataHash ) ); } } interface IERC20 { function totalSupply() external view returns (uint256); function balanceOf(address account) external view returns (uint256); function allowance(address owner, address spender) external view returns (uint256); function approve(address spender, uint256 amount) external returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); event Approval(address indexed owner, address indexed spender, uint256 value); /// @notice EIP 2612 function permit( address owner, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) external; } // Data part taken out for building of contracts that receive delegate calls contract ERC20Data { /// @notice owner > balance mapping. mapping(address => uint256) public balanceOf; /// @notice owner > spender > allowance mapping. mapping(address => mapping(address => uint256)) public allowance; /// @notice owner > nonce mapping. Used in `permit`. mapping(address => uint256) public nonces; } abstract contract ERC20 is IERC20, Domain { /// @notice owner > balance mapping. mapping(address => uint256) public override balanceOf; /// @notice owner > spender > allowance mapping. mapping(address => mapping(address => uint256)) public override allowance; /// @notice owner > nonce mapping. Used in `permit`. mapping(address => uint256) public nonces; event Transfer(address indexed _from, address indexed _to, uint256 _value); event Approval(address indexed _owner, address indexed _spender, uint256 _value); /// @notice Transfers `amount` tokens from `msg.sender` to `to`. /// @param to The address to move the tokens. /// @param amount of the tokens to move. /// @return (bool) Returns True if succeeded. function transfer(address to, uint256 amount) public returns (bool) { // If `amount` is 0, or `msg.sender` is `to` nothing happens if (amount != 0 || msg.sender == to) { uint256 srcBalance = balanceOf[msg.sender]; require(srcBalance >= amount, "ERC20: balance too low"); if (msg.sender != to) { require(to != address(0), "ERC20: no zero address"); // Moved down so low balance calls safe some gas balanceOf[msg.sender] = srcBalance - amount; // Underflow is checked balanceOf[to] += amount; } } emit Transfer(msg.sender, to, amount); return true; } /// @notice Transfers `amount` tokens from `from` to `to`. Caller needs approval for `from`. /// @param from Address to draw tokens from. /// @param to The address to move the tokens. /// @param amount The token amount to move. /// @return (bool) Returns True if succeeded. function transferFrom( address from, address to, uint256 amount ) public returns (bool) { // If `amount` is 0, or `from` is `to` nothing happens if (amount != 0) { uint256 srcBalance = balanceOf[from]; require(srcBalance >= amount, "ERC20: balance too low"); if (from != to) { uint256 spenderAllowance = allowance[from][msg.sender]; // If allowance is infinite, don't decrease it to save on gas (breaks with EIP-20). if (spenderAllowance != type(uint256).max) { require(spenderAllowance >= amount, "ERC20: allowance too low"); allowance[from][msg.sender] = spenderAllowance - amount; // Underflow is checked } require(to != address(0), "ERC20: no zero address"); // Moved down so other failed calls safe some gas balanceOf[from] = srcBalance - amount; // Underflow is checked balanceOf[to] += amount; } } emit Transfer(from, to, amount); return true; } /// @notice Approves `amount` from sender to be spend by `spender`. /// @param spender Address of the party that can draw from msg.sender's account. /// @param amount The maximum collective amount that `spender` can draw. /// @return (bool) Returns True if approved. function approve(address spender, uint256 amount) public override returns (bool) { allowance[msg.sender][spender] = amount; emit Approval(msg.sender, spender, amount); return true; } // solhint-disable-next-line func-name-mixedcase function DOMAIN_SEPARATOR() external view returns (bytes32) { return _domainSeparator(); } // keccak256("Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)"); bytes32 private constant PERMIT_SIGNATURE_HASH = 0x6e71edae12b1b97f4d1f60370fef10105fa2faae0126114a169c64845d6126c9; /// @notice Approves `value` from `owner_` to be spend by `spender`. /// @param owner_ Address of the owner. /// @param spender The address of the spender that gets approved to draw from `owner_`. /// @param value The maximum collective amount that `spender` can draw. /// @param deadline This permit must be redeemed before this deadline (UTC timestamp in seconds). function permit( address owner_, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) external override { require(owner_ != address(0), "ERC20: Owner cannot be 0"); require(block.timestamp < deadline, "ERC20: Expired"); require( ecrecover(_getDigest(keccak256(abi.encode(PERMIT_SIGNATURE_HASH, owner_, spender, value, nonces[owner_]++, deadline))), v, r, s) == owner_, "ERC20: Invalid Signature" ); allowance[owner_][spender] = value; emit Approval(owner_, spender, value); } } // Contract: BoringMath /// @notice A library for performing overflow-/underflow-safe math, /// updated with awesomeness from of DappHub (https://github.com/dapphub/ds-math). library BoringMath { function add(uint256 a, uint256 b) internal pure returns (uint256 c) { require((c = a + b) >= b, "BoringMath: Add Overflow"); } function sub(uint256 a, uint256 b) internal pure returns (uint256 c) { require((c = a - b) <= a, "BoringMath: Underflow"); } function mul(uint256 a, uint256 b) internal pure returns (uint256 c) { require(b == 0 || (c = a * b) / b == a, "BoringMath: Mul Overflow"); } } /// @title Spell /// @author 0xMerlin /// @dev This contract spreads Magic. contract Spell is ERC20, BoringOwnable { using BoringMath for uint256; // ERC20 'variables' string public constant symbol = "SPELL"; string public constant name = "Spell Token"; uint8 public constant decimals = 18; uint256 public override totalSupply; uint256 public constant MAX_SUPPLY = 420 * 1e27; function mint(address to, uint256 amount) public onlyOwner { require(to != address(0), "SPELL: no mint to zero address"); require(MAX_SUPPLY >= totalSupply.add(amount), "SPELL: Don't go over MAX"); totalSupply = totalSupply + amount; balanceOf[to] += amount; emit Transfer(address(0), to, amount); } }
Return the DOMAIN_SEPARATOR It's named internal to allow making it public from the contract that uses it by creating a simple view function with the desired public name, such as DOMAIN_SEPARATOR or domainSeparator. solhint-disable-next-line func-name-mixedcase
function _domainSeparator() internal view returns (bytes32) { return chainId == DOMAIN_SEPARATOR_CHAIN_ID ? _DOMAIN_SEPARATOR : _calculateDomainSeparator(chainId); }
916,879
pragma solidity ^0.8.0; // Copyright 2020 Keyko GmbH. // SPDX-License-Identifier: (Apache-2.0 AND CC-BY-4.0) // Code is Apache-2.0 and docs are CC-BY-4.0 import {IERC20, ILendingPool, ILendingPoolAddressesProvider, IProtocolDataProvider, IStableDebtToken, IPriceOracleGetter} from '../../../interfaces/IAaveInterfaces.sol'; import {SafeERC20, SafeMath} from '../../../libraries/AaveLibrary.sol'; import '../../../interfaces/IWETHGateway.sol'; import '@openzeppelin/contracts-upgradeable/token/ERC20/ERC20Upgradeable.sol'; import '@openzeppelin/contracts-upgradeable/token/ERC721/IERC721Upgradeable.sol'; import '@openzeppelin/contracts-upgradeable/token/ERC721/IERC721ReceiverUpgradeable.sol'; import '@openzeppelin/contracts-upgradeable/security/ReentrancyGuardUpgradeable.sol'; import '@openzeppelin/contracts-upgradeable/access/AccessControlUpgradeable.sol'; contract AaveCreditVault is ReentrancyGuardUpgradeable, IERC721ReceiverUpgradeable, AccessControlUpgradeable { using SafeERC20 for IERC20; using SafeMath for uint256; ILendingPool public lendingPool; IProtocolDataProvider public dataProvider; IWETHGateway public weth; ILendingPoolAddressesProvider private addressProvider; IPriceOracleGetter private priceOracle; address private borrowedAsset; uint256 private borrowedAmount; uint256 public nvmFee; uint256 public agreementFee; uint256 private constant FEE_BASE = 10000; address public treasuryAddress; address public borrower; address public lender; bytes32 public repayConditionId; address private nftAddress; uint256 private nftId; bytes32 public constant BORROWER_ROLE = keccak256('BORROWER_ROLE'); bytes32 public constant LENDER_ROLE = keccak256('LENDER_ROLE'); bytes32 public constant CONDITION_ROLE = keccak256('CONDITION_ROLE'); /** * Vault constructor, creates a unique vault for each agreement * @param _lendingPool Aave lending pool address * @param _dataProvider Aave data provider address * @param _weth WETH address * @param _nvmFee Nevermined fee that will apply to this agreeement * @param _agreementFee Agreement fee that lender will receive on agreement maturity * @param _treasuryAddress Address of nevermined contract to store fees */ constructor( address _lendingPool, address _dataProvider, address _weth, uint256 _nvmFee, uint256 _agreementFee, address _treasuryAddress, address _borrower, address _lender, address[] memory _conditions ) { lendingPool = ILendingPool(_lendingPool); dataProvider = IProtocolDataProvider(_dataProvider); weth = IWETHGateway(_weth); addressProvider = lendingPool.getAddressesProvider(); priceOracle = IPriceOracleGetter(addressProvider.getPriceOracle()); nvmFee = _nvmFee; agreementFee = _agreementFee; treasuryAddress = _treasuryAddress; borrower = _borrower; lender = _lender; AccessControlUpgradeable.__AccessControl_init(); AccessControlUpgradeable._setupRole(BORROWER_ROLE, _borrower); AccessControlUpgradeable._setupRole(LENDER_ROLE, _lender); for(uint256 i = 0; i < _conditions.length; i++){ AccessControlUpgradeable._setupRole(CONDITION_ROLE, _conditions[i]); } } function isLender( address _address ) public view returns (bool) { return hasRole(LENDER_ROLE, _address); } function isBorrower( address _address ) public view returns (bool) { return hasRole(BORROWER_ROLE, _address); } /** * Deposit function. Receives the funds from the delegator and deposits the funds * in the Aave contracts * @param _collateralAsset collateral asset that will be deposit on Aave * @param _amount Amount of collateral to deposit */ function deposit( address _collateralAsset, uint256 _amount ) public payable nonReentrant { if (msg.value == 0) _transferERC20(_collateralAsset, _amount); else { weth.depositETH{value: msg.value}(address(lendingPool), address(this), 0); } } /** * Appproves delegatee to borrow funds from Aave on behalf of delegator * @param _borrower delegatee that will borrow the funds * @param _amount Amount of funds to delegate * @param _asset Asset to delegate the borrow * @param _interestRateMode interest rate type stable 1, variable 2 */ function approveBorrower( address _borrower, uint256 _amount, address _asset, uint256 _interestRateMode ) public { require(hasRole(CONDITION_ROLE, msg.sender), 'Only conditions'); (, address stableDebtTokenAddress, address variableDebtTokenAddress ) = dataProvider .getReserveTokensAddresses(_asset); address assetAddress = _interestRateMode == 1 ? stableDebtTokenAddress : variableDebtTokenAddress; IStableDebtToken(assetAddress).approveDelegation( _borrower, _amount ); } /** * Return the actual delegated amount for the borrower in the specific asset * @param _borrower The borrower of the funds (i.e. delgatee) * @param _asset The asset they are allowed to borrow * @param _interestRateMode interest rate type stable 1, variable 2 */ function delegatedAmount( address _borrower, address _asset, uint256 _interestRateMode ) public view returns (uint256) { (, address stableDebtTokenAddress, address variableDebtTokenAddress ) = dataProvider .getReserveTokensAddresses(_asset); address assetAddress = _interestRateMode == 1 ? stableDebtTokenAddress : variableDebtTokenAddress; return IStableDebtToken(assetAddress).borrowAllowance( address(this), _borrower ); } /** * Borrower can call this function to borrow the delegated funds * @param _assetToBorrow The asset they are allowed to borrow * @param _amount Amount to borrow * @param _delgatee Address where the funds will be transfered * @param _interestRateMode interest rate type stable 1, variable 2 */ function borrow( address _assetToBorrow, uint256 _amount, address _delgatee, uint256 _interestRateMode ) public { require(hasRole(CONDITION_ROLE, msg.sender), 'Only conditions'); require(borrowedAmount == 0, 'Already borrowed'); borrowedAsset = _assetToBorrow; borrowedAmount = _amount; lendingPool.borrow(_assetToBorrow, _amount, _interestRateMode, 0, address(this)); IERC20(_assetToBorrow).transfer(_delgatee, _amount); } /** * Repay an uncollaterised loan * @param _asset The asset to be repaid * @param _interestRateMode interest rate type stable 1, variable 2 * @param _repayConditionId identifier of the condition id working as lock for other vault methods */ function repay( address _asset, uint256 _interestRateMode, bytes32 _repayConditionId ) public { require(hasRole(CONDITION_ROLE, msg.sender), 'Only conditions'); IERC20(_asset).approve(address(lendingPool), uint256(2**256 - 1)); lendingPool.repay(_asset, uint256(2**256 - 1), _interestRateMode, address(this)); require(getActualCreditDebt() == 0, 'Not enough amount to repay'); repayConditionId = _repayConditionId; } function setLockConditionId( bytes32 _repayConditionId ) public { require(hasRole(CONDITION_ROLE, msg.sender), 'Only conditions'); repayConditionId = _repayConditionId; } /** * Returns the borrowed amount from the delegatee on this agreement */ function getBorrowedAmount() public view returns (uint256) { return borrowedAmount; } /** * Returns the priceof the asset in the Aave oracles * @param _asset The asset to get the actual price */ function getAssetPrice( address _asset ) public view returns (uint256) { return priceOracle.getAssetPrice(_asset); } /** * Returns the total debt of the credit in the Aave protocol expressed in token units */ function getCreditAssetDebt() public view returns (uint256) { (, uint256 totalDebtETH, , , , ) = lendingPool.getUserAccountData( address(this) ); uint256 price = priceOracle.getAssetPrice(borrowedAsset); (uint256 _decimals, , , , , , , , , ) = dataProvider .getReserveConfigurationData(borrowedAsset); return totalDebtETH.div(price).mul(10**_decimals); } /** * Returns the total debt of the credit in the Aave protocol expressed in ETH units */ function getActualCreditDebt() public view returns (uint256) { (, uint256 totalDebtETH, , , , ) = lendingPool.getUserAccountData( address(this) ); return totalDebtETH; } /** * Returns the total actual debt of the agreement credit + fees in token units */ function getTotalActualDebt() public view returns (uint256) { uint256 creditDebt = getCreditAssetDebt(); uint256 delegatorFee = borrowedAmount.div(FEE_BASE).mul(agreementFee); uint256 nvmFeeAmount = borrowedAmount.div(FEE_BASE).mul(nvmFee); return creditDebt.add(delegatorFee).add(nvmFeeAmount); } /** * Withdraw all of a collateral as the underlying asset, if no outstanding loans delegated * @param _asset The underlying asset to withdraw * @param _delegator Delegator address that deposited the collateral */ function withdrawCollateral( address _asset, address _delegator ) public { require(hasRole(CONDITION_ROLE, msg.sender), 'Only conditions'); lendingPool.withdraw(_asset, uint256(2**256 - 1), _delegator); uint256 delegatorFee = borrowedAmount.div(FEE_BASE).mul(agreementFee); IERC20(borrowedAsset).transfer(_delegator, delegatorFee); uint256 finalBalance = IERC20(borrowedAsset).balanceOf(address(this)); IERC20(borrowedAsset).transfer(treasuryAddress, finalBalance); } /** * Transfer a NFT (ERC-721) locked into the vault to a receiver address * @param _tokenId the token id * @param _receiver the receiver adddress */ function transferNFT( uint256 _tokenId, address _receiver ) public { require(hasRole(CONDITION_ROLE, msg.sender), 'Only conditions'); require(nftId == _tokenId, 'Invalid tokenId'); IERC721Upgradeable token = IERC721Upgradeable(nftAddress); token.approve(_receiver, _tokenId); token.safeTransferFrom(address(this), _receiver, _tokenId); } /** * Transfers the ERC20 token deposited to the Aave contracts * @param _collateralAsset collateral asset that will be deposit on Aave * @param _amount Amount of collateral to deposit */ function _transferERC20( address _collateralAsset, uint256 _amount ) internal { IERC20Upgradeable token = ERC20Upgradeable(_collateralAsset); token.approve(address(lendingPool), _amount); lendingPool.deposit(_collateralAsset, _amount, address(this), 0); } /** * @notice Handle the receipt of an NFT * @dev The ERC721 smart contract calls this function on the recipient * after a {IERC721-safeTransferFrom}. This function MUST return the function selector, * otherwise the caller will revert the transaction. * * Note: the ERC721 contract address is always the message sender. * (param not used): operator The address which called `safeTransferFrom` function * (param not used): from The address which previously owned the token * @param _tokenId The NFT identifier which is being transferred * (param not used): data Additional data with no specified format * @return bytes4 `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))` */ function onERC721Received( address, address, uint256 _tokenId, bytes memory ) public virtual override returns (bytes4) { require(nftAddress == address(0), 'NFT already locked'); nftAddress = msg.sender; nftId = _tokenId; return this.onERC721Received.selector; } }
Returns the total debt of the credit in the Aave protocol expressed in ETH units/
function getActualCreditDebt() public view returns (uint256) { (, uint256 totalDebtETH, , , , ) = lendingPool.getUserAccountData( address(this) ); return totalDebtETH; }
5,493,912
pragma solidity ^0.4.18; contract Manager { address public ceo; address public cfo; address public coo; address public cao; event OwnershipTransferred(address previousCeo, address newCeo); event Pause(); event Unpause(); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ function Manager() public { coo = msg.sender; cfo = 0x7810704C6197aFA95e940eF6F719dF32657AD5af; ceo = 0x96C0815aF056c5294Ad368e3FBDb39a1c9Ae4e2B; cao = 0xC4888491B404FfD15cA7F599D624b12a9D845725; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyCEO() { require(msg.sender == ceo); _; } modifier onlyCOO() { require(msg.sender == coo); _; } modifier onlyCAO() { require(msg.sender == cao); _; } bool allowTransfer = false; function changeAllowTransferState() public onlyCOO { if (allowTransfer) { allowTransfer = false; } else { allowTransfer = true; } } modifier whenTransferAllowed() { require(allowTransfer); _; } /** * @dev Allows the current owner to transfer control of the contract to a newCeo. * @param newCeo The address to transfer ownership to. */ function demiseCEO(address newCeo) public onlyCEO { require(newCeo != address(0)); emit OwnershipTransferred(ceo, newCeo); ceo = newCeo; } function setCFO(address newCfo) public onlyCEO { require(newCfo != address(0)); cfo = newCfo; } function setCOO(address newCoo) public onlyCEO { require(newCoo != address(0)); coo = newCoo; } function setCAO(address newCao) public onlyCEO { require(newCao != address(0)); cao = newCao; } 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() onlyCAO whenNotPaused public { paused = true; emit Pause(); } /** * @dev called by the owner to unpause, returns to normal state */ function unpause() onlyCAO whenPaused public { paused = false; emit Unpause(); } } contract SkinBase is Manager { struct Skin { uint128 appearance; uint64 cooldownEndTime; uint64 mixingWithId; } // All skins, mapping from skin id to skin apprance mapping (uint256 => Skin) skins; // Mapping from skin id to owner mapping (uint256 => address) public skinIdToOwner; // Whether a skin is on sale mapping (uint256 => bool) public isOnSale; // Using mapping (address => uint256) public accountsToActiveSkin; // Number of all total valid skins // skinId 0 should not correspond to any skin, because skin.mixingWithId==0 indicates not mixing uint256 public nextSkinId = 1; // Number of skins an account owns mapping (address => uint256) public numSkinOfAccounts; event SkinTransfer(address from, address to, uint256 skinId); event SetActiveSkin(address account, uint256 skinId); // Get the i-th skin an account owns, for off-chain usage only function skinOfAccountById(address account, uint256 id) external view returns (uint256) { uint256 count = 0; uint256 numSkinOfAccount = numSkinOfAccounts[account]; require(numSkinOfAccount > 0); require(id < numSkinOfAccount); for (uint256 i = 1; i < nextSkinId; i++) { if (skinIdToOwner[i] == account) { // This skin belongs to current account if (count == id) { // This is the id-th skin of current account, a.k.a, what we need return i; } count++; } } revert(); } // Get skin by id function getSkin(uint256 id) public view returns (uint128, uint64, uint64) { require(id > 0); require(id < nextSkinId); Skin storage skin = skins[id]; return (skin.appearance, skin.cooldownEndTime, skin.mixingWithId); } function withdrawETH() external onlyCAO { cfo.transfer(address(this).balance); } function transferP2P(uint256 id, address targetAccount) whenTransferAllowed public { require(skinIdToOwner[id] == msg.sender); require(msg.sender != targetAccount); skinIdToOwner[id] = targetAccount; numSkinOfAccounts[msg.sender] -= 1; numSkinOfAccounts[targetAccount] += 1; // emit event emit SkinTransfer(msg.sender, targetAccount, id); } function _isComplete(uint256 id) internal view returns (bool) { uint128 _appearance = skins[id].appearance; uint128 mask = uint128(65535); uint128 _type = _appearance & mask; uint128 maskedValue; for (uint256 i = 1; i < 8; i++) { mask = mask << 16; maskedValue = (_appearance & mask) >> (16*i); if (maskedValue != _type) { return false; } } return true; } function setActiveSkin(uint256 id) public { require(skinIdToOwner[id] == msg.sender); require(_isComplete(id)); require(isOnSale[id] == false); require(skins[id].mixingWithId == 0); accountsToActiveSkin[msg.sender] = id; emit SetActiveSkin(msg.sender, id); } function getActiveSkin(address account) public view returns (uint128) { uint256 activeId = accountsToActiveSkin[account]; if (activeId == 0) { return uint128(0); } return (skins[activeId].appearance & uint128(65535)); } } contract SkinMix is SkinBase { // Mix formula MixFormulaInterface public mixFormula; // Pre-paid ether for synthesization, will be returned to user if the synthesization failed (minus gas). uint256 public prePaidFee = 150000 * 5000000000; // (15w gas * 5 gwei) bool public enableMix = false; // Events event MixStart(address account, uint256 skinAId, uint256 skinBId); event AutoMix(address account, uint256 skinAId, uint256 skinBId, uint64 cooldownEndTime); event MixSuccess(address account, uint256 skinId, uint256 skinAId, uint256 skinBId); // Set mix formula contract address function setMixFormulaAddress(address mixFormulaAddress) external onlyCOO { mixFormula = MixFormulaInterface(mixFormulaAddress); } // setPrePaidFee: set advance amount, only owner can call this function setPrePaidFee(uint256 newPrePaidFee) external onlyCOO { prePaidFee = newPrePaidFee; } function changeMixEnable(bool newState) external onlyCOO { enableMix = newState; } // _isCooldownReady: check whether cooldown period has been passed function _isCooldownReady(uint256 skinAId, uint256 skinBId) private view returns (bool) { return (skins[skinAId].cooldownEndTime <= uint64(now)) && (skins[skinBId].cooldownEndTime <= uint64(now)); } // _isNotMixing: check whether two skins are in another mixing process function _isNotMixing(uint256 skinAId, uint256 skinBId) private view returns (bool) { return (skins[skinAId].mixingWithId == 0) && (skins[skinBId].mixingWithId == 0); } // _setCooldownTime: set new cooldown time function _setCooldownEndTime(uint256 skinAId, uint256 skinBId) private { uint256 end = now + 20 minutes; // uint256 end = now; skins[skinAId].cooldownEndTime = uint64(end); skins[skinBId].cooldownEndTime = uint64(end); } // _isValidSkin: whether an account can mix using these skins // Make sure two things: // 1. these two skins do exist // 2. this account owns these skins function _isValidSkin(address account, uint256 skinAId, uint256 skinBId) private view returns (bool) { // Make sure those two skins belongs to this account if (skinAId == skinBId) { return false; } if ((skinAId == 0) || (skinBId == 0)) { return false; } if ((skinAId >= nextSkinId) || (skinBId >= nextSkinId)) { return false; } if (accountsToActiveSkin[account] == skinAId || accountsToActiveSkin[account] == skinBId) { return false; } return (skinIdToOwner[skinAId] == account) && (skinIdToOwner[skinBId] == account); } // _isNotOnSale: whether a skin is not on sale function _isNotOnSale(uint256 skinId) private view returns (bool) { return (isOnSale[skinId] == false); } // mix function mix(uint256 skinAId, uint256 skinBId) public whenNotPaused { require(enableMix == true); // Check whether skins are valid require(_isValidSkin(msg.sender, skinAId, skinBId)); // Check whether skins are neither on sale require(_isNotOnSale(skinAId) && _isNotOnSale(skinBId)); // Check cooldown require(_isCooldownReady(skinAId, skinBId)); // Check these skins are not in another process require(_isNotMixing(skinAId, skinBId)); // Set new cooldown time _setCooldownEndTime(skinAId, skinBId); // Mark skins as in mixing skins[skinAId].mixingWithId = uint64(skinBId); skins[skinBId].mixingWithId = uint64(skinAId); // Emit MixStart event emit MixStart(msg.sender, skinAId, skinBId); } // Mixing auto function mixAuto(uint256 skinAId, uint256 skinBId) public payable whenNotPaused { require(msg.value >= prePaidFee); mix(skinAId, skinBId); Skin storage skin = skins[skinAId]; emit AutoMix(msg.sender, skinAId, skinBId, skin.cooldownEndTime); } // Get mixing result, return the resulted skin id function getMixingResult(uint256 skinAId, uint256 skinBId) public whenNotPaused { // Check these two skins belongs to the same account address account = skinIdToOwner[skinAId]; require(account == skinIdToOwner[skinBId]); // Check these two skins are in the same mixing process Skin storage skinA = skins[skinAId]; Skin storage skinB = skins[skinBId]; require(skinA.mixingWithId == uint64(skinBId)); require(skinB.mixingWithId == uint64(skinAId)); // Check cooldown require(_isCooldownReady(skinAId, skinBId)); // Create new skin uint128 newSkinAppearance = mixFormula.calcNewSkinAppearance(skinA.appearance, skinB.appearance, getActiveSkin(account)); Skin memory newSkin = Skin({appearance: newSkinAppearance, cooldownEndTime: uint64(now), mixingWithId: 0}); skins[nextSkinId] = newSkin; skinIdToOwner[nextSkinId] = account; isOnSale[nextSkinId] = false; nextSkinId++; // Clear old skins skinA.mixingWithId = 0; skinB.mixingWithId = 0; // In order to distinguish created skins in minting with destroyed skins // skinIdToOwner[skinAId] = owner; // skinIdToOwner[skinBId] = owner; delete skinIdToOwner[skinAId]; delete skinIdToOwner[skinBId]; // require(numSkinOfAccounts[account] >= 2); numSkinOfAccounts[account] -= 1; emit MixSuccess(account, nextSkinId - 1, skinAId, skinBId); } } contract MixFormulaInterface { function calcNewSkinAppearance(uint128 x, uint128 y, uint128 addition) public returns (uint128); // create random appearance function randomSkinAppearance(uint256 externalNum, uint128 addition) public returns (uint128); // bleach function bleachAppearance(uint128 appearance, uint128 attributes) public returns (uint128); // recycle function recycleAppearance(uint128[5] appearances, uint256 preference, uint128 addition) public returns (uint128); // summon10 function summon10SkinAppearance(uint256 externalNum, uint128 addition) public returns (uint128); } contract SkinMarket is SkinMix { // Cut ratio for a transaction // Values 0-10,000 map to 0%-100% uint128 public trCut = 400; // Sale orders list mapping (uint256 => uint256) public desiredPrice; // events event PutOnSale(address account, uint256 skinId); event WithdrawSale(address account, uint256 skinId); event BuyInMarket(address buyer, uint256 skinId); // functions function setTrCut(uint256 newCut) external onlyCOO { trCut = uint128(newCut); } // Put asset on sale function putOnSale(uint256 skinId, uint256 price) public whenNotPaused { // Only owner of skin pass require(skinIdToOwner[skinId] == msg.sender); require(accountsToActiveSkin[msg.sender] != skinId); // Check whether skin is mixing require(skins[skinId].mixingWithId == 0); // Check whether skin is already on sale require(isOnSale[skinId] == false); require(price > 0); // Put on sale desiredPrice[skinId] = price; isOnSale[skinId] = true; // Emit the Approval event emit PutOnSale(msg.sender, skinId); } // Withdraw an sale order function withdrawSale(uint256 skinId) external whenNotPaused { // Check whether this skin is on sale require(isOnSale[skinId] == true); // Can only withdraw self's sale require(skinIdToOwner[skinId] == msg.sender); // Withdraw isOnSale[skinId] = false; desiredPrice[skinId] = 0; // Emit the cancel event emit WithdrawSale(msg.sender, skinId); } // Buy skin in market function buyInMarket(uint256 skinId) external payable whenNotPaused { // Check whether this skin is on sale require(isOnSale[skinId] == true); address seller = skinIdToOwner[skinId]; // Check the sender isn't the seller require(msg.sender != seller); uint256 _price = desiredPrice[skinId]; // Check whether pay value is enough require(msg.value >= _price); // Cut and then send the proceeds to seller uint256 sellerProceeds = _price - _computeCut(_price); seller.transfer(sellerProceeds); // Transfer skin from seller to buyer numSkinOfAccounts[seller] -= 1; skinIdToOwner[skinId] = msg.sender; numSkinOfAccounts[msg.sender] += 1; isOnSale[skinId] = false; desiredPrice[skinId] = 0; // Emit the buy event emit BuyInMarket(msg.sender, skinId); } // Compute the marketCut function _computeCut(uint256 _price) internal view returns (uint256) { return _price / 10000 * trCut; } } contract SkinMinting is SkinMarket { // Limits the number of skins the contract owner can ever create. uint256 public skinCreatedLimit = 50000; uint256 public skinCreatedNum; // The summon and bleach numbers of each accounts: will be cleared every day mapping (address => uint256) public accountToSummonNum; mapping (address => uint256) public accountToBleachNum; // Pay level of each accounts mapping (address => uint256) public accountToPayLevel; mapping (address => uint256) public accountLastClearTime; mapping (address => uint256) public bleachLastClearTime; // Free bleach number donated mapping (address => uint256) public freeBleachNum; bool isBleachAllowed = false; bool isRecycleAllowed = false; uint256 public levelClearTime = now; // price and limit uint256 public bleachDailyLimit = 3; uint256 public baseSummonPrice = 1 finney; uint256 public bleachPrice = 100 ether; // do not call this // Pay level uint256[5] public levelSplits = [10, 20, 50, 100, 200]; uint256[6] public payMultiple = [10, 12, 15, 20, 30, 40]; // events event CreateNewSkin(uint256 skinId, address account); event Bleach(uint256 skinId, uint128 newAppearance); event Recycle(uint256 skinId0, uint256 skinId1, uint256 skinId2, uint256 skinId3, uint256 skinId4, uint256 newSkinId); // functions // Set price function setBaseSummonPrice(uint256 newPrice) external onlyCOO { baseSummonPrice = newPrice; } function setBleachPrice(uint256 newPrice) external onlyCOO { bleachPrice = newPrice; } function setBleachDailyLimit(uint256 limit) external onlyCOO { bleachDailyLimit = limit; } function switchBleachAllowed(bool newBleachAllowed) external onlyCOO { isBleachAllowed = newBleachAllowed; } function switchRecycleAllowed(bool newRecycleAllowed) external onlyCOO { isRecycleAllowed = newRecycleAllowed; } // Create base skin for sell. Only owner can create function createSkin(uint128 specifiedAppearance, uint256 salePrice) external onlyCOO { require(skinCreatedNum < skinCreatedLimit); // Create specified skin // uint128 randomAppearance = mixFormula.randomSkinAppearance(); Skin memory newSkin = Skin({appearance: specifiedAppearance, cooldownEndTime: uint64(now), mixingWithId: 0}); skins[nextSkinId] = newSkin; skinIdToOwner[nextSkinId] = coo; isOnSale[nextSkinId] = false; // Emit the create event emit CreateNewSkin(nextSkinId, coo); // Put this skin on sale putOnSale(nextSkinId, salePrice); nextSkinId++; numSkinOfAccounts[coo] += 1; skinCreatedNum += 1; } // Donate a skin to player. Only COO can operate function donateSkin(uint128 specifiedAppearance, address donee) external whenNotPaused onlyCOO { Skin memory newSkin = Skin({appearance: specifiedAppearance, cooldownEndTime: uint64(now), mixingWithId: 0}); skins[nextSkinId] = newSkin; skinIdToOwner[nextSkinId] = donee; isOnSale[nextSkinId] = false; // Emit the create event emit CreateNewSkin(nextSkinId, donee); nextSkinId++; numSkinOfAccounts[donee] += 1; skinCreatedNum += 1; } // function moveData(uint128[] legacyAppearance, address[] legacyOwner, bool[] legacyIsOnSale, uint256[] legacyDesiredPrice) external onlyCOO { Skin memory newSkin = Skin({appearance: 0, cooldownEndTime: 0, mixingWithId: 0}); for (uint256 i = 0; i < legacyOwner.length; i++) { newSkin.appearance = legacyAppearance[i]; newSkin.cooldownEndTime = uint64(now); newSkin.mixingWithId = 0; skins[nextSkinId] = newSkin; skinIdToOwner[nextSkinId] = legacyOwner[i]; isOnSale[nextSkinId] = legacyIsOnSale[i]; desiredPrice[nextSkinId] = legacyDesiredPrice[i]; // Emit the create event emit CreateNewSkin(nextSkinId, legacyOwner[i]); nextSkinId++; numSkinOfAccounts[legacyOwner[i]] += 1; if (numSkinOfAccounts[legacyOwner[i]] > freeBleachNum[legacyOwner[i]]*10 || freeBleachNum[legacyOwner[i]] == 0) { freeBleachNum[legacyOwner[i]] += 1; } skinCreatedNum += 1; } } // Summon function summon() external payable whenNotPaused { // Clear daily summon numbers if (accountLastClearTime[msg.sender] == uint256(0)) { // This account's first time to summon, we do not need to clear summon numbers accountLastClearTime[msg.sender] = now; } else { if (accountLastClearTime[msg.sender] < levelClearTime && now > levelClearTime) { accountToSummonNum[msg.sender] = 0; accountToPayLevel[msg.sender] = 0; accountLastClearTime[msg.sender] = now; } } uint256 payLevel = accountToPayLevel[msg.sender]; uint256 price = payMultiple[payLevel] * baseSummonPrice; require(msg.value >= price); // Create random skin uint128 randomAppearance = mixFormula.randomSkinAppearance(nextSkinId, getActiveSkin(msg.sender)); // uint128 randomAppearance = 0; Skin memory newSkin = Skin({appearance: randomAppearance, cooldownEndTime: uint64(now), mixingWithId: 0}); skins[nextSkinId] = newSkin; skinIdToOwner[nextSkinId] = msg.sender; isOnSale[nextSkinId] = false; // Emit the create event emit CreateNewSkin(nextSkinId, msg.sender); nextSkinId++; numSkinOfAccounts[msg.sender] += 1; accountToSummonNum[msg.sender] += 1; // Handle the paylevel if (payLevel < 5) { if (accountToSummonNum[msg.sender] >= levelSplits[payLevel]) { accountToPayLevel[msg.sender] = payLevel + 1; } } } // Summon10 function summon10() external payable whenNotPaused { // Clear daily summon numbers if (accountLastClearTime[msg.sender] == uint256(0)) { // This account's first time to summon, we do not need to clear summon numbers accountLastClearTime[msg.sender] = now; } else { if (accountLastClearTime[msg.sender] < levelClearTime && now > levelClearTime) { accountToSummonNum[msg.sender] = 0; accountToPayLevel[msg.sender] = 0; accountLastClearTime[msg.sender] = now; } } uint256 payLevel = accountToPayLevel[msg.sender]; uint256 price = payMultiple[payLevel] * baseSummonPrice; require(msg.value >= price*10); Skin memory newSkin; uint128 randomAppearance; // Create random skin for (uint256 i = 0; i < 10; i++) { randomAppearance = mixFormula.randomSkinAppearance(nextSkinId, getActiveSkin(msg.sender)); newSkin = Skin({appearance: randomAppearance, cooldownEndTime: uint64(now), mixingWithId: 0}); skins[nextSkinId] = newSkin; skinIdToOwner[nextSkinId] = msg.sender; isOnSale[nextSkinId] = false; // Emit the create event emit CreateNewSkin(nextSkinId, msg.sender); nextSkinId++; } // Give additional skin randomAppearance = mixFormula.summon10SkinAppearance(nextSkinId, getActiveSkin(msg.sender)); newSkin = Skin({appearance: randomAppearance, cooldownEndTime: uint64(now), mixingWithId: 0}); skins[nextSkinId] = newSkin; skinIdToOwner[nextSkinId] = msg.sender; isOnSale[nextSkinId] = false; // Emit the create event emit CreateNewSkin(nextSkinId, msg.sender); nextSkinId++; numSkinOfAccounts[msg.sender] += 11; accountToSummonNum[msg.sender] += 10; // Handle the paylevel if (payLevel < 5) { if (accountToSummonNum[msg.sender] >= levelSplits[payLevel]) { accountToPayLevel[msg.sender] = payLevel + 1; } } } // Recycle bin function recycleSkin(uint256[5] wasteSkins, uint256 preferIndex) external whenNotPaused { require(isRecycleAllowed == true); for (uint256 i = 0; i < 5; i++) { require(skinIdToOwner[wasteSkins[i]] == msg.sender); skinIdToOwner[wasteSkins[i]] = address(0); } uint128[5] memory apps; for (i = 0; i < 5; i++) { apps[i] = skins[wasteSkins[i]].appearance; } // Create random skin uint128 recycleApp = mixFormula.recycleAppearance(apps, preferIndex, getActiveSkin(msg.sender)); Skin memory newSkin = Skin({appearance: recycleApp, cooldownEndTime: uint64(now), mixingWithId: 0}); skins[nextSkinId] = newSkin; skinIdToOwner[nextSkinId] = msg.sender; isOnSale[nextSkinId] = false; // Emit event emit Recycle(wasteSkins[0], wasteSkins[1], wasteSkins[2], wasteSkins[3], wasteSkins[4], nextSkinId); nextSkinId++; numSkinOfAccounts[msg.sender] -= 4; } // Bleach some attributes function bleach(uint128 skinId, uint128 attributes) external payable whenNotPaused { require(isBleachAllowed); // Clear daily summon numbers if (bleachLastClearTime[msg.sender] == uint256(0)) { // This account's first time to summon, we do not need to clear bleach numbers bleachLastClearTime[msg.sender] = now; } else { if (bleachLastClearTime[msg.sender] < levelClearTime && now > levelClearTime) { accountToBleachNum[msg.sender] = 0; bleachLastClearTime[msg.sender] = now; } } require(accountToBleachNum[msg.sender] < bleachDailyLimit); accountToBleachNum[msg.sender] += 1; // Check whether msg.sender is owner of the skin require(msg.sender == skinIdToOwner[skinId]); // Check whether this skin is on sale require(isOnSale[skinId] == false); uint256 bleachNum = 0; for (uint256 i = 0; i < 8; i++) { if ((attributes & (uint128(1) << i)) > 0) { if (freeBleachNum[msg.sender] > 0) { freeBleachNum[msg.sender]--; } else { bleachNum++; } } } // Check whether there is enough money require(msg.value >= bleachNum * bleachPrice); Skin storage originSkin = skins[skinId]; // Check whether this skin is in mixing require(originSkin.mixingWithId == 0); uint128 newAppearance = mixFormula.bleachAppearance(originSkin.appearance, attributes); originSkin.appearance = newAppearance; // Emit bleach event emit Bleach(skinId, newAppearance); } // Our daemon will clear daily summon numbers function clearSummonNum() external onlyCOO { uint256 nextDay = levelClearTime + 1 days; if (now > nextDay) { levelClearTime = nextDay; } } }
_isValidSkin: whether an account can mix using these skins Make sure two things: 1. these two skins do exist 2. this account owns these skins Make sure those two skins belongs to this account
function _isValidSkin(address account, uint256 skinAId, uint256 skinBId) private view returns (bool) { if (skinAId == skinBId) { return false; } if ((skinAId == 0) || (skinBId == 0)) { return false; } if ((skinAId >= nextSkinId) || (skinBId >= nextSkinId)) { return false; } if (accountsToActiveSkin[account] == skinAId || accountsToActiveSkin[account] == skinBId) { return false; } return (skinIdToOwner[skinAId] == account) && (skinIdToOwner[skinBId] == account); }
14,703,192
// SPDX-License-Identifier: Apache-2.0 pragma solidity ^0.8.11; import {ERC20} from "@rari-capital/solmate/src/tokens/ERC20.sol"; import {SafeTransferLib} from "@rari-capital/solmate/src/utils/SafeTransferLib.sol"; import {Ownable} from "@openzeppelin/contracts/access/Ownable.sol"; import {IAaveV2StablecoinCellar} from "./interfaces/IAaveV2StablecoinCellar.sol"; import {IAaveIncentivesController} from "./interfaces/IAaveIncentivesController.sol"; import {IStakedTokenV2} from "./interfaces/IStakedTokenV2.sol"; import {ICurveSwaps} from "./interfaces/ICurveSwaps.sol"; import {ISushiSwapRouter} from "./interfaces/ISushiSwapRouter.sol"; import {IGravity} from "./interfaces/IGravity.sol"; import {ILendingPool} from "./interfaces/ILendingPool.sol"; import {MathUtils} from "./utils/MathUtils.sol"; /** * @title Sommelier Aave V2 Stablecoin Cellar * @notice Dynamic ERC4626 that adapts strategies to always get the best yield for stablecoins on Aave. * @author Brian Le */ contract AaveV2StablecoinCellar is IAaveV2StablecoinCellar, ERC20, Ownable { using SafeTransferLib for ERC20; using MathUtils for uint256; /** * @notice The asset that makes up the cellar's holding pool. Will change whenever the cellar * rebalances into a new strategy. * @dev The cellar denotes its inactive assets in this token. While it waits in the holding pool * to be entered into a strategy, it is used to pay for withdraws from those redeeming their * shares. */ ERC20 public asset; /** * @notice An interest-bearing derivative of the current asset returned by Aave for lending * assets. Represents cellar's portion of active assets earning yield in a lending * strategy. */ ERC20 public assetAToken; /** * @notice The decimals of precision used by the current asset. * @dev Some stablecoins (eg. USDC and USDT) don't use the standard 18 decimals of precision. * This is used for converting between decimals when performing calculations in the cellar. */ uint8 public assetDecimals; /** * @notice Mapping from a user's address to all their deposits and balances. * @dev Used in determining which of a user's shares are active (entered into a strategy earning * yield vs inactive (waiting in the holding pool to be entered into a strategy and not * earning yield). */ mapping(address => UserDeposit[]) public userDeposits; /** * @notice Mapping from user's address to the index of first non-zero deposit in `userDeposits`. * @dev Saves gas when looping through all user's deposits. */ mapping(address => uint256) public currentDepositIndex; /** * @notice Last time all inactive assets were entered into a strategy and made active. */ uint256 public lastTimeEnteredStrategy; /** * @notice The value fees are divided by to get a percentage. Represents maximum percent (100%). */ uint256 public constant DENOMINATOR = 100_00; /** * @notice The percentage of platform fees (1%) taken off of active assets over a year. */ uint256 public constant PLATFORM_FEE = 1_00; /** * @notice The percentage of performance fees (5%) taken off of cellar gains. */ uint256 public constant PERFORMANCE_FEE = 5_00; /** * @notice Timestamp of last time platform fees were accrued. */ uint256 public lastTimeAccruedPlatformFees; /** * @notice Amount of active assets in cellar last time performance fees were accrued. */ uint256 public lastActiveAssets; /** * @notice Normalized income index for the current asset on Aave recorded last time performance * fees were accrued. */ uint256 public lastNormalizedIncome; /** * @notice Amount of platform fees that have been accrued awaiting transfer. * @dev Fees are taken in shares and redeemed for assets at the time they are transferred from * the cellar to Cosmos to be distributed. */ uint256 public accruedPlatformFees; /** * @notice Amount of performance fees that have been accrued awaiting transfer. * @dev Fees are taken in shares and redeemed for assets at the time they are transferred from * the cellar to Cosmos to be distributed. */ uint256 public accruedPerformanceFees; /** * @notice Cosmos address of the fee distributor as a hex value. * @dev The Gravity contract expects a 32-byte value formatted in a specific way. */ bytes32 public constant feesDistributor = hex"000000000000000000000000b813554b423266bbd4c16c32fa383394868c1f55"; /** * @notice Maximum amount of assets that can be managed by the cellar. Denominated in the same * units as the current asset. * @dev Limited to $5m until after security audits. */ uint256 public maxLiquidity; /** * @notice Whether or not the contract is paused in case of an emergency. */ bool public isPaused; /** * @notice Whether or not the contract is permanently shutdown in case of an emergency. */ bool public isShutdown; // ======================================== IMMUTABLES ======================================== // Curve Registry Exchange contract ICurveSwaps public immutable curveRegistryExchange; // 0xD1602F68CC7C4c7B59D686243EA35a9C73B0c6a2 // SushiSwap Router V2 contract ISushiSwapRouter public immutable sushiswapRouter; // 0xd9e1cE17f2641f24aE83637ab66a2cca9C378B9F // Aave Lending Pool V2 contract ILendingPool public immutable lendingPool; // 0x7d2768dE32b0b80b7a3454c06BdAc94A69DDc7A9 // Aave Incentives Controller V2 contract IAaveIncentivesController public immutable incentivesController; // 0xd784927Ff2f95ba542BfC824c8a8a98F3495f6b5 // Cosmos Gravity Bridge contract IGravity public immutable gravityBridge; // 0x69592e6f9d21989a043646fE8225da2600e5A0f7 IStakedTokenV2 public immutable stkAAVE; // 0x4da27a545c0c5B758a6BA100e3a049001de870f5 ERC20 public immutable AAVE; // 0x7Fc66500c84A76Ad7e9c93437bFc5Ac33E2DDaE9 ERC20 public immutable WETH; // 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2 /** * @dev Owner of the cellar will be the Gravity contract controlled by Steward: * https://github.com/cosmos/gravity-bridge/blob/main/solidity/contracts/Gravity.sol * https://github.com/PeggyJV/steward * @param _asset current asset managed by the cellar * @param _curveRegistryExchange Curve registry exchange * @param _sushiswapRouter Sushiswap V2 router address * @param _lendingPool Aave V2 lending pool address * @param _incentivesController _incentivesController * @param _gravityBridge Cosmos Gravity Bridge address * @param _stkAAVE stkAAVE address * @param _AAVE AAVE address * @param _WETH WETH address */ constructor( ERC20 _asset, ICurveSwaps _curveRegistryExchange, ISushiSwapRouter _sushiswapRouter, ILendingPool _lendingPool, IAaveIncentivesController _incentivesController, IGravity _gravityBridge, IStakedTokenV2 _stkAAVE, ERC20 _AAVE, ERC20 _WETH ) ERC20("Sommelier Aave V2 Stablecoin Cellar LP Token", "aave2-CLR-S", 18) Ownable() { curveRegistryExchange = _curveRegistryExchange; sushiswapRouter = _sushiswapRouter; lendingPool = _lendingPool; incentivesController = _incentivesController; gravityBridge = _gravityBridge; stkAAVE = _stkAAVE; AAVE = _AAVE; WETH = _WETH; // Initialize asset. _updateStrategy(address(_asset)); // Initialize starting point for platform fee accrual to time when cellar was created. // Otherwise it would incorrectly calculate how much platform fees to take when accrueFees // is called for the first time. lastTimeAccruedPlatformFees = block.timestamp; } // =============================== DEPOSIT/WITHDRAWAL OPERATIONS =============================== /** * @notice Deposits assets and mints the shares to receiver. * @param assets amount of assets to deposit * @param receiver address receiving the shares * @return shares amount of shares minted */ function deposit(uint256 assets, address receiver) external returns (uint256 shares) { // In the case where a user tries to deposit more than their balance, the desired behavior // is to deposit what they have instead of reverting. uint256 maxDepositable = asset.balanceOf(msg.sender); if (assets > maxDepositable) assets = maxDepositable; (, shares) = _deposit(assets, 0, receiver); } /** * @notice Mints shares to receiver by depositing assets. * @param shares amount of shares to mint * @param receiver address receiving the shares * @return assets amount of assets deposited */ function mint(uint256 shares, address receiver) external returns (uint256 assets) { // In the case where a user tries to mint more shares than possible, the desired behavior // is to mint as many shares as their balance allows instead of reverting. uint256 maxMintable = previewDeposit(asset.balanceOf(msg.sender)); if (shares > maxMintable) shares = maxMintable; (assets, ) = _deposit(0, shares, receiver); } function _deposit(uint256 assets, uint256 shares, address receiver) internal returns (uint256, uint256) { // In case of an emergency or contract vulnerability, we don't want users to be able to // deposit more assets into a compromised contract. if (isPaused) revert ContractPaused(); if (isShutdown) revert ContractShutdown(); // Must calculate before assets are transferred in. shares > 0 ? assets = previewMint(shares) : shares = previewDeposit(assets); // Check for rounding error on `deposit` since we round down in previewDeposit. No need to // check for rounding error if `mint`, previewMint rounds up. if (shares == 0) revert ZeroShares(); // Check if security restrictions still apply. Enforce them if they do. if (maxLiquidity != type(uint256).max) { if (assets + totalAssets() > maxLiquidity) revert LiquidityRestricted(maxLiquidity); if (assets > maxDeposit(receiver)) revert DepositRestricted(50_000 * 10**assetDecimals); } // Transfers assets into the cellar. asset.safeTransferFrom(msg.sender, address(this), assets); // Mint user tokens that represents their share of the cellar's assets. _mint(receiver, shares); // Store the user's deposit data. This will be used later on when the user wants to withdraw // their assets or transfer their shares. UserDeposit[] storage deposits = userDeposits[receiver]; deposits.push(UserDeposit({ // Always store asset amounts with 18 decimals of precision regardless of the asset's // decimals. This is so we can still use this data even after rebalancing to different // asset. assets: uint112(assets.changeDecimals(assetDecimals, decimals)), shares: uint112(shares), timeDeposited: uint32(block.timestamp) })); emit Deposit( msg.sender, receiver, address(asset), assets, shares ); return (assets, shares); } /** * @notice Withdraws assets to receiver by redeeming shares from owner. * @param assets amount of assets being withdrawn * @param receiver address of account receiving the assets * @param owner address of the owner of the shares being redeemed * @return shares amount of shares redeemed */ function withdraw( uint256 assets, address receiver, address owner ) external returns (uint256 shares) { // This is done to avoid the possibility of an overflow if `assets` was set to a very high // number (like 2**256 – 1) when trying to change decimals. If a user tries to withdraw // more than their balance, the desired behavior is to withdraw as much as possible. uint256 maxWithdrawable = previewRedeem(balanceOf[owner]); if (assets > maxWithdrawable) assets = maxWithdrawable; // Ensures proceeding calculations are done with a standard 18 decimals of precision. Will // change back to the using the asset's usual decimals of precision when transferring assets // after all calculations are done. assets = assets.changeDecimals(assetDecimals, decimals); (, shares) = _withdraw(assets, receiver, owner); } /** * @notice Redeems shares from owner to withdraw assets to receiver. * @param shares amount of shares redeemed * @param receiver address of account receiving the assets * @param owner address of the owner of the shares being redeemed * @return assets amount of assets sent to receiver */ function redeem( uint256 shares, address receiver, address owner ) external returns (uint256 assets) { // This is done to avoid the possibility of an overflow if `shares` was set to a very high // number (like 2**256 – 1) when trying to change decimals. If a user tries to redeem more // than their balance, the desired behavior is to redeem as much as possible. uint256 maxRedeemable = maxRedeem(owner); if (shares > maxRedeemable) shares = maxRedeemable; (assets, ) = _withdraw(_convertToAssets(shares), receiver, owner); } /// @dev `assets` must be passed in with 18 decimals of precision. Should extend/truncate decimals of /// the amount passed in if necessary to ensure this is true. function _withdraw( uint256 assets, address receiver, address owner ) internal returns (uint256, uint256) { if (balanceOf[owner] == 0) revert ZeroShares(); if (assets == 0) revert ZeroAssets(); // Tracks the total amount of shares being redeemed for the amount of assets withdrawn. uint256 shares; // Retrieve the user's deposits to begin looping through them, generally from oldest to // newest deposits. This may not be the case though if shares have been transferred to the // owner, which will be added to the end of the owner's deposits regardless of time // deposited. UserDeposit[] storage deposits = userDeposits[owner]; // Tracks the amount of assets left to withdraw. Updated at the end of each loop. uint256 leftToWithdraw = assets; // Saves gas by avoiding calling `_convertToAssets` on active shares during each loop. uint256 exchangeRate = _convertToAssets(1e18); for (uint256 i = currentDepositIndex[owner]; i < deposits.length; i++) { UserDeposit storage d = deposits[i]; // Whether or not deposited shares are active or inactive. bool isActive = d.timeDeposited <= lastTimeEnteredStrategy; // If shares are active, convert them to the amount of assets they're worth to see the // maximum amount of assets we can take from this deposit. uint256 dAssets = isActive ? uint256(d.shares).mulWadDown(exchangeRate) : d.assets; // Determine the amount of assets and shares to withdraw from this deposit. uint256 withdrawnAssets = MathUtils.min(leftToWithdraw, dAssets); uint256 withdrawnShares = uint256(d.shares).mulDivUp(withdrawnAssets, dAssets); // For active shares, deletes the deposit data we don't need anymore for a gas refund. if (isActive) { delete d.assets; delete d.timeDeposited; } else { d.assets -= uint112(withdrawnAssets); } // Take the shares we need from this deposit and add them to our total. d.shares -= uint112(withdrawnShares); shares += withdrawnShares; // Update the counter of assets we have left to withdraw. leftToWithdraw -= withdrawnAssets; // Finish if this is the last deposit or there is nothing left to withdraw. if (i == deposits.length - 1 || leftToWithdraw == 0) { // Store the user's next non-zero deposit to save gas on future looping. currentDepositIndex[owner] = d.shares != 0 ? i : i+1; break; } } // If the caller is not the owner of the shares, check to see if the owner has approved them // to spend their shares. if (msg.sender != owner) { uint256 allowed = allowance[owner][msg.sender]; // Saves gas for limited approvals. if (allowed != type(uint256).max) allowance[owner][msg.sender] = allowed - shares; } // Redeem shares for assets. _burn(owner, shares); // Determine the total amount of assets withdrawn. assets -= leftToWithdraw; // Convert assets decimals back to get ready for transfers. assets = assets.changeDecimals(decimals, assetDecimals); // Only withdraw from strategy if holding pool does not contain enough funds. _allocateAssets(assets); // Transfer assets to receiver from the cellar's holding pool. asset.safeTransfer(receiver, assets); emit Withdraw(receiver, owner, address(asset), assets, shares); // Returns the amount of assets withdrawn and amount of shares redeemed. The amount of // assets withdrawn may differ from the amount of assets specified when calling the function // if the user has less assets then they tried withdrawing. return (assets, shares); } // ================================== ACCOUNTING OPERATIONS ================================== /** * @dev The internal functions always use 18 decimals of precision while the public functions use * as many decimals as the current asset (aka they don't change the decimals). This is * because we want the user deposit data the cellar stores to be usable across different * assets regardless of the decimals used. This means the cellar will always perform * calculations and store data with a standard of 18 decimals of precision but will change * the decimals back when transferring assets outside the contract or returning data * through public view functions. */ /** * @notice Total amount of active asset entered into a strategy. */ function activeAssets() public view returns (uint256) { // The aTokens' value is pegged to the value of the corresponding asset at a 1:1 ratio. We // can find the amount of assets active in a strategy simply by taking balance of aTokens // cellar holds. return assetAToken.balanceOf(address(this)); } function _activeAssets() internal view returns (uint256) { uint256 assets = assetAToken.balanceOf(address(this)); return assets.changeDecimals(assetDecimals, decimals); } /** * @notice Total amount of inactive asset waiting in a holding pool to be entered into a strategy. */ function inactiveAssets() public view returns (uint256) { return asset.balanceOf(address(this)); } function _inactiveAssets() internal view returns (uint256) { uint256 assets = asset.balanceOf(address(this)); return assets.changeDecimals(assetDecimals, decimals); } /** * @notice Total amount of the asset that is managed by cellar. */ function totalAssets() public view returns (uint256) { return activeAssets() + inactiveAssets(); } function _totalAssets() internal view returns (uint256) { return _activeAssets() + _inactiveAssets(); } /** * @notice The amount of shares that the cellar would exchange for the amount of assets provided * ONLY if they are active. * @param assets amount of assets to convert * @return shares the assets can be exchanged for */ function convertToShares(uint256 assets) public view returns (uint256) { assets = assets.changeDecimals(assetDecimals, decimals); return _convertToShares(assets); } function _convertToShares(uint256 assets) internal view returns (uint256) { return totalSupply == 0 ? assets : assets.mulDivDown(totalSupply, _totalAssets()); } /** * @notice The amount of assets that the cellar would exchange for the amount of shares provided * ONLY if they are active. * @param shares amount of shares to convert * @return assets the shares can be exchanged for */ function convertToAssets(uint256 shares) public view returns (uint256) { uint256 assets = _convertToAssets(shares); return assets.changeDecimals(decimals, assetDecimals); } function _convertToAssets(uint256 shares) internal view returns (uint256) { return totalSupply == 0 ? shares : shares.mulDivDown(_totalAssets(), totalSupply); } /** * @notice Simulate the effects of depositing assets at the current block, given current on-chain * conditions. * @param assets amount of assets to deposit * @return shares that will be minted */ function previewDeposit(uint256 assets) public view returns (uint256) { return convertToShares(assets); } /** * @notice Simulate the effects of minting shares at the current block, given current on-chain * conditions. * @param shares amount of shares to mint * @return assets that will be deposited */ function previewMint(uint256 shares) public view returns (uint256) { uint256 supply = totalSupply; // Saves an extra SLOAD if totalSupply is non-zero. uint256 assets = supply == 0 ? shares : shares.mulDivUp(_totalAssets(), supply); return assets.changeDecimals(decimals, assetDecimals); } /** * @notice Simulate the effects of withdrawing assets at the current block, given current * on-chain conditions. Assumes the shares being redeemed are all active. * @param assets amount of assets to withdraw * @return shares that will be redeemed */ function previewWithdraw(uint256 assets) public view returns (uint256) { uint256 supply = totalSupply; // Saves an extra SLOAD if totalSupply is non-zero. return supply == 0 ? assets : assets.mulDivUp(supply, totalAssets()); } /** * @notice Simulate the effects of redeeming shares at the current block, given current on-chain * conditions. Assumes the shares being redeemed are all active. * @param shares amount of sharers to redeem * @return assets that can be withdrawn */ function previewRedeem(uint256 shares) public view returns (uint256) { return convertToAssets(shares); } // ======================================= STATE INFORMATION ===================================== /** * @notice Retrieve information on a user's deposits. * @param user address of the user * @return userActiveShares amount of active shares the user has * @return userInactiveShares amount of inactive shares the user has * @return userActiveAssets amount of active assets the user has * @return userInactiveAssets amount of inactive assets the user has */ function depositBalances(address user) public view returns ( uint256 userActiveShares, uint256 userInactiveShares, uint256 userActiveAssets, uint256 userInactiveAssets ) { // Retrieve the user's deposits to begin looping through them, generally from oldest to // newest deposits. This may not be the case though if shares have been transferred to the // user, which will be added to the end of the user's deposits regardless of time // deposited. UserDeposit[] storage deposits = userDeposits[user]; // Saves gas by avoiding calling `_convertToAssets` on active shares during each loop. uint256 exchangeRate = _convertToAssets(1e18); for (uint256 i = currentDepositIndex[user]; i < deposits.length; i++) { UserDeposit storage d = deposits[i]; // Determine whether or not deposit is active or inactive. if (d.timeDeposited <= lastTimeEnteredStrategy) { // Saves an extra SLOAD if active and cast type to uint256. uint256 dShares = d.shares; userActiveShares += dShares; userActiveAssets += dShares.mulWadDown(exchangeRate); // Convert shares to assets. } else { userInactiveShares += d.shares; userInactiveAssets += d.assets; } } // Return assets in their original units. userActiveAssets = userActiveAssets.changeDecimals(decimals, assetDecimals); userInactiveAssets = userInactiveAssets.changeDecimals(decimals, assetDecimals); } /** * @notice Returns the number of deposits for a user. Can be used off-chain to * make iterating through user stakes easier. * @param user address of the user * @return deposits the number of deposits for the user */ function numDeposits(address user) external view returns (uint256) { return userDeposits[user].length; } // =========================== DEPOSIT/WITHDRAWAL LIMIT OPERATIONS =========================== /** * @notice Total number of assets that can be deposited by owner into the cellar. * @dev Until after security audits, limits deposits to $50k per wallet. * @param owner address of account that would receive the shares * @return maximum amount of assets that can be deposited */ function maxDeposit(address owner) public view returns (uint256) { if (isShutdown || isPaused) return 0; if (maxLiquidity == type(uint256).max) return type(uint256).max; uint256 depositLimit = 50_000 * 10**assetDecimals; uint256 assets = previewRedeem(balanceOf[owner]); return depositLimit > assets ? depositLimit - assets : 0; } /** * @notice Total number of shares that can be minted for owner from the cellar. * @dev Until after security audits, limits mints to $50k of shares per wallet. * @param owner address of account that would receive the shares * @return maximum amount of shares that can be minted */ function maxMint(address owner) public view returns (uint256) { if (isShutdown || isPaused) return 0; if (maxLiquidity == type(uint256).max) return type(uint256).max; uint256 mintLimit = previewDeposit(50_000 * 10**assetDecimals); uint256 shares = balanceOf[owner]; return mintLimit > shares ? mintLimit - shares : 0; } /** * @notice Total number of assets that can be withdrawn from the cellar. * @param owner address of account that would holds the shares * @return maximum amount of assets that can be withdrawn */ function maxWithdraw(address owner) public view returns (uint256) { UserDeposit[] storage deposits = userDeposits[owner]; // Track max assets that can be withdrawn. uint256 assets; // Saves gas by avoiding calling `_convertToAssets` on active shares during each loop. uint256 exchangeRate = _convertToAssets(1e18); for (uint256 i = currentDepositIndex[owner]; i < deposits.length; i++) { UserDeposit storage d = deposits[i]; // Determine the amount of assets that can be withdrawn. Only redeem active shares for // assets, otherwise just withdrawn the original amount of assets that were deposited. assets += d.timeDeposited <= lastTimeEnteredStrategy ? uint256(d.shares).mulWadDown(exchangeRate) : d.assets; } // Return the maximum amount of assets that can be withdrawn in the assets original units. return assets.changeDecimals(decimals, assetDecimals); } /** * @notice Total number of shares that can be redeemed from the cellar. * @param owner address of account that would holds the shares * @return maximum amount of shares that can be redeemed */ function maxRedeem(address owner) public view returns (uint256) { return balanceOf[owner]; } // ====================================== FEE OPERATIONS ====================================== /** * @notice Take platform fees and performance fees off of cellar's active assets. */ function accrueFees() external { // When the contract is shutdown, there should be no reason to accrue fees because there // will be no active assets to accrue fees on. if (isShutdown) revert ContractShutdown(); // Platform fees taken each accrual = activeAssets * (elapsedTime * (2% / SECS_PER_YEAR)). uint256 elapsedTime = block.timestamp - lastTimeAccruedPlatformFees; uint256 platformFeeInAssets = (_activeAssets() * elapsedTime * PLATFORM_FEE) / DENOMINATOR / 365 days; // The cellar accrues fees as shares instead of assets. uint256 platformFees = _convertToShares(platformFeeInAssets); _mint(address(this), platformFees); // Update the tracker for total platform fees accrued that are still waiting to be // transferred. accruedPlatformFees += platformFees; emit AccruedPlatformFees(platformFees); // Begin accrual of performance fees. _accruePerformanceFees(true); } /** * @notice Accrue performance fees. * @param updateFeeData whether or not to update fee data */ function _accruePerformanceFees(bool updateFeeData) internal { // Retrieve the current normalized income per unit of asset for the current strategy on Aave. uint256 normalizedIncome = lendingPool.getReserveNormalizedIncome(address(asset)); // If this is the first time the cellar is accruing performance fees, it will skip the part // were we take fees and should just update the fee data to set a baseline for assessing the // current strategy's performance. if (lastActiveAssets != 0) { // An index value greater than 1e27 indicates positive performance for the strategy's // lending position, while a value less than that indicates negative performance. uint256 performanceIndex = normalizedIncome.mulDivDown(1e27, lastNormalizedIncome); // This is the amount the cellar's active assets have grown to solely from performance // on Aave since the last time performance fees were accrued. It does not include // changes from deposits and withdraws. uint256 updatedActiveAssets = lastActiveAssets.mulDivUp(performanceIndex, 1e27); // Determines whether performance has been positive or negative. if (performanceIndex >= 1e27) { // Fees taken each accrual = (updatedActiveAssets - lastActiveAssets) * 5% uint256 gain = updatedActiveAssets - lastActiveAssets; uint256 performanceFeeInAssets = gain.mulDivDown(PERFORMANCE_FEE, DENOMINATOR); // The cellar accrues fees as shares instead of assets. uint256 performanceFees = _convertToShares(performanceFeeInAssets); _mint(address(this), performanceFees); accruedPerformanceFees += performanceFees; emit AccruedPerformanceFees(performanceFees); } else { // This would only happen if the current stablecoin strategy on Aave performed // negatively. This should rarely happen, if ever, for this particular cellar. But // in case it does, this mechanism will burn performance fees to help offset losses // in proportion to those minted for previous gains. uint256 loss = lastActiveAssets - updatedActiveAssets; uint256 insuranceInAssets = loss.mulDivDown(PERFORMANCE_FEE, DENOMINATOR); // Cannot burn more performance fees than the cellar has accrued. uint256 insurance = MathUtils.min( _convertToShares(insuranceInAssets), accruedPerformanceFees ); _burn(address(this), insurance); accruedPerformanceFees -= insurance; emit BurntPerformanceFees(insurance); } } // There may be cases were we don't want to update fee data in this function, for example // when we accrue performance fees before rebalancing into a new strategy since the data // will be outdated after the rebalance to a new strategy. if (updateFeeData) { lastActiveAssets = _activeAssets(); lastNormalizedIncome = normalizedIncome; } } /** * @notice Transfer accrued fees to Cosmos to distribute. */ function transferFees() external onlyOwner { // Total up all the fees this cellar has accrued and determine how much they can be redeemed // for in assets. uint256 fees = accruedPerformanceFees + accruedPlatformFees; uint256 feeInAssets = previewRedeem(fees); // Redeem our fee shares for assets to transfer to Cosmos. _burn(address(this), fees); // Only withdraw assets from strategy if the holding pool does not contain enough funds. // Otherwise, all assets will come from the holding pool. _allocateAssets(feeInAssets); // Transfer assets to a fee distributor on Cosmos. asset.approve(address(gravityBridge), feeInAssets); gravityBridge.sendToCosmos(address(asset), feesDistributor, feeInAssets); emit TransferFees(accruedPlatformFees, accruedPerformanceFees); // Reset the tracker for fees accrued that are still waiting to be transferred. accruedPlatformFees = 0; accruedPerformanceFees = 0; } // ===================================== ADMIN OPERATIONS ===================================== /** * @notice Enters into the current Aave stablecoin strategy. */ function enterStrategy() external onlyOwner { // When the contract is shutdown, it shouldn't be allowed to enter back into a strategy with // the assets it just withdrew from Aave. if (isShutdown) revert ContractShutdown(); // Deposits all inactive assets in the holding pool into the current strategy. _depositToAave(address(asset), inactiveAssets()); // The cellar will use this when determining which of a user's shares are active vs inactive. lastTimeEnteredStrategy = block.timestamp; } /** * @notice Rebalances current assets into a new asset strategy. * @param route array of [initial token, pool, token, pool, token, ...] that specifies the swap route * @param swapParams multidimensional array of [i, j, swap type] where i and j are the correct values for the n'th pool in `_route` and swap type should be 1 for a stableswap `exchange`, 2 for stableswap `exchange_underlying`, 3 for a cryptoswap `exchange`, 4 for a cryptoswap `exchange_underlying` and 5 for Polygon factory metapools `exchange_underlying` * @param minAmountOut minimum amount received after the final swap */ function rebalance( address[9] memory route, uint256[3][4] memory swapParams, uint256 minAmountOut ) external onlyOwner { // If the contract is shutdown, cellar shouldn't be able to rebalance assets it recently // pulled out back into a new strategy. if (isShutdown) revert ContractShutdown(); // Retrieve the last token in the route and store it as the new asset. address newAsset; for (uint256 i; ; i += 2) { if (i == 8 || route[i+1] == address(0)) { newAsset = route[i]; break; } } // Doesn't make sense to rebalance into the same asset. if (newAsset == address(asset)) revert SameAsset(newAsset); // Accrue any final performance fees from the current strategy before rebalancing. Otherwise // those fees would be lost when we proceed to update fee data for the new strategy. Also we // don't want to update the fee data here because we will do that later on after we've // rebalanced into a new strategy. _accruePerformanceFees(false); // Pull all active assets entered into Aave back into the cellar so we can swap everything // into the new asset. _withdrawFromAave(address(asset), type(uint256).max); uint256 holdingPoolAssets = inactiveAssets(); // Approve Curve to swap the cellar's assets. asset.safeApprove(address(curveRegistryExchange), holdingPoolAssets); // Perform stablecoin swap using Curve. uint256 amountOut = curveRegistryExchange.exchange_multiple( route, swapParams, holdingPoolAssets, minAmountOut ); // Store this later for the event we will emit. address oldAsset = address(asset); // Updates state for our new strategy and check to make sure Aave supports it before // rebalancing. _updateStrategy(newAsset); // Rebalance our assets into a new strategy. _depositToAave(newAsset, amountOut); // Update fee data for next fee accrual with new strategy. lastActiveAssets = _activeAssets(); lastNormalizedIncome = lendingPool.getReserveNormalizedIncome(address(asset)); emit Rebalance(oldAsset, newAsset, amountOut); } /** * @notice Reinvest rewards back into cellar's current strategy. * @dev Must be called within 2 day unstake period 10 days after `claimAndUnstake` was run. * @param minAmountOut minimum amount of assets cellar should receive after swap */ function reinvest(uint256 minAmountOut) public onlyOwner { // Redeems the cellar's stkAAVe rewards for AAVE. stkAAVE.redeem(address(this), type(uint256).max); uint256 amountIn = AAVE.balanceOf(address(this)); // Approve the Sushiswap to swap AAVE. AAVE.safeApprove(address(sushiswapRouter), amountIn); // Specify the swap path from AAVE -> WETH -> current asset. address[] memory path = new address[](3); path[0] = address(AAVE); path[1] = address(WETH); path[2] = address(asset); // Perform a multihop swap using Sushiswap. uint256[] memory amounts = sushiswapRouter.swapExactTokensForTokens( amountIn, minAmountOut, path, address(this), block.timestamp + 60 ); uint256 amountOut = amounts[amounts.length - 1]; // In the case of a shutdown, we just may want to redeem any leftover rewards for // shareholders to claim but without entering them back into a strategy. if (!isShutdown) { // Take performance fee off of rewards. uint256 performanceFeeInAssets = amountOut.mulDivDown(PERFORMANCE_FEE, DENOMINATOR); uint256 performanceFees = convertToShares(performanceFeeInAssets); // Mint performance fees to cellar as shares. _mint(address(this), performanceFees); accruedPerformanceFees += performanceFees; // Reinvest rewards back into the current strategy. _depositToAave(address(asset), amountOut); } } /** * @notice Claim rewards from Aave and begin cooldown period to unstake them. * @return claimed amount of rewards claimed from Aave */ function claimAndUnstake() public onlyOwner returns (uint256 claimed) { // Necessary to do as `claimRewards` accepts a dynamic array as first param. address[] memory aToken = new address[](1); aToken[0] = address(assetAToken); // Claim all stkAAVE rewards. claimed = incentivesController.claimRewards(aToken, type(uint256).max, address(this)); // Begin the cooldown period for unstaking stkAAVE to later redeem for AAVE. stkAAVE.cooldown(); } /** * @notice Sweep tokens sent here that are not managed by the cellar. * @dev This may be used in case the wrong tokens are accidentally sent to this contract. * @param token address of token to transfer out of this cellar */ function sweep(address token) external onlyOwner { // Prevent sweeping of assets managed by the cellar and shares minted to the cellar as fees. if (token == address(asset) || token == address(assetAToken) || token == address(this)) revert ProtectedAsset(token); // Transfer out tokens in this cellar that shouldn't be here. uint256 amount = ERC20(token).balanceOf(address(this)); ERC20(token).safeTransfer(msg.sender, amount); emit Sweep(token, amount); } /** * @notice Removes initial liquidity restriction. */ function removeLiquidityRestriction() external onlyOwner { maxLiquidity = type(uint256).max; emit LiquidityRestrictionRemoved(); } /** * @notice Pause the contract to prevent deposits. * @param _isPaused whether the contract should be paused or unpaused */ function setPause(bool _isPaused) external onlyOwner { if (isShutdown) revert ContractShutdown(); isPaused = _isPaused; emit Pause(_isPaused); } /** * @notice Stops the contract - this is irreversible. Should only be used in an emergency, * for example an irreversible accounting bug or an exploit. */ function shutdown() external onlyOwner { if (isShutdown) revert AlreadyShutdown(); isShutdown = true; // Ensure contract is not paused. isPaused = false; // Withdraw everything from Aave. The check is necessary to prevent a revert happening if we // try to withdraw from Aave without any assets entered into a strategy which would prevent // the contract from being able to be shutdown in this case. if (activeAssets() > 0) _withdrawFromAave(address(asset), type(uint256).max); emit Shutdown(); } // ========================================== HELPERS ========================================== /** * @notice Update state variables related to the current strategy. * @param newAsset address of the new asset being managed by the cellar */ function _updateStrategy(address newAsset) internal { // Retrieve the aToken that will represent the cellar's new strategy on Aave. (, , , , , , , address aTokenAddress, , , , ) = lendingPool.getReserveData(newAsset); // If the address is not null, it is supported by Aave. if (aTokenAddress == address(0)) revert TokenIsNotSupportedByAave(newAsset); // Update state related to the current strategy. asset = ERC20(newAsset); assetDecimals = ERC20(newAsset).decimals(); assetAToken = ERC20(aTokenAddress); // Update the decimals max liquidity is denoted in if restrictions are still in place. if (maxLiquidity != type(uint256).max) maxLiquidity = 5_000_000 * 10**assetDecimals; } /** * @notice Ensures there is enough assets in the contract available for a transfer. * @dev Only withdraws from strategy if needed. * @param assets The amount of assets to allocate */ function _allocateAssets(uint256 assets) internal { uint256 holdingPoolAssets = inactiveAssets(); if (assets > holdingPoolAssets) { _withdrawFromAave(address(asset), assets - holdingPoolAssets); } } /** * @notice Deposits cellar holdings into an Aave lending pool. * @param token the address of the token * @param amount the amount of tokens to deposit */ function _depositToAave(address token, uint256 amount) internal { ERC20(token).safeApprove(address(lendingPool), amount); // Deposit tokens to Aave protocol. lendingPool.deposit(token, amount, address(this), 0); emit DepositToAave(token, amount); } /** * @notice Withdraws assets from Aave. * @param token the address of the token * @param amount the amount of tokens to withdraw * @return withdrawnAmount the withdrawn amount from Aave */ function _withdrawFromAave(address token, uint256 amount) internal returns (uint256) { // Withdraw tokens from Aave protocol uint256 withdrawnAmount = lendingPool.withdraw(token, amount, address(this)); emit WithdrawFromAave(token, withdrawnAmount); return withdrawnAmount; } // ================================= SHARE TRANSFER OPERATIONS ================================= /** * @dev Modified versions of Solmate's ERC20 transfer and transferFrom functions to work with the * cellar's active vs inactive shares mechanic. */ /** * @notice Transfers shares from one account to another. * @dev If the sender specifies to only transfer active shares and does not have enough active * shares to transfer to meet the amount specified, the default behavior is to not to * revert but transfer as many active shares as the sender has to the receiver. * @param from address that is sending shares * @param to address that is receiving shares * @param amount amount of shares to transfer * @param onlyActive whether to only transfer active shares */ function transferFrom( address from, address to, uint256 amount, bool onlyActive ) public returns (bool) { // If the sender is not the owner of the shares, check to see if the owner has approved them // to spend their shares. if (from != msg.sender) { uint256 allowed = allowance[from][msg.sender]; // Saves gas for limited approvals. if (allowed != type(uint256).max) allowance[from][msg.sender] = allowed - amount; } // Retrieve the deposits from sender then begin looping through deposits, generally from // oldest to newest deposits. This may not be the case though if shares have been // transferred to the sender, as they will be added to the end of the sender's deposits // regardless of time deposited. UserDeposit[] storage depositsFrom = userDeposits[from]; // Tracks the amount of shares left to transfer; updated at the end of each loop. uint256 leftToTransfer = amount; for (uint256 i = currentDepositIndex[from]; i < depositsFrom.length; i++) { UserDeposit storage dFrom = depositsFrom[i]; // If we only want to transfer active shares, skips this deposit if it is inactive. bool isActive = dFrom.timeDeposited <= lastTimeEnteredStrategy; if (onlyActive && !isActive) continue; // Saves an extra SLOAD if active and cast type to uint256. uint256 dFromShares = dFrom.shares; // Determine the amount of assets and shares to transfer from this deposit. uint256 transferredShares = MathUtils.min(leftToTransfer, dFromShares); uint256 transferredAssets = uint256(dFrom.assets).mulDivUp(transferredShares, dFromShares); // For active shares, deletes the deposit data we don't need anymore for a gas refund. if (isActive) { delete dFrom.assets; delete dFrom.timeDeposited; } else { dFrom.assets -= uint112(transferredAssets); } // Taken shares from this deposit to transfer. dFrom.shares -= uint112(transferredShares); // Transfer a new deposit to the end of receiver's list of deposits. userDeposits[to].push(UserDeposit({ assets: isActive ? 0 : uint112(transferredAssets), shares: uint112(transferredShares), timeDeposited: isActive ? 0 : dFrom.timeDeposited })); // Update the counter of assets left to transfer. leftToTransfer -= transferredShares; if (i == depositsFrom.length - 1 || leftToTransfer == 0) { // Only store the index for the next non-zero deposit to save gas on looping if // inactive deposits weren't skipped. if (!onlyActive) currentDepositIndex[from] = dFrom.shares != 0 ? i : i+1; break; } } // Determine the total amount of shares transferred. amount -= leftToTransfer; // Will revert here if sender is trying to transfer more shares then they have, so no need // for an explicit check. balanceOf[from] -= amount; // Cannot overflow because the sum of all user balances can't exceed the max uint256 value. unchecked { balanceOf[to] += amount; } emit Transfer(from, to, amount); return true; } /// @dev For compatibility with ERC20 standard. function transferFrom(address from, address to, uint256 amount) public override returns (bool) { // Defaults to only transferring active shares. return transferFrom(from, to, amount, true); } function transfer(address to, uint256 amount) public override returns (bool) { // Defaults to only transferring active shares. return transferFrom(msg.sender, to, amount, true); } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity >=0.8.0; /// @notice Modern and gas efficient ERC20 + EIP-2612 implementation. /// @author Solmate (https://github.com/Rari-Capital/solmate/blob/main/src/tokens/ERC20.sol) /// @author Modified from Uniswap (https://github.com/Uniswap/uniswap-v2-core/blob/master/contracts/UniswapV2ERC20.sol) /// @dev Do not manually set balances without updating totalSupply, as the sum of all user balances must not exceed it. abstract contract ERC20 { /*/////////////////////////////////////////////////////////////// EVENTS //////////////////////////////////////////////////////////////*/ event Transfer(address indexed from, address indexed to, uint256 amount); event Approval(address indexed owner, address indexed spender, uint256 amount); /*/////////////////////////////////////////////////////////////// METADATA STORAGE //////////////////////////////////////////////////////////////*/ string public name; string public symbol; uint8 public immutable decimals; /*/////////////////////////////////////////////////////////////// ERC20 STORAGE //////////////////////////////////////////////////////////////*/ uint256 public totalSupply; mapping(address => uint256) public balanceOf; mapping(address => mapping(address => uint256)) public allowance; /*/////////////////////////////////////////////////////////////// EIP-2612 STORAGE //////////////////////////////////////////////////////////////*/ bytes32 public constant PERMIT_TYPEHASH = keccak256("Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)"); uint256 internal immutable INITIAL_CHAIN_ID; bytes32 internal immutable INITIAL_DOMAIN_SEPARATOR; mapping(address => uint256) public nonces; /*/////////////////////////////////////////////////////////////// CONSTRUCTOR //////////////////////////////////////////////////////////////*/ constructor( string memory _name, string memory _symbol, uint8 _decimals ) { name = _name; symbol = _symbol; decimals = _decimals; INITIAL_CHAIN_ID = block.chainid; INITIAL_DOMAIN_SEPARATOR = computeDomainSeparator(); } /*/////////////////////////////////////////////////////////////// ERC20 LOGIC //////////////////////////////////////////////////////////////*/ function approve(address spender, uint256 amount) public virtual returns (bool) { allowance[msg.sender][spender] = amount; emit Approval(msg.sender, spender, amount); return true; } function transfer(address to, uint256 amount) public virtual returns (bool) { balanceOf[msg.sender] -= amount; // Cannot overflow because the sum of all user // balances can't exceed the max uint256 value. unchecked { balanceOf[to] += amount; } emit Transfer(msg.sender, to, amount); return true; } function transferFrom( address from, address to, uint256 amount ) public virtual returns (bool) { uint256 allowed = allowance[from][msg.sender]; // Saves gas for limited approvals. if (allowed != type(uint256).max) allowance[from][msg.sender] = allowed - amount; balanceOf[from] -= amount; // Cannot overflow because the sum of all user // balances can't exceed the max uint256 value. unchecked { balanceOf[to] += amount; } emit Transfer(from, to, amount); return true; } /*/////////////////////////////////////////////////////////////// EIP-2612 LOGIC //////////////////////////////////////////////////////////////*/ function permit( address owner, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) public virtual { require(deadline >= block.timestamp, "PERMIT_DEADLINE_EXPIRED"); // Unchecked because the only math done is incrementing // the owner's nonce which cannot realistically overflow. unchecked { bytes32 digest = keccak256( abi.encodePacked( "\x19\x01", DOMAIN_SEPARATOR(), keccak256(abi.encode(PERMIT_TYPEHASH, owner, spender, value, nonces[owner]++, deadline)) ) ); address recoveredAddress = ecrecover(digest, v, r, s); require(recoveredAddress != address(0) && recoveredAddress == owner, "INVALID_SIGNER"); allowance[recoveredAddress][spender] = value; } emit Approval(owner, spender, value); } function DOMAIN_SEPARATOR() public view virtual returns (bytes32) { return block.chainid == INITIAL_CHAIN_ID ? INITIAL_DOMAIN_SEPARATOR : computeDomainSeparator(); } function computeDomainSeparator() internal view virtual returns (bytes32) { return keccak256( abi.encode( keccak256("EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)"), keccak256(bytes(name)), keccak256("1"), block.chainid, address(this) ) ); } /*/////////////////////////////////////////////////////////////// INTERNAL MINT/BURN LOGIC //////////////////////////////////////////////////////////////*/ function _mint(address to, uint256 amount) internal virtual { totalSupply += amount; // Cannot overflow because the sum of all user // balances can't exceed the max uint256 value. unchecked { balanceOf[to] += amount; } emit Transfer(address(0), to, amount); } function _burn(address from, uint256 amount) internal virtual { balanceOf[from] -= amount; // Cannot underflow because a user's balance // will never be larger than the total supply. unchecked { totalSupply -= amount; } emit Transfer(from, address(0), amount); } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity >=0.8.0; import {ERC20} from "../tokens/ERC20.sol"; /// @notice Safe ETH and ERC20 transfer library that gracefully handles missing return values. /// @author Solmate (https://github.com/Rari-Capital/solmate/blob/main/src/utils/SafeTransferLib.sol) /// @author Modified from Gnosis (https://github.com/gnosis/gp-v2-contracts/blob/main/src/contracts/libraries/GPv2SafeERC20.sol) /// @dev Use with caution! Some functions in this library knowingly create dirty bits at the destination of the free memory pointer. library SafeTransferLib { /*/////////////////////////////////////////////////////////////// ETH OPERATIONS //////////////////////////////////////////////////////////////*/ function safeTransferETH(address to, uint256 amount) internal { bool callStatus; assembly { // Transfer the ETH and store if it succeeded or not. callStatus := call(gas(), to, amount, 0, 0, 0, 0) } require(callStatus, "ETH_TRANSFER_FAILED"); } /*/////////////////////////////////////////////////////////////// ERC20 OPERATIONS //////////////////////////////////////////////////////////////*/ function safeTransferFrom( ERC20 token, address from, address to, uint256 amount ) internal { bool callStatus; assembly { // Get a pointer to some free memory. let freeMemoryPointer := mload(0x40) // Write the abi-encoded calldata to memory piece by piece: mstore(freeMemoryPointer, 0x23b872dd00000000000000000000000000000000000000000000000000000000) // Begin with the function selector. mstore(add(freeMemoryPointer, 4), and(from, 0xffffffffffffffffffffffffffffffffffffffff)) // Mask and append the "from" argument. mstore(add(freeMemoryPointer, 36), and(to, 0xffffffffffffffffffffffffffffffffffffffff)) // Mask and append the "to" argument. mstore(add(freeMemoryPointer, 68), amount) // Finally append the "amount" argument. No mask as it's a full 32 byte value. // Call the token and store if it succeeded or not. // We use 100 because the calldata length is 4 + 32 * 3. callStatus := call(gas(), token, 0, freeMemoryPointer, 100, 0, 0) } require(didLastOptionalReturnCallSucceed(callStatus), "TRANSFER_FROM_FAILED"); } function safeTransfer( ERC20 token, address to, uint256 amount ) internal { bool callStatus; assembly { // Get a pointer to some free memory. let freeMemoryPointer := mload(0x40) // Write the abi-encoded calldata to memory piece by piece: mstore(freeMemoryPointer, 0xa9059cbb00000000000000000000000000000000000000000000000000000000) // Begin with the function selector. mstore(add(freeMemoryPointer, 4), and(to, 0xffffffffffffffffffffffffffffffffffffffff)) // Mask and append the "to" argument. mstore(add(freeMemoryPointer, 36), amount) // Finally append the "amount" argument. No mask as it's a full 32 byte value. // Call the token and store if it succeeded or not. // We use 68 because the calldata length is 4 + 32 * 2. callStatus := call(gas(), token, 0, freeMemoryPointer, 68, 0, 0) } require(didLastOptionalReturnCallSucceed(callStatus), "TRANSFER_FAILED"); } function safeApprove( ERC20 token, address to, uint256 amount ) internal { bool callStatus; assembly { // Get a pointer to some free memory. let freeMemoryPointer := mload(0x40) // Write the abi-encoded calldata to memory piece by piece: mstore(freeMemoryPointer, 0x095ea7b300000000000000000000000000000000000000000000000000000000) // Begin with the function selector. mstore(add(freeMemoryPointer, 4), and(to, 0xffffffffffffffffffffffffffffffffffffffff)) // Mask and append the "to" argument. mstore(add(freeMemoryPointer, 36), amount) // Finally append the "amount" argument. No mask as it's a full 32 byte value. // Call the token and store if it succeeded or not. // We use 68 because the calldata length is 4 + 32 * 2. callStatus := call(gas(), token, 0, freeMemoryPointer, 68, 0, 0) } require(didLastOptionalReturnCallSucceed(callStatus), "APPROVE_FAILED"); } /*/////////////////////////////////////////////////////////////// INTERNAL HELPER LOGIC //////////////////////////////////////////////////////////////*/ function didLastOptionalReturnCallSucceed(bool callStatus) private pure returns (bool success) { assembly { // Get how many bytes the call returned. let returnDataSize := returndatasize() // If the call reverted: if iszero(callStatus) { // Copy the revert message into memory. returndatacopy(0, 0, returnDataSize) // Revert with the same message. revert(0, returnDataSize) } switch returnDataSize case 32 { // Copy the return data into memory. returndatacopy(0, 0, returnDataSize) // Set success to whether it returned true. success := iszero(iszero(mload(0))) } case 0 { // There was no return data. success := 1 } default { // It returned some malformed input. success := 0 } } } } // 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: Apache-2.0 pragma solidity ^0.8.11; /// @title interface for AaveV2StablecoinCellar interface IAaveV2StablecoinCellar { // ======================================= EVENTS ======================================= /** * @notice Emitted when assets are deposited into cellar. * @param caller the address of the caller * @param token the address of token the cellar receives * @param owner the address of the owner of shares * @param assets the amount of assets being deposited * @param shares the amount of shares minted to owner */ event Deposit( address indexed caller, address indexed owner, address indexed token, uint256 assets, uint256 shares ); /** * @notice Emitted when assets are withdrawn from cellar. * @param receiver the address of the receiver of the withdrawn assets * @param owner the address of the owner of the shares * @param token the address of the token withdrawn * @param assets the amount of assets being withdrawn * @param shares the amount of shares burned from owner */ event Withdraw( address indexed receiver, address indexed owner, address indexed token, uint256 assets, uint256 shares ); /** * @notice Emitted on deposit to Aave. * @param token the address of the token * @param amount the amount of tokens to deposit */ event DepositToAave( address indexed token, uint256 amount ); /** * @notice Emitted on withdraw from Aave. * @param token the address of the token * @param amount the amount of tokens to withdraw */ event WithdrawFromAave( address indexed token, uint256 amount ); /** * @notice Emitted on rebalance of Aave strategy. * @param oldAsset the address of the asset for the old strategy * @param newAsset the address of the asset for the new strategy * @param assets the amount of the new assets that has been deposited to Aave after rebalance */ event Rebalance( address indexed oldAsset, address indexed newAsset, uint256 assets ); /** * @notice Emitted when platform fees accrued. * @param fees amount of fees accrued in shares */ event AccruedPlatformFees(uint256 fees); /** * @notice Emitted when performance fees accrued. * @param fees amount of fees accrued in shares */ event AccruedPerformanceFees(uint256 fees); /** * @notice Emitted when performance fees burnt as insurance. * @param fees amount of fees burnt in shares */ event BurntPerformanceFees(uint256 fees); /** * @notice Emitted when platform fees are transferred to Cosmos. * @param platformFees amount of platform fees transferred * @param performanceFees amount of performance fees transferred */ event TransferFees(uint256 platformFees, uint256 performanceFees); /** * @notice Emitted when liquidity restriction removed. */ event LiquidityRestrictionRemoved(); /** * @notice Emitted when tokens accidentally sent to cellar are recovered. * @param token the address of the token * @param amount amount transferred out */ event Sweep(address indexed token, uint256 amount); /** * @notice Emitted when cellar is paused. * @param isPaused whether the contract is paused */ event Pause(bool isPaused); /** * @notice Emitted when cellar is shutdown. */ event Shutdown(); // ======================================= ERRORS ======================================= /** * @notice Attempted an action with zero assets. */ error ZeroAssets(); /** * @notice Attempted an action with zero shares. */ error ZeroShares(); /** * @notice Attempted deposit more liquidity over the liquidity limit. * @param maxLiquidity the max liquidity */ error LiquidityRestricted(uint256 maxLiquidity); /** * @notice Attempted deposit more than the per wallet limit. * @param maxDeposit the max deposit */ error DepositRestricted(uint256 maxDeposit); /** * @notice Current asset is updated to an asset not supported by Aave. * @param unsupportedToken address of the unsupported token */ error TokenIsNotSupportedByAave(address unsupportedToken); /** * @notice Attempted to sweep an asset that is managed by the cellar. * @param token address of the token that can't be sweeped */ error ProtectedAsset(address token); /** * @notice Attempted rebalance into the same asset. * @param asset address of the asset */ error SameAsset(address asset); /** * @notice Attempted action was prevented due to contract being shutdown. */ error ContractShutdown(); /** * @notice Attempted action was prevented due to contract being paused. */ error ContractPaused(); /** * @notice Attempted to shutdown the contract when it was already shutdown. */ error AlreadyShutdown(); // ======================================= STRUCTS ======================================= /** * @notice Stores user deposit data. * @param assets amount of assets deposited * @param shares amount of shares that were minted for their deposit * @param timeDeposited timestamp of when the user deposited */ struct UserDeposit { uint112 assets; uint112 shares; uint32 timeDeposited; } // ================================= DEPOSIT/WITHDRAWAL OPERATIONS ================================= function deposit(uint256 assets, address receiver) external returns (uint256); function mint(uint256 shares, address receiver) external returns (uint256); function withdraw( uint256 assets, address receiver, address owner ) external returns (uint256 shares); function redeem( uint256 shares, address receiver, address owner ) external returns (uint256 assets); // ==================================== ACCOUNTING OPERATIONS ==================================== function activeAssets() external view returns (uint256); function inactiveAssets() external view returns (uint256); function totalAssets() external view returns (uint256); function convertToShares(uint256 assets) external view returns (uint256); function convertToAssets(uint256 shares) external view returns (uint256); function previewDeposit(uint256 assets) external view returns (uint256); function previewMint(uint256 shares) external view returns (uint256); function previewWithdraw(uint256 assets) external view returns (uint256); function previewRedeem(uint256 shares) external view returns (uint256); // ======================================= STATE INFORMATION ===================================== function depositBalances(address user) external view returns ( uint256 userActiveShares, uint256 userInactiveShares, uint256 userActiveAssets, uint256 userInactiveAssets ); function numDeposits(address user) external view returns (uint256); // ============================ DEPOSIT/WITHDRAWAL LIMIT OPERATIONS ============================ function maxDeposit(address owner) external view returns (uint256); function maxMint(address owner) external view returns (uint256); function maxWithdraw(address owner) external view returns (uint256); function maxRedeem(address owner) external view returns (uint256); // ======================================= FEE OPERATIONS ======================================= function accrueFees() external; function transferFees() external; // ======================================= ADMIN OPERATIONS ======================================= function enterStrategy() external; function rebalance( address[9] memory route, uint256[3][4] memory swapParams, uint256 minAmountOut ) external; function reinvest(uint256 minAmountOut) external; function claimAndUnstake() external returns (uint256 claimed); function sweep(address token) external; function removeLiquidityRestriction() external; function setPause(bool _isPaused) external; function shutdown() external; // ================================== SHARE TRANSFER OPERATIONS ================================== function transferFrom( address from, address to, uint256 amount, bool onlyActive ) external returns (bool); } // SPDX-License-Identifier: Apache-2.0 pragma solidity ^0.8.11; interface IAaveIncentivesController { event RewardsAccrued(address indexed user, uint256 amount); event RewardsClaimed( address indexed user, address indexed to, address indexed claimer, uint256 amount ); event ClaimerSet(address indexed user, address indexed claimer); /* * @dev Returns the configuration of the distribution for a certain asset * @param asset The address of the reference asset of the distribution * @return The asset index, the emission per second and the last updated timestamp **/ function getAssetData(address asset) external view returns ( uint256, uint256, uint256 ); /* * LEGACY ************************** * @dev Returns the configuration of the distribution for a certain asset * @param asset The address of the reference asset of the distribution * @return The asset index, the emission per second and the last updated timestamp **/ function assets(address asset) external view returns ( uint128, uint128, uint256 ); /** * @dev Whitelists an address to claim the rewards on behalf of another address * @param user The address of the user * @param claimer The address of the claimer */ function setClaimer(address user, address claimer) external; /** * @dev Returns the whitelisted claimer for a certain address (0x0 if not set) * @param user The address of the user * @return The claimer address */ function getClaimer(address user) external view returns (address); /** * @dev Configure assets for a certain rewards emission * @param assets The assets to incentivize * @param emissionsPerSecond The emission for each asset */ function configureAssets(address[] calldata assets, uint256[] calldata emissionsPerSecond) external; /** * @dev Called by the corresponding asset on any update that affects the rewards distribution * @param asset The address of the user * @param userBalance The balance of the user of the asset in the lending pool * @param totalSupply The total supply of the asset in the lending pool **/ function handleAction( address asset, uint256 userBalance, uint256 totalSupply ) external; /** * @dev Returns the total of rewards of an user, already accrued + not yet accrued * @param user The address of the user * @return The rewards **/ function getRewardsBalance(address[] calldata assets, address user) external view returns (uint256); /** * @dev Claims reward for an user, on all the assets of the lending pool, accumulating the pending rewards * @param amount Amount of rewards to claim * @param to Address that will be receiving the rewards * @return Rewards claimed **/ function claimRewards( address[] calldata assets, uint256 amount, address to ) external returns (uint256); /** * @dev Claims reward for an user on behalf, on all the assets of the lending pool, accumulating the pending rewards. The caller must * be whitelisted via "allowClaimOnBehalf" function by the RewardsAdmin role manager * @param amount Amount of rewards to claim * @param user Address to check and claim rewards * @param to Address that will be receiving the rewards * @return Rewards claimed **/ function claimRewardsOnBehalf( address[] calldata assets, uint256 amount, address user, address to ) external returns (uint256); /** * @dev returns the unclaimed rewards of the user * @param user the address of the user * @return the unclaimed user rewards */ function getUserUnclaimedRewards(address user) external view returns (uint256); /** * @dev returns the unclaimed rewards of the user * @param user the address of the user * @param asset The asset to incentivize * @return the user index for the asset */ function getUserAssetData(address user, address asset) external view returns (uint256); /** * @dev for backward compatibility with previous implementation of the Incentives controller */ function REWARD_TOKEN() external view returns (address); /** * @dev for backward compatibility with previous implementation of the Incentives controller */ function PRECISION() external view returns (uint8); /** * @dev Gets the distribution end timestamp of the emissions */ function DISTRIBUTION_END() external view returns (uint256); } // SPDX-License-Identifier: agpl-3.0 pragma solidity ^0.8.11; interface IStakedTokenV2 { function stake(address to, uint256 amount) external; function redeem(address to, uint256 amount) external; function cooldown() external; function claimRewards(address to, uint256 amount) external; function balanceOf(address account) external view returns (uint256); function stakersCooldowns(address account) external view returns (uint256); } // SPDX-License-Identifier: Apache-2.0 pragma solidity ^0.8.11; interface ICurveSwaps { function exchange_multiple( address[9] memory _route, uint256[3][4] memory _swap_params, uint256 _amount, uint256 _expected ) external returns (uint256); } // SPDX-License-Identifier: Apache-2.0 pragma solidity ^0.8.11; /** * @notice Partial interface for a SushiSwap Router contract **/ interface ISushiSwapRouter { function swapExactTokensForTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external returns (uint[] memory amounts); } // SPDX-License-Identifier: Apache-2.0 pragma solidity ^0.8.11; interface IGravity { function sendToCosmos(address _tokenContract, bytes32 _destination, uint256 _amount) external; } // SPDX-License-Identifier: Apache-2.0 pragma solidity ^0.8.11; /** * @dev Partial interface for a Aave LendingPool contract, * which is the main point of interaction with an Aave protocol's market **/ interface ILendingPool { /** * @dev Deposits an `amount` of underlying asset into the reserve, receiving in return overlying aTokens. * - E.g. User deposits 100 USDC and gets in return 100 aUSDC * @param asset The address of the underlying asset to deposit * @param amount The amount to be deposited * @param onBehalfOf The address that will receive the aTokens, same as msg.sender if the user * wants to receive them on his own wallet, or a different address if the beneficiary of aTokens * is a different wallet * @param referralCode Code used to register the integrator originating the operation, for potential rewards. * 0 if the action is executed directly by the user, without any middle-man **/ function deposit( address asset, uint256 amount, address onBehalfOf, uint16 referralCode ) external; /** * @dev Withdraws an `amount` of underlying asset from the reserve, burning the equivalent aTokens owned * E.g. User has 100 aUSDC, calls withdraw() and receives 100 USDC, burning the 100 aUSDC * @param asset The address of the underlying asset to withdraw * @param amount The underlying amount to be withdrawn * - Send the value type(uint256).max in order to withdraw the whole aToken balance * @param to Address that will receive the underlying, same as msg.sender if the user * wants to receive it on his own wallet, or a different address if the beneficiary is a * different wallet * @return The final amount withdrawn **/ function withdraw( address asset, uint256 amount, address to ) external returns (uint256); /** * @dev Returns the normalized income normalized income of the reserve * @param asset The address of the underlying asset of the reserve * @return The reserve's normalized income */ function getReserveNormalizedIncome(address asset) external view returns (uint256); /** * @dev Returns the normalized income normalized income of the reserve * @param asset The address of the underlying asset of the reserve **/ function getReserveData(address asset) external view returns ( //stores the reserve configuration //bit 0-15: LTV //bit 16-31: Liq. threshold //bit 32-47: Liq. bonus //bit 48-55: Decimals //bit 56: Reserve is active //bit 57: reserve is frozen //bit 58: borrowing is enabled //bit 59: stable rate borrowing enabled //bit 60-63: reserved //bit 64-79: reserve factor uint256 configuration, //the liquidity index. Expressed in ray uint128 liquidityIndex, //variable borrow index. Expressed in ray uint128 variableBorrowIndex, //the current supply rate. Expressed in ray uint128 currentLiquidityRate, //the current variable borrow rate. Expressed in ray uint128 currentVariableBorrowRate, //the current stable borrow rate. Expressed in ray uint128 currentStableBorrowRate, uint40 lastUpdateTimestamp, //tokens addresses address aTokenAddress, address stableDebtTokenAddress, address variableDebtTokenAddress, //address of the interest rate strategy address interestRateStrategyAddress, //the id of the reserve. Represents the position in the list of the active reserves uint8 id ); } // SPDX-License-Identifier: Apache-2.0 pragma solidity ^0.8.11; library MathUtils { /** * @notice Used to change the decimals of precision used for an amount. */ function changeDecimals( uint256 amount, uint8 fromDecimals, uint8 toDecimals ) internal pure returns (uint256) { if (fromDecimals == toDecimals) { return amount; } else if (fromDecimals < toDecimals) { return amount * 10**(toDecimals - fromDecimals); } else { return ceilDiv(amount, 10**(fromDecimals - toDecimals)); } } // ===================================== OPENZEPPELIN'S MATH ===================================== function ceilDiv(uint256 a, uint256 b) internal pure returns (uint256) { // (a + b - 1) / b can overflow on addition, so we distribute. return a / b + (a % b == 0 ? 0 : 1); } function min(uint256 a, uint256 b) internal pure returns (uint256) { return a < b ? a : b; } // ================================= SOLMATE's FIXEDPOINTMATHLIB ================================= uint256 public constant WAD = 1e18; // The scalar of ETH and most ERC20s. function mulWadDown(uint256 x, uint256 y) internal pure returns (uint256) { return mulDivDown(x, y, WAD); // Equivalent to (x * y) / WAD rounded down. } function mulDivDown( uint256 x, uint256 y, uint256 denominator ) internal pure returns (uint256 z) { assembly { // Store x * y in z for now. z := mul(x, y) // Equivalent to require(denominator != 0 && (x == 0 || (x * y) / x == y)) if iszero(and(iszero(iszero(denominator)), or(iszero(x), eq(div(z, x), y)))) { revert(0, 0) } // Divide z by the denominator. z := div(z, denominator) } } function mulDivUp( uint256 x, uint256 y, uint256 denominator ) internal pure returns (uint256 z) { assembly { // Store x * y in z for now. z := mul(x, y) // Equivalent to require(denominator != 0 && (x == 0 || (x * y) / x == y)) if iszero(and(iszero(iszero(denominator)), or(iszero(x), eq(div(z, x), y)))) { revert(0, 0) } // First, divide z - 1 by the denominator and add 1. // We allow z - 1 to underflow if z is 0, because we multiply the // end result by 0 if z is zero, ensuring we return 0 if z is zero. z := mul(iszero(iszero(z)), add(div(sub(z, 1), denominator), 1)) } } } // 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; } }
Take platform fees and performance fees off of cellar's active assets./ When the contract is shutdown, there should be no reason to accrue fees because there will be no active assets to accrue fees on. Platform fees taken each accrual = activeAssets (elapsedTime (2% / SECS_PER_YEAR)). The cellar accrues fees as shares instead of assets. Update the tracker for total platform fees accrued that are still waiting to be transferred. Begin accrual of performance fees.
function accrueFees() external { if (isShutdown) revert ContractShutdown(); uint256 elapsedTime = block.timestamp - lastTimeAccruedPlatformFees; uint256 platformFeeInAssets = (_activeAssets() * elapsedTime * PLATFORM_FEE) / DENOMINATOR / 365 days; uint256 platformFees = _convertToShares(platformFeeInAssets); _mint(address(this), platformFees); accruedPlatformFees += platformFees; emit AccruedPlatformFees(platformFees); _accruePerformanceFees(true); }
265,731
./partial_match/1/0x7A6425C9b3F5521BFa5d71Df710A2FB80508319b/sources/Exchange.sol
Executes an exchange method call in the context of signer. salt Arbitrary number to ensure uniqueness of transaction hash. signerAddress Address of transaction signer. data AbiV2 encoded calldata. signature Proof of signer transaction by signer. File: contracts/exchange/mixins/MTransactions.sol/ Hash for the EIP712 ZeroEx Transaction Schema
{ bytes32 constant internal EIP712_ZEROEX_TRANSACTION_SCHEMA_HASH = keccak256(abi.encodePacked( "ZeroExTransaction(", "uint256 salt,", "address signerAddress,", "bytes data", ")" )); function hashZeroExTransaction( uint256 salt, address signerAddress, bytes memory data ) internal pure returns (bytes32 result); function getCurrentContextAddress() internal view returns (address); }
4,477,642
// SPDX-License-Identifier: MIT // Sources flattened with hardhat v2.0.5 https://hardhat.org // File contracts/interface/IFlashloanExecutor.sol pragma solidity 0.6.12; interface IFlashloanExecutor { function executeOperation( address reserve, uint256 amount, uint256 fee, bytes memory data ) external; } // File @openzeppelin/contracts-upgradeable/math/[email protected] 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, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } // File contracts/library/SafeRatioMath.sol pragma solidity 0.6.12; library SafeRatioMath { using SafeMathUpgradeable for uint256; uint256 private constant BASE = 10**18; uint256 private constant DOUBLE = 10**36; function divup(uint256 x, uint256 y) internal pure returns (uint256 z) { z = x.add(y.sub(1)).div(y); } function rmul(uint256 x, uint256 y) internal pure returns (uint256 z) { z = x.mul(y).div(BASE); } function rdiv(uint256 x, uint256 y) internal pure returns (uint256 z) { z = x.mul(BASE).div(y); } function rdivup(uint256 x, uint256 y) internal pure returns (uint256 z) { z = x.mul(BASE).add(y.sub(1)).div(y); } function tmul( uint256 x, uint256 y, uint256 z ) internal pure returns (uint256 result) { result = x.mul(y).mul(z).div(DOUBLE); } function rpow( uint256 x, uint256 n, uint256 base ) internal pure returns (uint256 z) { assembly { switch x case 0 { switch n case 0 { z := base } default { z := 0 } } default { switch mod(n, 2) case 0 { z := base } default { z := x } let half := div(base, 2) // for rounding. for { n := div(n, 2) } n { n := div(n, 2) } { let xx := mul(x, x) if iszero(eq(div(xx, x), x)) { revert(0, 0) } let xxRound := add(xx, half) if lt(xxRound, xx) { revert(0, 0) } x := div(xxRound, base) if mod(n, 2) { let zx := mul(z, x) if and( iszero(iszero(x)), iszero(eq(div(zx, x), z)) ) { revert(0, 0) } let zxRound := add(zx, half) if lt(zxRound, zx) { revert(0, 0) } z := div(zxRound, base) } } } } } } // File @openzeppelin/contracts-upgradeable/token/ERC20/[email protected] 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); } // File contracts/library/Initializable.sol pragma solidity 0.6.12; /** * @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 Modifier to protect an initializer function from being invoked twice. */ modifier initializer() { require( !_initialized, "Initializable: contract is already initialized" ); _; _initialized = true; } } // File contracts/library/ReentrancyGuard.sol pragma solidity 0.6.12; /** * @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 { 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; function __ReentrancyGuard_init() 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; } uint256[49] private __gap; } // File contracts/library/Ownable.sol pragma solidity 0.6.12; /** * @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 {_setPendingOwner} and {_acceptOwner}. */ contract Ownable { /** * @dev Returns the address of the current owner. */ address payable public owner; /** * @dev Returns the address of the current pending owner. */ address payable public pendingOwner; event NewOwner(address indexed previousOwner, address indexed newOwner); event NewPendingOwner( address indexed oldPendingOwner, address indexed newPendingOwner ); /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner == msg.sender, "onlyOwner: caller is not the owner"); _; } /** * @dev Initializes the contract setting the deployer as the initial owner. */ function __Ownable_init() internal { owner = msg.sender; emit NewOwner(address(0), msg.sender); } /** * @notice Base on the inputing parameter `newPendingOwner` to check the exact error reason. * @dev Transfer contract control to a new owner. The newPendingOwner must call `_acceptOwner` to finish the transfer. * @param newPendingOwner New pending owner. */ function _setPendingOwner(address payable newPendingOwner) external onlyOwner { require( newPendingOwner != address(0) && newPendingOwner != pendingOwner, "_setPendingOwner: New owenr can not be zero address and owner has been set!" ); // Gets current owner. address oldPendingOwner = pendingOwner; // Sets new pending owner. pendingOwner = newPendingOwner; emit NewPendingOwner(oldPendingOwner, newPendingOwner); } /** * @dev Accepts the admin rights, but only for pendingOwenr. */ function _acceptOwner() external { require( msg.sender == pendingOwner, "_acceptOwner: Only for pending owner!" ); // Gets current values for events. address oldOwner = owner; address oldPendingOwner = pendingOwner; // Set the new contract owner. owner = pendingOwner; // Clear the pendingOwner. pendingOwner = address(0); emit NewOwner(oldOwner, owner); emit NewPendingOwner(oldPendingOwner, pendingOwner); } uint256[50] private __gap; } // File contracts/library/ERC20.sol pragma solidity 0.6.12; /** * @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 { using SafeMathUpgradeable for uint256; mapping(address => uint256) public balanceOf; mapping(address => mapping(address => uint256)) public allowance; uint256 public totalSupply; string public name; string public symbol; uint8 public decimals; /** * @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 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_, uint8 decimals_ ) internal { name = name_; symbol = symbol_; decimals = decimals_; } /** * @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 returns (bool) { _transfer(msg.sender, recipient, amount); return true; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual returns (bool) { _approve(msg.sender, spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}. * * Requirements: * * - `sender` and `recipient` cannot be the zero 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 returns (bool) { _transfer(sender, recipient, amount); _approve(sender, msg.sender, allowance[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 virtual returns (bool) { _approve( msg.sender, spender, allowance[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 virtual returns (bool) { _approve( msg.sender, spender, allowance[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 virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); balanceOf[sender] = balanceOf[sender].sub(amount); balanceOf[recipient] = balanceOf[recipient].add(amount); emit Transfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements: * * - `to` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); totalSupply = totalSupply.add(amount); balanceOf[account] = balanceOf[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"); balanceOf[account] = balanceOf[account].sub(amount); totalSupply = totalSupply.sub(amount); emit Transfer(account, address(0), amount); } /** * @dev Destroys `amount` tokens from `account`, deducting from the caller's * allowance if caller is not the `account`. * * See {ERC20-_burn} and {ERC20-allowance}. * * Requirements: * * - the caller other than `msg.sender` must have allowance for ``accounts``'s tokens of at least * `amount`. */ function _burnFrom(address account, uint256 amount) internal virtual { if (msg.sender != account) _approve( account, msg.sender, allowance[account][msg.sender].sub(amount) ); _burn(account, 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"); allowance[owner][spender] = amount; emit Approval(owner, spender, amount); } uint256[50] private __gap; } // File contracts/interface/IInterestRateModelInterface.sol pragma solidity 0.6.12; /** * @title dForce Lending Protocol's InterestRateModel Interface. * @author dForce Team. */ interface IInterestRateModelInterface { function isInterestRateModel() external view returns (bool); /** * @dev Calculates the current borrow interest rate per block. * @param cash The total amount of cash the market has. * @param borrows The total amount of borrows the market has. * @param reserves The total amnount of reserves the market has. * @return The borrow rate per block (as a percentage, and scaled by 1e18). */ function getBorrowRate( uint256 cash, uint256 borrows, uint256 reserves ) external view returns (uint256); /** * @dev Calculates the current supply interest rate per block. * @param cash The total amount of cash the market has. * @param borrows The total amount of borrows the market has. * @param reserves The total amnount of reserves the market has. * @param reserveRatio The current reserve factor the market has. * @return The supply rate per block (as a percentage, and scaled by 1e18). */ function getSupplyRate( uint256 cash, uint256 borrows, uint256 reserves, uint256 reserveRatio ) external view returns (uint256); } // File contracts/interface/IControllerInterface.sol pragma solidity 0.6.12; interface IControllerAdminInterface { /// @notice Emitted when an admin supports a market event MarketAdded( address iToken, uint256 collateralFactor, uint256 borrowFactor, uint256 supplyCapacity, uint256 borrowCapacity, uint256 distributionFactor ); function _addMarket( address _iToken, uint256 _collateralFactor, uint256 _borrowFactor, uint256 _supplyCapacity, uint256 _borrowCapacity, uint256 _distributionFactor ) external; /// @notice Emitted when new price oracle is set event NewPriceOracle(address oldPriceOracle, address newPriceOracle); function _setPriceOracle(address newOracle) external; /// @notice Emitted when close factor is changed by admin event NewCloseFactor( uint256 oldCloseFactorMantissa, uint256 newCloseFactorMantissa ); function _setCloseFactor(uint256 newCloseFactorMantissa) external; /// @notice Emitted when liquidation incentive is changed by admin event NewLiquidationIncentive( uint256 oldLiquidationIncentiveMantissa, uint256 newLiquidationIncentiveMantissa ); function _setLiquidationIncentive(uint256 newLiquidationIncentiveMantissa) external; /// @notice Emitted when iToken's collateral factor is changed by admin event NewCollateralFactor( address iToken, uint256 oldCollateralFactorMantissa, uint256 newCollateralFactorMantissa ); function _setCollateralFactor( address iToken, uint256 newCollateralFactorMantissa ) external; /// @notice Emitted when iToken's borrow factor is changed by admin event NewBorrowFactor( address iToken, uint256 oldBorrowFactorMantissa, uint256 newBorrowFactorMantissa ); function _setBorrowFactor(address iToken, uint256 newBorrowFactorMantissa) external; /// @notice Emitted when iToken's borrow capacity is changed by admin event NewBorrowCapacity( address iToken, uint256 oldBorrowCapacity, uint256 newBorrowCapacity ); function _setBorrowCapacity(address iToken, uint256 newBorrowCapacity) external; /// @notice Emitted when iToken's supply capacity is changed by admin event NewSupplyCapacity( address iToken, uint256 oldSupplyCapacity, uint256 newSupplyCapacity ); function _setSupplyCapacity(address iToken, uint256 newSupplyCapacity) external; /// @notice Emitted when pause guardian is changed by admin event NewPauseGuardian(address oldPauseGuardian, address newPauseGuardian); function _setPauseGuardian(address newPauseGuardian) external; /// @notice Emitted when mint is paused/unpaused by admin or pause guardian event MintPaused(address iToken, bool paused); function _setMintPaused(address iToken, bool paused) external; function _setAllMintPaused(bool paused) external; /// @notice Emitted when redeem is paused/unpaused by admin or pause guardian event RedeemPaused(address iToken, bool paused); function _setRedeemPaused(address iToken, bool paused) external; function _setAllRedeemPaused(bool paused) external; /// @notice Emitted when borrow is paused/unpaused by admin or pause guardian event BorrowPaused(address iToken, bool paused); function _setBorrowPaused(address iToken, bool paused) external; function _setAllBorrowPaused(bool paused) external; /// @notice Emitted when transfer is paused/unpaused by admin or pause guardian event TransferPaused(bool paused); function _setTransferPaused(bool paused) external; /// @notice Emitted when seize is paused/unpaused by admin or pause guardian event SeizePaused(bool paused); function _setSeizePaused(bool paused) external; function _setiTokenPaused(address iToken, bool paused) external; function _setProtocolPaused(bool paused) external; event NewRewardDistributor( address oldRewardDistributor, address _newRewardDistributor ); function _setRewardDistributor(address _newRewardDistributor) external; } interface IControllerPolicyInterface { function beforeMint( address iToken, address account, uint256 mintAmount ) external; function afterMint( address iToken, address minter, uint256 mintAmount, uint256 mintedAmount ) external; function beforeRedeem( address iToken, address redeemer, uint256 redeemAmount ) external; function afterRedeem( address iToken, address redeemer, uint256 redeemAmount, uint256 redeemedAmount ) external; function beforeBorrow( address iToken, address borrower, uint256 borrowAmount ) external; function afterBorrow( address iToken, address borrower, uint256 borrowedAmount ) external; function beforeRepayBorrow( address iToken, address payer, address borrower, uint256 repayAmount ) external; function afterRepayBorrow( address iToken, address payer, address borrower, uint256 repayAmount ) external; function beforeLiquidateBorrow( address iTokenBorrowed, address iTokenCollateral, address liquidator, address borrower, uint256 repayAmount ) external; function afterLiquidateBorrow( address iTokenBorrowed, address iTokenCollateral, address liquidator, address borrower, uint256 repaidAmount, uint256 seizedAmount ) external; function beforeSeize( address iTokenBorrowed, address iTokenCollateral, address liquidator, address borrower, uint256 seizeAmount ) external; function afterSeize( address iTokenBorrowed, address iTokenCollateral, address liquidator, address borrower, uint256 seizedAmount ) external; function beforeTransfer( address iToken, address from, address to, uint256 amount ) external; function afterTransfer( address iToken, address from, address to, uint256 amount ) external; function beforeFlashloan( address iToken, address to, uint256 amount ) external; function afterFlashloan( address iToken, address to, uint256 amount ) external; } interface IControllerAccountEquityInterface { function calcAccountEquity(address account) external view returns ( uint256, uint256, uint256, uint256 ); function liquidateCalculateSeizeTokens( address iTokenBorrowed, address iTokenCollateral, uint256 actualRepayAmount ) external view returns (uint256); } interface IControllerAccountInterface { function hasEnteredMarket(address account, address iToken) external view returns (bool); function getEnteredMarkets(address account) external view returns (address[] memory); /// @notice Emitted when an account enters a market event MarketEntered(address iToken, address account); function enterMarkets(address[] calldata iTokens) external returns (bool[] memory); /// @notice Emitted when an account exits a market event MarketExited(address iToken, address account); function exitMarkets(address[] calldata iTokens) external returns (bool[] memory); /// @notice Emitted when an account add a borrow asset event BorrowedAdded(address iToken, address account); /// @notice Emitted when an account remove a borrow asset event BorrowedRemoved(address iToken, address account); function hasBorrowed(address account, address iToken) external view returns (bool); function getBorrowedAssets(address account) external view returns (address[] memory); } interface IControllerInterface is IControllerAdminInterface, IControllerPolicyInterface, IControllerAccountEquityInterface, IControllerAccountInterface { /** * @notice Security checks when updating the comptroller of a market, always expect to return true. */ function isController() external view returns (bool); /** * @notice Return all of the iTokens * @return The list of iToken addresses */ function getAlliTokens() external view returns (address[] memory); /** * @notice Check whether a iToken is listed in controller * @param _iToken The iToken to check for * @return true if the iToken is listed otherwise false */ function hasiToken(address _iToken) external view returns (bool); } // File contracts/TokenBase/TokenStorage.sol pragma solidity 0.6.12; /** * @title dForce's lending Token storage Contract * @author dForce */ contract TokenStorage is Initializable, ReentrancyGuard, Ownable, ERC20 { //---------------------------------- //********* Token Storage ********** //---------------------------------- uint256 constant BASE = 1e18; /** * @dev Whether this token is supported in the market or not. */ bool public constant isSupported = true; /** * @dev Maximum borrow rate(0.1% per block, scaled by 1e18). */ uint256 constant maxBorrowRate = 0.001e18; /** * @dev Interest ratio set aside for reserves(scaled by 1e18). */ uint256 public reserveRatio; /** * @dev Maximum interest ratio that can be set aside for reserves(scaled by 1e18). */ uint256 constant maxReserveRatio = 1e18; /** * @notice This ratio is relative to the total flashloan fee. * @dev Flash loan fee rate(scaled by 1e18). */ uint256 public flashloanFeeRatio; /** * @notice This ratio is relative to the total flashloan fee. * @dev Protocol fee rate when a flashloan happens(scaled by 1e18); */ uint256 public protocolFeeRatio; /** * @dev Underlying token address. */ IERC20Upgradeable public underlying; /** * @dev Current interest rate model contract. */ IInterestRateModelInterface public interestRateModel; /** * @dev Core control of the contract. */ IControllerInterface public controller; /** * @dev Initial exchange rate(scaled by 1e18). */ uint256 constant initialExchangeRate = 1e18; /** * @dev The interest index for borrows of asset as of blockNumber. */ uint256 public borrowIndex; /** * @dev Block number that interest was last accrued at. */ uint256 public accrualBlockNumber; /** * @dev Total amount of this reserve borrowed. */ uint256 public totalBorrows; /** * @dev Total amount of this reserves accrued. */ uint256 public totalReserves; /** * @dev Container for user balance information written to storage. * @param principal User total balance with accrued interest after applying the user's most recent balance-changing action. * @param interestIndex The total interestIndex as calculated after applying the user's most recent balance-changing action. */ struct BorrowSnapshot { uint256 principal; uint256 interestIndex; } /** * @dev 2-level map: userAddress -> assetAddress -> balance for borrows. */ mapping(address => BorrowSnapshot) internal accountBorrows; bytes32 public DOMAIN_SEPARATOR; // keccak256("Permit(address owner,address spender,uint256 chainId, uint256 value,uint256 nonce,uint256 deadline)"); bytes32 public constant PERMIT_TYPEHASH = 0x576144ed657c8304561e56ca632e17751956250114636e8c01f64a7f2c6d98cf; mapping(address => uint256) public nonces; } // File contracts/TokenBase/TokenEvent.sol pragma solidity 0.6.12; /** * @title dForce's lending Token event Contract * @author dForce */ contract TokenEvent is TokenStorage { //---------------------------------- //********** User Events *********** //---------------------------------- event UpdateInterest( uint256 currentBlockNumber, uint256 interestAccumulated, uint256 borrowIndex, uint256 cash, uint256 totalBorrows, uint256 totalReserves ); event Mint( address spender, address recipient, uint256 mintAmount, uint256 mintTokens ); event Redeem( address from, address recipient, uint256 redeemiTokenAmount, uint256 redeemUnderlyingAmount ); /** * @dev Emits when underlying is borrowed. */ event Borrow( address borrower, uint256 borrowAmount, uint256 accountBorrows, uint256 accountInterestIndex, uint256 totalBorrows ); event RepayBorrow( address payer, address borrower, uint256 repayAmount, uint256 accountBorrows, uint256 accountInterestIndex, uint256 totalBorrows ); event LiquidateBorrow( address liquidator, address borrower, uint256 repayAmount, address iTokenCollateral, uint256 seizeTokens ); event Flashloan( address loaner, uint256 loanAmount, uint256 flashloanFee, uint256 protocolFee, uint256 timestamp ); //---------------------------------- //********** Owner Events ********** //---------------------------------- event NewReserveRatio(uint256 oldReserveRatio, uint256 newReserveRatio); event NewFlashloanFeeRatio( uint256 oldFlashloanFeeRatio, uint256 newFlashloanFeeRatio ); event NewProtocolFeeRatio( uint256 oldProtocolFeeRatio, uint256 newProtocolFeeRatio ); event NewFlashloanFee( uint256 oldFlashloanFeeRatio, uint256 newFlashloanFeeRatio, uint256 oldProtocolFeeRatio, uint256 newProtocolFeeRatio ); event NewInterestRateModel( IInterestRateModelInterface oldInterestRateModel, IInterestRateModelInterface newInterestRateModel ); event NewController( IControllerInterface oldController, IControllerInterface newController ); event ReservesWithdrawn( address admin, uint256 amount, uint256 newTotalReserves, uint256 oldTotalReserves ); } // File contracts/TokenBase/TokenAdmin.sol pragma solidity 0.6.12; /** * @title dForce's lending Token admin Contract * @author dForce */ abstract contract TokenAdmin is TokenEvent { //---------------------------------- //********* Owner Actions ********** //---------------------------------- modifier settleInterest() { // Accrues interest. _updateInterest(); require( accrualBlockNumber == block.number, "settleInterest: Fail to accrue interest!" ); _; } /** * @dev Sets a new controller. */ function _setController(IControllerInterface _newController) external virtual onlyOwner { IControllerInterface _oldController = controller; // Ensures the input address is a controller contract. require( _newController.isController(), "_setController: This is not the controller contract!" ); // Sets to new controller. controller = _newController; emit NewController(_oldController, _newController); } /** * @dev Sets a new interest rate model. * @param _newInterestRateModel The new interest rate model. */ function _setInterestRateModel( IInterestRateModelInterface _newInterestRateModel ) external virtual onlyOwner { // Gets current interest rate model. IInterestRateModelInterface _oldInterestRateModel = interestRateModel; // Ensures the input address is the interest model contract. require( _newInterestRateModel.isInterestRateModel(), "_setInterestRateModel: This is not the rate model contract!" ); // Set to the new interest rate model. interestRateModel = _newInterestRateModel; emit NewInterestRateModel(_oldInterestRateModel, _newInterestRateModel); } /** * @dev Sets a new reserve ratio. */ function _setNewReserveRatio(uint256 _newReserveRatio) external virtual onlyOwner settleInterest { require( _newReserveRatio <= maxReserveRatio, "_setNewReserveRatio: New reserve ratio too large!" ); // Gets current reserve ratio. uint256 _oldReserveRatio = reserveRatio; // Sets new reserve ratio. reserveRatio = _newReserveRatio; emit NewReserveRatio(_oldReserveRatio, _newReserveRatio); } /** * @dev Sets a new flashloan fee ratio. */ function _setNewFlashloanFeeRatio(uint256 _newFlashloanFeeRatio) external virtual onlyOwner settleInterest { require( _newFlashloanFeeRatio <= BASE, "setNewFlashloanFeeRatio: New flashloan ratio too large!" ); // Gets current reserve ratio. uint256 _oldFlashloanFeeRatio = flashloanFeeRatio; // Sets new reserve ratio. flashloanFeeRatio = _newFlashloanFeeRatio; emit NewFlashloanFeeRatio(_oldFlashloanFeeRatio, _newFlashloanFeeRatio); } /** * @dev Sets a new protocol fee ratio. */ function _setNewProtocolFeeRatio(uint256 _newProtocolFeeRatio) external virtual onlyOwner settleInterest // nonReentrant { require( _newProtocolFeeRatio <= BASE, "_setNewProtocolFeeRatio: New protocol ratio too large!" ); // Gets current reserve ratio. uint256 _oldProtocolFeeRatio = protocolFeeRatio; // Sets new reserve ratio. protocolFeeRatio = _newProtocolFeeRatio; emit NewProtocolFeeRatio(_oldProtocolFeeRatio, _newProtocolFeeRatio); } /** * @dev Admin withdraws `_withdrawAmount` of the iToken. * @param _withdrawAmount Amount of reserves to withdraw. */ function _withdrawReserves(uint256 _withdrawAmount) external virtual onlyOwner settleInterest // nonReentrant { require( _withdrawAmount <= totalReserves && _withdrawAmount <= _getCurrentCash(), "_withdrawReserves: Invalid withdraw amount and do not have enough cash!" ); uint256 _oldTotalReserves = totalReserves; // Updates total amount of the reserves. totalReserves = totalReserves.sub(_withdrawAmount); // Transfers reserve to the owner. _doTransferOut(owner, _withdrawAmount); emit ReservesWithdrawn( owner, _withdrawAmount, totalReserves, _oldTotalReserves ); } /** * @notice Calculates interest and update total borrows and reserves. * @dev Updates total borrows and reserves with any accumulated interest. */ function _updateInterest() internal virtual; /** * @dev Transfers underlying token out. */ function _doTransferOut(address payable _recipient, uint256 _amount) internal virtual; /** * @dev Total amount of reserves owned by this contract. */ function _getCurrentCash() internal view virtual returns (uint256); } // File contracts/TokenBase/TokenERC20.sol pragma solidity 0.6.12; /** * @title dForce's lending Token ERC20 Contract * @author dForce */ abstract contract TokenERC20 is TokenAdmin { /** * @dev Transfers `_amount` tokens from `_spender` to `_recipient`. * @param _spender The address of the source account. * @param _recipient The address of the destination account. * @param _amount The number of tokens to transfer. */ function _transferTokens( address _spender, address _recipient, uint256 _amount ) internal returns (bool) { require( _spender != _recipient, "_transferTokens: Do not self-transfer!" ); controller.beforeTransfer( address(this), msg.sender, _recipient, _amount ); _transfer(_spender, _recipient, _amount); controller.afterTransfer(address(this), _spender, _recipient, _amount); return true; } //---------------------------------- //********* ERC20 Actions ********** //---------------------------------- /** * @notice Cause iToken is an ERC20 token, so users can `transfer` them, * but this action is only allowed when after transferring tokens, the caller * does not have a shortfall. * @dev Moves `_amount` tokens from caller to `_recipient`. * @param _recipient The address of the destination account. * @param _amount The number of tokens to transfer. */ function transfer(address _recipient, uint256 _amount) public virtual override nonReentrant returns (bool) { return _transferTokens(msg.sender, _recipient, _amount); } /** * @notice Cause iToken is an ERC20 token, so users can `transferFrom` them, * but this action is only allowed when after transferring tokens, the `_spender` * does not have a shortfall. * @dev Moves `_amount` tokens from `_spender` to `_recipient`. * @param _spender The address of the source account. * @param _recipient The address of the destination account. * @param _amount The number of tokens to transfer. */ function transferFrom( address _spender, address _recipient, uint256 _amount ) public virtual override nonReentrant returns (bool) { _approve( _spender, msg.sender, allowance[_spender][msg.sender].sub(_amount) ); return _transferTokens(_spender, _recipient, _amount); } } // File contracts/TokenBase/Base.sol pragma solidity 0.6.12; /** * @title dForce's lending Base Contract * @author dForce */ abstract contract Base is TokenERC20 { using SafeRatioMath for uint256; /** * @notice Expects to call only once to create a new lending market. * @param _name Token name. * @param _symbol Token symbol. * @param _controller Core controller contract address. * @param _interestRateModel Token interest rate model contract address. */ function _initialize( string memory _name, string memory _symbol, uint8 _decimals, IControllerInterface _controller, IInterestRateModelInterface _interestRateModel ) internal virtual { controller = _controller; interestRateModel = _interestRateModel; accrualBlockNumber = block.number; borrowIndex = BASE; flashloanFeeRatio = 0.0008e18; protocolFeeRatio = 0.25e18; __Ownable_init(); __ERC20_init(_name, _symbol, _decimals); __ReentrancyGuard_init(); DOMAIN_SEPARATOR = keccak256( abi.encode( keccak256( "EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)" ), keccak256(bytes(_name)), keccak256(bytes("1")), _getChainId(), address(this) ) ); } /*********************************/ /******** Security Check *********/ /*********************************/ /** * @notice Check whether is a iToken contract, return false for iMSD contract. */ function isiToken() external pure virtual returns (bool) { return true; } //---------------------------------- //******** Main calculation ******** //---------------------------------- struct InterestLocalVars { uint256 borrowRate; uint256 currentBlockNumber; uint256 currentCash; uint256 totalBorrows; uint256 totalReserves; uint256 borrowIndex; uint256 blockDelta; uint256 simpleInterestFactor; uint256 interestAccumulated; uint256 newTotalBorrows; uint256 newTotalReserves; uint256 newBorrowIndex; } /** * @notice Calculates interest and update total borrows and reserves. * @dev Updates total borrows and reserves with any accumulated interest. */ function _updateInterest() internal virtual override { // When more calls in the same block, only the first one takes effect, so for the // following calls, nothing updates. if (block.number != accrualBlockNumber) { InterestLocalVars memory _vars; _vars.currentCash = _getCurrentCash(); _vars.totalBorrows = totalBorrows; _vars.totalReserves = totalReserves; // Gets the current borrow interest rate. _vars.borrowRate = interestRateModel.getBorrowRate( _vars.currentCash, _vars.totalBorrows, _vars.totalReserves ); require( _vars.borrowRate <= maxBorrowRate, "_updateInterest: Borrow rate is too high!" ); // Records the current block number. _vars.currentBlockNumber = block.number; // Calculates the number of blocks elapsed since the last accrual. _vars.blockDelta = _vars.currentBlockNumber.sub(accrualBlockNumber); /** * Calculates the interest accumulated into borrows and reserves and the new index: * simpleInterestFactor = borrowRate * blockDelta * interestAccumulated = simpleInterestFactor * totalBorrows * newTotalBorrows = interestAccumulated + totalBorrows * newTotalReserves = interestAccumulated * reserveFactor + totalReserves * newBorrowIndex = simpleInterestFactor * borrowIndex + borrowIndex */ _vars.simpleInterestFactor = _vars.borrowRate.mul(_vars.blockDelta); _vars.interestAccumulated = _vars.simpleInterestFactor.rmul( _vars.totalBorrows ); _vars.newTotalBorrows = _vars.interestAccumulated.add( _vars.totalBorrows ); _vars.newTotalReserves = reserveRatio .rmul(_vars.interestAccumulated) .add(_vars.totalReserves); _vars.borrowIndex = borrowIndex; _vars.newBorrowIndex = _vars .simpleInterestFactor .rmul(_vars.borrowIndex) .add(_vars.borrowIndex); // Writes the previously calculated values into storage. accrualBlockNumber = _vars.currentBlockNumber; borrowIndex = _vars.newBorrowIndex; totalBorrows = _vars.newTotalBorrows; totalReserves = _vars.newTotalReserves; // Emits an `UpdateInterest` event. emit UpdateInterest( _vars.currentBlockNumber, _vars.interestAccumulated, _vars.newBorrowIndex, _vars.currentCash, _vars.newTotalBorrows, _vars.newTotalReserves ); } } struct MintLocalVars { uint256 exchangeRate; uint256 mintTokens; uint256 actualMintAmout; } /** * @dev User deposits token into the market and `_recipient` gets iToken. * @param _recipient The address of the user to get iToken. * @param _mintAmount The amount of the underlying token to deposit. */ function _mintInternal(address _recipient, uint256 _mintAmount) internal virtual { controller.beforeMint(address(this), _recipient, _mintAmount); MintLocalVars memory _vars; /** * Gets the current exchange rate and calculate the number of iToken to be minted: * mintTokens = mintAmount / exchangeRate */ _vars.exchangeRate = _exchangeRateInternal(); // Transfers `_mintAmount` from caller to contract, and returns the actual amount the contract // get, cause some tokens may be charged. _vars.actualMintAmout = _doTransferIn(msg.sender, _mintAmount); // Supports deflationary tokens. _vars.mintTokens = _vars.actualMintAmout.rdiv(_vars.exchangeRate); // Mints `mintTokens` iToken to `_recipient`. _mint(_recipient, _vars.mintTokens); controller.afterMint( address(this), _recipient, _mintAmount, _vars.mintTokens ); emit Mint(msg.sender, _recipient, _mintAmount, _vars.mintTokens); } /** * @notice This is a common function to redeem, so only one of `_redeemiTokenAmount` or * `_redeemUnderlyingAmount` may be non-zero. * @dev Caller redeems undelying token based on the input amount of iToken or underlying token. * @param _from The address of the account which will spend underlying token. * @param _redeemiTokenAmount The number of iTokens to redeem into underlying. * @param _redeemUnderlyingAmount The number of underlying tokens to receive. */ function _redeemInternal( address _from, uint256 _redeemiTokenAmount, uint256 _redeemUnderlyingAmount ) internal virtual { require( _redeemiTokenAmount > 0, "_redeemInternal: Redeem iToken amount should be greater than zero!" ); controller.beforeRedeem(address(this), _from, _redeemiTokenAmount); _burnFrom(_from, _redeemiTokenAmount); /** * Transfers `_redeemUnderlyingAmount` underlying token to caller. */ _doTransferOut(msg.sender, _redeemUnderlyingAmount); controller.afterRedeem( address(this), _from, _redeemiTokenAmount, _redeemUnderlyingAmount ); emit Redeem( _from, msg.sender, _redeemiTokenAmount, _redeemUnderlyingAmount ); } /** * @dev Caller borrows assets from the protocol. * @param _borrower The account that will borrow tokens. * @param _borrowAmount The amount of the underlying asset to borrow. */ function _borrowInternal(address payable _borrower, uint256 _borrowAmount) internal virtual { controller.beforeBorrow(address(this), _borrower, _borrowAmount); // Calculates the new borrower and total borrow balances: // newAccountBorrows = accountBorrows + borrowAmount // newTotalBorrows = totalBorrows + borrowAmount BorrowSnapshot storage borrowSnapshot = accountBorrows[_borrower]; borrowSnapshot.principal = _borrowBalanceInternal(_borrower).add( _borrowAmount ); borrowSnapshot.interestIndex = borrowIndex; totalBorrows = totalBorrows.add(_borrowAmount); // Transfers token to borrower. _doTransferOut(_borrower, _borrowAmount); controller.afterBorrow(address(this), _borrower, _borrowAmount); emit Borrow( _borrower, _borrowAmount, borrowSnapshot.principal, borrowSnapshot.interestIndex, totalBorrows ); } /** * @notice Please approve enough amount at first!!! If not, * maybe you will get an error: `SafeMath: subtraction overflow` * @dev `_payer` repays `_repayAmount` tokens for `_borrower`. * @param _payer The account to pay for the borrowed. * @param _borrower The account with the debt being payed off. * @param _repayAmount The amount to repay (or -1 for max). */ function _repayInternal( address _payer, address _borrower, uint256 _repayAmount ) internal virtual returns (uint256) { controller.beforeRepayBorrow( address(this), _payer, _borrower, _repayAmount ); // Calculates the latest borrowed amount by the new market borrowed index. uint256 _accountBorrows = _borrowBalanceInternal(_borrower); // Transfers the token into the market to repay. uint256 _actualRepayAmount = _doTransferIn( _payer, _repayAmount > _accountBorrows ? _accountBorrows : _repayAmount ); // Calculates the `_borrower` new borrow balance and total borrow balances: // accountBorrows[_borrower].principal = accountBorrows - actualRepayAmount // newTotalBorrows = totalBorrows - actualRepayAmount // Saves borrower updates. BorrowSnapshot storage borrowSnapshot = accountBorrows[_borrower]; borrowSnapshot.principal = _accountBorrows.sub(_actualRepayAmount); borrowSnapshot.interestIndex = borrowIndex; totalBorrows = totalBorrows < _actualRepayAmount ? 0 : totalBorrows.sub(_actualRepayAmount); // Defense hook. controller.afterRepayBorrow( address(this), _payer, _borrower, _actualRepayAmount ); emit RepayBorrow( _payer, _borrower, _actualRepayAmount, borrowSnapshot.principal, borrowSnapshot.interestIndex, totalBorrows ); return _actualRepayAmount; } /** * @dev The caller repays some of borrow and receive collateral. * @param _borrower The account whose borrow should be liquidated. * @param _repayAmount The amount to repay. * @param _assetCollateral The market in which to seize collateral from the borrower. */ function _liquidateBorrowInternal( address _borrower, uint256 _repayAmount, address _assetCollateral ) internal virtual { require( msg.sender != _borrower, "_liquidateBorrowInternal: Liquidator can not be borrower!" ); // According to the parameter `_repayAmount` to see what is the exact error. require( _repayAmount != 0, "_liquidateBorrowInternal: Liquidate amount should be greater than 0!" ); // Accrues interest for collateral asset. Base _dlCollateral = Base(_assetCollateral); _dlCollateral.updateInterest(); controller.beforeLiquidateBorrow( address(this), _assetCollateral, msg.sender, _borrower, _repayAmount ); require( _dlCollateral.accrualBlockNumber() == block.number, "_liquidateBorrowInternal: Failed to update block number in collateral asset!" ); uint256 _actualRepayAmount = _repayInternal(msg.sender, _borrower, _repayAmount); // Calculates the number of collateral tokens that will be seized uint256 _seizeTokens = controller.liquidateCalculateSeizeTokens( address(this), _assetCollateral, _actualRepayAmount ); // If this is also the collateral, calls seizeInternal to avoid re-entrancy, // otherwise make an external call. if (_assetCollateral == address(this)) { _seizeInternal(address(this), msg.sender, _borrower, _seizeTokens); } else { _dlCollateral.seize(msg.sender, _borrower, _seizeTokens); } controller.afterLiquidateBorrow( address(this), _assetCollateral, msg.sender, _borrower, _actualRepayAmount, _seizeTokens ); emit LiquidateBorrow( msg.sender, _borrower, _actualRepayAmount, _assetCollateral, _seizeTokens ); } /** * @dev Transfers this token to the liquidator. * @param _seizerToken The contract seizing the collateral. * @param _liquidator The account receiving seized collateral. * @param _borrower The account having collateral seized. * @param _seizeTokens The number of iTokens to seize. */ function _seizeInternal( address _seizerToken, address _liquidator, address _borrower, uint256 _seizeTokens ) internal virtual { require( _borrower != _liquidator, "seize: Liquidator can not be borrower!" ); controller.beforeSeize( address(this), _seizerToken, _liquidator, _borrower, _seizeTokens ); /** * Calculates the new _borrower and _liquidator token balances, * that is transfer `_seizeTokens` iToken from `_borrower` to `_liquidator`. */ _transfer(_borrower, _liquidator, _seizeTokens); // Hook checks. controller.afterSeize( address(this), _seizerToken, _liquidator, _borrower, _seizeTokens ); } /** * @param _account The address whose balance should be calculated. */ function _borrowBalanceInternal(address _account) internal view virtual returns (uint256) { // Gets stored borrowed data of the `_account`. BorrowSnapshot storage borrowSnapshot = accountBorrows[_account]; // If borrowBalance = 0, return 0 directly. if (borrowSnapshot.principal == 0 || borrowSnapshot.interestIndex == 0) return 0; // Calculate new borrow balance with market new borrow index: // recentBorrowBalance = borrower.borrowBalance * market.borrowIndex / borrower.borrowIndex return borrowSnapshot.principal.mul(borrowIndex).divup( borrowSnapshot.interestIndex ); } /** * @dev Calculates the exchange rate from the underlying token to the iToken. */ function _exchangeRateInternal() internal view virtual returns (uint256) { if (totalSupply == 0) { // This is the first time to mint, so current exchange rate is equal to initial exchange rate. return initialExchangeRate; } else { // exchangeRate = (totalCash + totalBorrows - totalReserves) / totalSupply return _getCurrentCash().add(totalBorrows).sub(totalReserves).rdiv( totalSupply ); } } function updateInterest() external virtual returns (bool); /** * @dev EIP2612 permit function. For more details, please look at here: * https://eips.ethereum.org/EIPS/eip-2612 * @param _owner The owner of the funds. * @param _spender The spender. * @param _value The amount. * @param _deadline The deadline timestamp, type(uint256).max for max deadline. * @param _v Signature param. * @param _s Signature param. * @param _r Signature param. */ function permit( address _owner, address _spender, uint256 _value, uint256 _deadline, uint8 _v, bytes32 _r, bytes32 _s ) external { require(_deadline >= block.timestamp, "permit: EXPIRED!"); uint256 _currentNonce = nonces[_owner]; bytes32 _digest = keccak256( abi.encodePacked( "\x19\x01", DOMAIN_SEPARATOR, keccak256( abi.encode( PERMIT_TYPEHASH, _owner, _spender, _getChainId(), _value, _currentNonce, _deadline ) ) ) ); address _recoveredAddress = ecrecover(_digest, _v, _r, _s); require( _recoveredAddress != address(0) && _recoveredAddress == _owner, "permit: INVALID_SIGNATURE!" ); nonces[_owner] = _currentNonce.add(1); _approve(_owner, _spender, _value); } function _getChainId() internal pure returns (uint256) { uint256 chainId; assembly { chainId := chainid() } return chainId; } /** * @dev Transfers this tokens to the liquidator. * @param _liquidator The account receiving seized collateral. * @param _borrower The account having collateral seized. * @param _seizeTokens The number of iTokens to seize. */ function seize( address _liquidator, address _borrower, uint256 _seizeTokens ) external virtual; /** * @notice Users are expected to have enough allowance and balance before calling. * @dev Transfers asset in. */ function _doTransferIn(address _spender, uint256 _amount) internal virtual returns (uint256); function exchangeRateStored() external view virtual returns (uint256); function borrowBalanceStored(address _account) external view virtual returns (uint256); } // File @openzeppelin/contracts-upgradeable/utils/[email protected] 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(value))); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(AddressSet storage set, address value) internal returns (bool) { return _remove(set._inner, bytes32(uint256(value))); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(AddressSet storage set, address value) internal view returns (bool) { return _contains(set._inner, bytes32(uint256(value))); } /** * @dev Returns the number of values in the set. O(1). */ function length(AddressSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(AddressSet storage set, uint256 index) internal view returns (address) { return address(uint256(_at(set._inner, index))); } // UintSet struct UintSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(UintSet storage set, uint256 value) internal returns (bool) { return _add(set._inner, bytes32(value)); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(UintSet storage set, uint256 value) internal returns (bool) { return _remove(set._inner, bytes32(value)); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(UintSet storage set, uint256 value) internal view returns (bool) { return _contains(set._inner, bytes32(value)); } /** * @dev Returns the number of values on the set. O(1). */ function length(UintSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(UintSet storage set, uint256 index) internal view returns (uint256) { return uint256(_at(set._inner, index)); } } // File contracts/msd/MSD.sol pragma solidity 0.6.12; /** * @title dForce's Multi-currency Stable Debt Token * @author dForce */ contract MSD is Initializable, Ownable, ERC20 { using EnumerableSetUpgradeable for EnumerableSetUpgradeable.AddressSet; bytes32 public DOMAIN_SEPARATOR; // keccak256("Permit(address owner,address spender,uint256 chainId, uint256 value,uint256 nonce,uint256 deadline)"); bytes32 public constant PERMIT_TYPEHASH = 0x576144ed657c8304561e56ca632e17751956250114636e8c01f64a7f2c6d98cf; mapping(address => uint256) public nonces; /// @dev EnumerableSet of minters EnumerableSetUpgradeable.AddressSet internal minters; /** * @dev Emitted when `minter` is added as `minter`. */ event MinterAdded(address minter); /** * @dev Emitted when `minter` is removed from `minters`. */ event MinterRemoved(address minter); /** * @notice Expects to call only once to initialize the MSD token. * @param _name Token name. * @param _symbol Token symbol. */ function initialize( string memory _name, string memory _symbol, uint8 _decimals ) external initializer { __Ownable_init(); __ERC20_init(_name, _symbol, _decimals); DOMAIN_SEPARATOR = keccak256( abi.encode( keccak256( "EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)" ), keccak256(bytes(_name)), keccak256(bytes("1")), _getChainId(), address(this) ) ); } /** * @dev Throws if called by any account other than the minters. */ modifier onlyMinter() { require( minters.contains(msg.sender), "onlyMinter: caller is not minter" ); _; } /** * @notice Add `minter` into minters. * If `minter` have not been a minter, emits a `MinterAdded` event. * * @param _minter The minter to add * * Requirements: * - the caller must be `owner`. */ function _addMinter(address _minter) external onlyOwner { require(_minter != address(0), "_addMinter: _minter the zero address"); if (minters.add(_minter)) { emit MinterAdded(_minter); } } /** * @notice Remove `minter` from minters. * If `minter` is a minter, emits a `MinterRemoved` event. * * @param _minter The minter to remove * * Requirements: * - the caller must be `owner`. */ function _removeMinter(address _minter) external onlyOwner { require( _minter != address(0), "_removeMinter: _minter the zero address" ); if (minters.remove(_minter)) { emit MinterRemoved(_minter); } } function mint(address to, uint256 amount) external onlyMinter { _mint(to, amount); } function burn(address from, uint256 amount) external { _burnFrom(from, amount); } function _getChainId() internal pure returns (uint256) { uint256 chainId; assembly { chainId := chainid() } return chainId; } /** * @dev EIP2612 permit function. For more details, please look at here: * https://eips.ethereum.org/EIPS/eip-2612 * @param _owner The owner of the funds. * @param _spender The spender. * @param _value The amount. * @param _deadline The deadline timestamp, type(uint256).max for max deadline. * @param _v Signature param. * @param _s Signature param. * @param _r Signature param. */ function permit( address _owner, address _spender, uint256 _value, uint256 _deadline, uint8 _v, bytes32 _r, bytes32 _s ) external { require(_deadline >= block.timestamp, "permit: EXPIRED!"); uint256 _currentNonce = nonces[_owner]; bytes32 _digest = keccak256( abi.encodePacked( "\x19\x01", DOMAIN_SEPARATOR, keccak256( abi.encode( PERMIT_TYPEHASH, _owner, _spender, _getChainId(), _value, _currentNonce, _deadline ) ) ) ); address _recoveredAddress = ecrecover(_digest, _v, _r, _s); require( _recoveredAddress != address(0) && _recoveredAddress == _owner, "permit: INVALID_SIGNATURE!" ); nonces[_owner] = _currentNonce.add(1); _approve(_owner, _spender, _value); } /** * @notice Return all minters of this MSD token * @return _minters The list of minter addresses */ function getMinters() public view returns (address[] memory _minters) { uint256 _len = minters.length(); _minters = new address[](_len); for (uint256 i = 0; i < _len; i++) { _minters[i] = minters.at(i); } } } // File contracts/msd/MSDController.sol pragma solidity 0.6.12; /** * @dev Interface for Minters, minters now can be iMSD and MSDS */ interface IMinter { function updateInterest() external returns (bool); } /** * @title dForce's Multi-currency Stable Debt Token Controller * @author dForce */ contract MSDController is Initializable, Ownable { using SafeMathUpgradeable for uint256; using EnumerableSetUpgradeable for EnumerableSetUpgradeable.AddressSet; /// @dev EnumerableSet of all msdTokens EnumerableSetUpgradeable.AddressSet internal msdTokens; // @notice Mapping of msd tokens to corresponding minters mapping(address => EnumerableSetUpgradeable.AddressSet) internal msdMinters; struct TokenData { // System earning from borrow interest uint256 earning; // System debt from saving interest uint256 debt; } // @notice Mapping of msd tokens to corresponding TokenData mapping(address => TokenData) public msdTokenData; /** * @dev Emitted when `token` is added into msdTokens. */ event MSDAdded(address token); /** * @dev Emitted when `minter` is added into `tokens`'s minters. */ event MinterAdded(address token, address minter); /** * @dev Emitted when `minter` is removed from `tokens`'s minters. */ event MinterRemoved(address token, address minter); /** * @dev Emitted when reserve is withdrawn from `token`. */ event ReservesWithdrawn( address owner, address token, uint256 amount, uint256 oldTotalReserves, uint256 newTotalReserves ); /** * @notice Expects to call only once to initialize the MSD controller. */ function initialize() external initializer { __Ownable_init(); } /** * @notice Ensure this is a MSD Controller contract. */ function isMSDController() external pure returns (bool) { return true; } /** * @dev Throws if token is not in msdTokens */ function _checkMSD(address _token) internal view { require(hasMSD(_token), "token is not a valid MSD token"); } /** * @dev Throws if token is not a valid MSD token. */ modifier onlyMSD(address _token) { _checkMSD(_token); _; } /** * @dev Throws if called by any account other than the _token's minters. */ modifier onlyMSDMinter(address _token, address caller) { _checkMSD(_token); require( msdMinters[_token].contains(caller), "onlyMinter: caller is not the token's minter" ); _; } /** * @notice Add `_token` into msdTokens. * If `_token` have not been in msdTokens, emits a `MSDTokenAdded` event. * * @param _token The token to add * @param _minters The addresses to add as token's minters * * Requirements: * - the caller must be `owner`. */ function _addMSD(address _token, address[] calldata _minters) external onlyOwner { require(_token != address(0), "MSD token cannot be a zero address"); if (msdTokens.add(_token)) { emit MSDAdded(_token); } _addMinters(_token, _minters); } /** * @notice Add `_minters` into minters. * If `_minters` have not been in minters, emits a `MinterAdded` event. * * @param _minters The addresses to add as minters * * Requirements: * - the caller must be `owner`. */ function _addMinters(address _token, address[] memory _minters) public onlyOwner onlyMSD(_token) { uint256 _len = _minters.length; for (uint256 i = 0; i < _len; i++) { require( _minters[i] != address(0), "minter cannot be a zero address" ); if (msdMinters[_token].add(_minters[i])) { emit MinterAdded(_token, _minters[i]); } } } /** * @notice Remove `minter` from minters. * If `minter` is a minter, emits a `MinterRemoved` event. * * @param _minter The minter to remove * * Requirements: * - the caller must be `owner`, `_token` must be a MSD Token. */ function _removeMinter(address _token, address _minter) external onlyOwner onlyMSD(_token) { require(_minter != address(0), "_minter cannot be a zero address"); if (msdMinters[_token].remove(_minter)) { emit MinterRemoved(_token, _minter); } } /** * @notice Withdraw the reserve of `_token`. * @param _token The MSD token to withdraw * @param _amount The amount of token to withdraw * * Requirements: * - the caller must be `owner`, `_token` must be a MSD Token. */ function _withdrawReserves(address _token, uint256 _amount) external onlyOwner onlyMSD(_token) { (uint256 _equity, ) = calcEquity(_token); require(_equity >= _amount, "Token do not have enough reserve"); // Increase the token debt msdTokenData[_token].debt = msdTokenData[_token].debt.add(_amount); // Directly mint the token to owner MSD(_token).mint(owner, _amount); emit ReservesWithdrawn( owner, _token, _amount, _equity, _equity.sub(_amount) ); } /** * @notice Mint `amount` of `_token` to `_to`. * @param _token The MSD token to mint * @param _to The account to mint to * @param _amount The amount of token to mint * * Requirements: * - the caller must be `minter` of `_token`. */ function mintMSD( address _token, address _to, uint256 _amount ) external onlyMSDMinter(_token, msg.sender) { MSD(_token).mint(_to, _amount); } /*********************************/ /******** MSD Token Equity *******/ /*********************************/ /** * @notice Add `amount` of debt to `_token`. * @param _token The MSD token to add debt * @param _debt The amount of debt to add * * Requirements: * - the caller must be `minter` of `_token`. */ function addDebt(address _token, uint256 _debt) external onlyMSDMinter(_token, msg.sender) { msdTokenData[_token].debt = msdTokenData[_token].debt.add(_debt); } /** * @notice Add `amount` of earning to `_token`. * @param _token The MSD token to add earning * @param _earning The amount of earning to add * * Requirements: * - the caller must be `minter` of `_token`. */ function addEarning(address _token, uint256 _earning) external onlyMSDMinter(_token, msg.sender) { msdTokenData[_token].earning = msdTokenData[_token].earning.add( _earning ); } /** * @notice Get the MSD token equity * @param _token The MSD token to query * @return token equity, token debt, will call `updateInterest()` on its minters * * Requirements: * - `_token` must be a MSD Token. * */ function calcEquity(address _token) public onlyMSD(_token) returns (uint256, uint256) { // Call `updateInterest()` on all minters to get the latest token data EnumerableSetUpgradeable.AddressSet storage _msdMinters = msdMinters[_token]; uint256 _len = _msdMinters.length(); for (uint256 i = 0; i < _len; i++) { IMinter(_msdMinters.at(i)).updateInterest(); } TokenData storage _tokenData = msdTokenData[_token]; return _tokenData.earning > _tokenData.debt ? (_tokenData.earning.sub(_tokenData.debt), uint256(0)) : (uint256(0), _tokenData.debt.sub(_tokenData.earning)); } /*********************************/ /****** General Information ******/ /*********************************/ /** * @notice Return all of the MSD tokens * @return _allMSDs The list of MSD token addresses */ function getAllMSDs() public view returns (address[] memory _allMSDs) { EnumerableSetUpgradeable.AddressSet storage _msdTokens = msdTokens; uint256 _len = _msdTokens.length(); _allMSDs = new address[](_len); for (uint256 i = 0; i < _len; i++) { _allMSDs[i] = _msdTokens.at(i); } } /** * @notice Check whether a address is a valid MSD * @param _token The token address to check for * @return true if the _token is a valid MSD otherwise false */ function hasMSD(address _token) public view returns (bool) { return msdTokens.contains(_token); } /** * @notice Return all minter of a MSD token * @param _token The MSD token address to get minters for * @return _minters The list of MSD token minter addresses * Will retuen empty if `_token` is not a valid MSD token */ function getMSDMinters(address _token) public view returns (address[] memory _minters) { EnumerableSetUpgradeable.AddressSet storage _msdMinters = msdMinters[_token]; uint256 _len = _msdMinters.length(); _minters = new address[](_len); for (uint256 i = 0; i < _len; i++) { _minters[i] = _msdMinters.at(i); } } } // File contracts/msd/iMSD.sol pragma solidity 0.6.12; /** * @title dForce's Lending Protocol Contract. * @notice dForce lending token for the Multi-currency Stable Debt Token. * @author dForce Team. */ contract iMSD is Base { MSDController public msdController; event NewMSDController( MSDController oldMSDController, MSDController newMSDController ); /** * @notice Expects to call only once to initialize a new market. * @param _underlyingToken The underlying token address. * @param _name Token name. * @param _symbol Token symbol. * @param _lendingController Lending controller contract address. * @param _interestRateModel Token interest rate model contract address. * @param _msdController MSD controller contract address. */ function initialize( address _underlyingToken, string memory _name, string memory _symbol, IControllerInterface _lendingController, IInterestRateModelInterface _interestRateModel, MSDController _msdController ) external initializer { require( address(_underlyingToken) != address(0), "initialize: underlying address should not be zero address!" ); require( address(_lendingController) != address(0), "initialize: controller address should not be zero address!" ); require( address(_msdController) != address(0), "initialize: MSD controller address should not be zero address!" ); require( address(_interestRateModel) != address(0), "initialize: interest model address should not be zero address!" ); _initialize( _name, _symbol, ERC20(_underlyingToken).decimals(), _lendingController, _interestRateModel ); underlying = IERC20Upgradeable(_underlyingToken); msdController = _msdController; } /** * @dev Sets a new reserve ratio. * iMSD hold no reserve, all borrow interest goes to MSD controller * Therefore, reserveRatio can not be changed */ function _setNewReserveRatio(uint256 _newReserveRatio) external override onlyOwner { _newReserveRatio; revert("Reserve Ratio of iMSD Token can not be changed"); } /** * @dev Sets a new MSD controller. * @param _newMSDController The new MSD controller */ function _setMSDController(MSDController _newMSDController) external onlyOwner { MSDController _oldMSDController = msdController; // Ensures the input address is a MSDController contract. require( _newMSDController.isMSDController(), "_setMSDController: This is not MSD controller contract!" ); msdController = _newMSDController; emit NewMSDController(_oldMSDController, _newMSDController); } /** * @notice Supposed to transfer underlying token into this contract * @dev iMSD burns the amount of underlying rather than transfering. */ function _doTransferIn(address _spender, uint256 _amount) internal override returns (uint256) { MSD(address(underlying)).burn(_spender, _amount); return _amount; } /** * @notice Supposed to transfer underlying token to `_recipient` * @dev iMSD mint the amount of underlying rather than transfering. * this can be called by `borrow()` and `_withdrawReserves()` * Reserves should stay 0 for iMSD */ function _doTransferOut(address payable _recipient, uint256 _amount) internal override { msdController.mintMSD(address(underlying), _recipient, _amount); } /** * @notice Calculates interest and update total borrows and reserves. * @dev Updates total borrows and reserves with any accumulated interest. * With 0 reserveRatio, all interest goes to totalBorrows and notify MSD Controller */ function _updateInterest() internal virtual override { // When more calls in the same block, only the first one takes effect, so for the // following calls, nothing updates. if (block.number != accrualBlockNumber) { uint256 _totalBorrows = totalBorrows; Base._updateInterest(); uint256 _interestAccumulated = totalBorrows.sub(_totalBorrows); // Notify the MSD controller to update earning if (_interestAccumulated > 0) { msdController.addEarning(address(underlying), _interestAccumulated); } } } /** * @dev iMSD does not hold any underlying in cash, returning 0 */ function _getCurrentCash() internal view override returns (uint256) { return 0; } /** * @dev Caller borrows tokens from the protocol to their own address. * @param _borrowAmount The amount of the underlying token to borrow. */ function borrow(uint256 _borrowAmount) external nonReentrant settleInterest { _borrowInternal(msg.sender, _borrowAmount); } /** * @dev Caller repays their own borrow. * @param _repayAmount The amount to repay. */ function repayBorrow(uint256 _repayAmount) external nonReentrant settleInterest { _repayInternal(msg.sender, msg.sender, _repayAmount); } /** * @dev Caller repays a borrow belonging to borrower. * @param _borrower the account with the debt being payed off. * @param _repayAmount The amount to repay. */ function repayBorrowBehalf(address _borrower, uint256 _repayAmount) external nonReentrant settleInterest { _repayInternal(msg.sender, _borrower, _repayAmount); } /** * @dev The caller liquidates the borrowers collateral. * @param _borrower The account whose borrow should be liquidated. * @param _assetCollateral The market in which to seize collateral from the borrower. * @param _repayAmount The amount to repay. */ function liquidateBorrow( address _borrower, uint256 _repayAmount, address _assetCollateral ) external nonReentrant settleInterest { // Liquidate and seize the same token will call _seizeInternal() instead of seize() require( _assetCollateral != address(this), "iMSD Token can not be seized" ); _liquidateBorrowInternal(_borrower, _repayAmount, _assetCollateral); } /** * @dev iMSD does not support seize(), but it is required by liquidateBorrow() * @param _liquidator The account receiving seized collateral. * @param _borrower The account having collateral seized. * @param _seizeTokens The number of iMSDs to seize. */ function seize( address _liquidator, address _borrower, uint256 _seizeTokens ) external override { _liquidator; _borrower; _seizeTokens; revert("iMSD Token can not be seized"); } /** * @notice Calculates interest and update total borrows and reserves. * @dev Updates total borrows and reserves with any accumulated interest. */ function updateInterest() external override returns (bool) { _updateInterest(); return true; } /** * @dev Gets the newest exchange rate by accruing interest. * iMSD returns the initial exchange rate 1.0 */ function exchangeRateCurrent() external pure returns (uint256) { return initialExchangeRate; } /** * @dev Calculates the exchange rate without accruing interest. * iMSD returns the initial exchange rate 1.0 */ function exchangeRateStored() external view override returns (uint256) { return initialExchangeRate; } /** * @dev Gets the underlying balance of the `_account`. * @param _account The address of the account to query. * iMSD just returns 0 */ function balanceOfUnderlying(address _account) external pure returns (uint256) { _account; return 0; } /** * @dev Gets the user's borrow balance with the latest `borrowIndex`. */ function borrowBalanceCurrent(address _account) external nonReentrant returns (uint256) { // Accrues interest. _updateInterest(); return _borrowBalanceInternal(_account); } /** * @dev Gets the borrow balance of user without accruing interest. */ function borrowBalanceStored(address _account) external view override returns (uint256) { return _borrowBalanceInternal(_account); } /** * @dev Gets user borrowing information. */ function borrowSnapshot(address _account) external view returns (uint256, uint256) { return ( accountBorrows[_account].principal, accountBorrows[_account].interestIndex ); } /** * @dev Gets the current total borrows by accruing interest. */ function totalBorrowsCurrent() external returns (uint256) { // Accrues interest. _updateInterest(); return totalBorrows; } /** * @dev Returns the current per-block borrow interest rate. * iMSD uses fixed interest rate model */ function borrowRatePerBlock() public view returns (uint256) { return interestRateModel.getBorrowRate( _getCurrentCash(), totalBorrows, totalReserves ); } /** * @dev Get cash balance of this iToken in the underlying token. */ function getCash() external view returns (uint256) { return _getCurrentCash(); } /** * @notice Check whether is a iToken contract, return false for iMSD contract. */ function isiToken() external pure override returns (bool) { return false; } }
Interface for Minters, minters now can be iMSD and MSDS/
interface IMinter { function updateInterest() external returns (bool); }
13,700,341
./full_match/80001/0xdCdf0B3d68A4E11eF2703b87020dC5a9c66babf7/sources/@superfluid-finance/ethereum-contracts/contracts/apps/SuperTokenV1Library.sol
get the aggregated flow info of the account token Super token address account Account to query return lastUpdated Timestamp of the last change of the net flow return flowRate The net flow rate of token for account return deposit The sum of all deposits for account's flows return owedDeposit The sum of all owed deposits for account's flows/
function getNetFlowInfo(ISuperToken token, address account) internal view returns (uint256 lastUpdated, int96 flowRate, uint256 deposit, uint256 owedDeposit) { (, IConstantFlowAgreementV1 cfa) = _getHostAndCFA(token); return cfa.getAccountFlowInfo(token, account); }
855,975
./full_match/1/0x2923A537546443AdcF47c7351b51Da6E423d3e58/sources/contracts/Marketplace.sol
Instantiates A New Presale Sale/
function __StartPresaleSale(SaleTypePresale memory _Sale, InternalPresaleSaleRoots memory _Roots) external onlyAdmin { PresaleSales[_TOTAL_UNIQUE_PRESALE_SALES] = _Sale; PresaleSalesInternal[_TOTAL_UNIQUE_PRESALE_SALES]._Active = true; InternalRoots[_TOTAL_UNIQUE_PRESALE_SALES] = _Roots; emit SaleStarted(_TOTAL_UNIQUE_PRESALE_SALES); _TOTAL_UNIQUE_PRESALE_SALES++; }
17,089,832
// SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.8.0; pragma abicoder v2; import "../../common/implementation/FixedPoint.sol"; // Simple contract used to withdraw liquidations using a DSProxy from legacy contracts (1.2.2 and below). contract LiquidationWithdrawer { function withdrawLiquidation( address financialContractAddress, uint256 liquidationId, address sponsor ) public returns (FixedPoint.Unsigned memory) { return IFinancialContract(financialContractAddress).withdrawLiquidation(liquidationId, sponsor); } } interface IFinancialContract { function withdrawLiquidation(uint256 liquidationId, address sponsor) external returns (FixedPoint.Unsigned memory amountWithdrawn); } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.8.0; import "@openzeppelin/contracts/utils/math/SafeMath.sol"; import "@openzeppelin/contracts/utils/math/SignedSafeMath.sol"; /** * @title Library for fixed point arithmetic on uints */ library FixedPoint { using SafeMath for uint256; using SignedSafeMath for int256; // Supports 18 decimals. E.g., 1e18 represents "1", 5e17 represents "0.5". // For unsigned values: // This can represent a value up to (2^256 - 1)/10^18 = ~10^59. 10^59 will be stored internally as uint256 10^77. uint256 private constant FP_SCALING_FACTOR = 10**18; // --------------------------------------- UNSIGNED ----------------------------------------------------------------------------- struct Unsigned { uint256 rawValue; } /** * @notice Constructs an `Unsigned` from an unscaled uint, e.g., `b=5` gets stored internally as `5*(10**18)`. * @param a uint to convert into a FixedPoint. * @return the converted FixedPoint. */ function fromUnscaledUint(uint256 a) internal pure returns (Unsigned memory) { return Unsigned(a.mul(FP_SCALING_FACTOR)); } /** * @notice Whether `a` is equal to `b`. * @param a a FixedPoint. * @param b a uint256. * @return True if equal, or False. */ function isEqual(Unsigned memory a, uint256 b) internal pure returns (bool) { return a.rawValue == fromUnscaledUint(b).rawValue; } /** * @notice Whether `a` is equal to `b`. * @param a a FixedPoint. * @param b a FixedPoint. * @return True if equal, or False. */ function isEqual(Unsigned memory a, Unsigned memory b) internal pure returns (bool) { return a.rawValue == b.rawValue; } /** * @notice Whether `a` is greater than `b`. * @param a a FixedPoint. * @param b a FixedPoint. * @return True if `a > b`, or False. */ function isGreaterThan(Unsigned memory a, Unsigned memory b) internal pure returns (bool) { return a.rawValue > b.rawValue; } /** * @notice Whether `a` is greater than `b`. * @param a a FixedPoint. * @param b a uint256. * @return True if `a > b`, or False. */ function isGreaterThan(Unsigned memory a, uint256 b) internal pure returns (bool) { return a.rawValue > fromUnscaledUint(b).rawValue; } /** * @notice Whether `a` is greater than `b`. * @param a a uint256. * @param b a FixedPoint. * @return True if `a > b`, or False. */ function isGreaterThan(uint256 a, Unsigned memory b) internal pure returns (bool) { return fromUnscaledUint(a).rawValue > b.rawValue; } /** * @notice Whether `a` is greater than or equal to `b`. * @param a a FixedPoint. * @param b a FixedPoint. * @return True if `a >= b`, or False. */ function isGreaterThanOrEqual(Unsigned memory a, Unsigned memory b) internal pure returns (bool) { return a.rawValue >= b.rawValue; } /** * @notice Whether `a` is greater than or equal to `b`. * @param a a FixedPoint. * @param b a uint256. * @return True if `a >= b`, or False. */ function isGreaterThanOrEqual(Unsigned memory a, uint256 b) internal pure returns (bool) { return a.rawValue >= fromUnscaledUint(b).rawValue; } /** * @notice Whether `a` is greater than or equal to `b`. * @param a a uint256. * @param b a FixedPoint. * @return True if `a >= b`, or False. */ function isGreaterThanOrEqual(uint256 a, Unsigned memory b) internal pure returns (bool) { return fromUnscaledUint(a).rawValue >= b.rawValue; } /** * @notice Whether `a` is less than `b`. * @param a a FixedPoint. * @param b a FixedPoint. * @return True if `a < b`, or False. */ function isLessThan(Unsigned memory a, Unsigned memory b) internal pure returns (bool) { return a.rawValue < b.rawValue; } /** * @notice Whether `a` is less than `b`. * @param a a FixedPoint. * @param b a uint256. * @return True if `a < b`, or False. */ function isLessThan(Unsigned memory a, uint256 b) internal pure returns (bool) { return a.rawValue < fromUnscaledUint(b).rawValue; } /** * @notice Whether `a` is less than `b`. * @param a a uint256. * @param b a FixedPoint. * @return True if `a < b`, or False. */ function isLessThan(uint256 a, Unsigned memory b) internal pure returns (bool) { return fromUnscaledUint(a).rawValue < b.rawValue; } /** * @notice Whether `a` is less than or equal to `b`. * @param a a FixedPoint. * @param b a FixedPoint. * @return True if `a <= b`, or False. */ function isLessThanOrEqual(Unsigned memory a, Unsigned memory b) internal pure returns (bool) { return a.rawValue <= b.rawValue; } /** * @notice Whether `a` is less than or equal to `b`. * @param a a FixedPoint. * @param b a uint256. * @return True if `a <= b`, or False. */ function isLessThanOrEqual(Unsigned memory a, uint256 b) internal pure returns (bool) { return a.rawValue <= fromUnscaledUint(b).rawValue; } /** * @notice Whether `a` is less than or equal to `b`. * @param a a uint256. * @param b a FixedPoint. * @return True if `a <= b`, or False. */ function isLessThanOrEqual(uint256 a, Unsigned memory b) internal pure returns (bool) { return fromUnscaledUint(a).rawValue <= b.rawValue; } /** * @notice The minimum of `a` and `b`. * @param a a FixedPoint. * @param b a FixedPoint. * @return the minimum of `a` and `b`. */ function min(Unsigned memory a, Unsigned memory b) internal pure returns (Unsigned memory) { return a.rawValue < b.rawValue ? a : b; } /** * @notice The maximum of `a` and `b`. * @param a a FixedPoint. * @param b a FixedPoint. * @return the maximum of `a` and `b`. */ function max(Unsigned memory a, Unsigned memory b) internal pure returns (Unsigned memory) { return a.rawValue > b.rawValue ? a : b; } /** * @notice Adds two `Unsigned`s, reverting on overflow. * @param a a FixedPoint. * @param b a FixedPoint. * @return the sum of `a` and `b`. */ function add(Unsigned memory a, Unsigned memory b) internal pure returns (Unsigned memory) { return Unsigned(a.rawValue.add(b.rawValue)); } /** * @notice Adds an `Unsigned` to an unscaled uint, reverting on overflow. * @param a a FixedPoint. * @param b a uint256. * @return the sum of `a` and `b`. */ function add(Unsigned memory a, uint256 b) internal pure returns (Unsigned memory) { return add(a, fromUnscaledUint(b)); } /** * @notice Subtracts two `Unsigned`s, reverting on overflow. * @param a a FixedPoint. * @param b a FixedPoint. * @return the difference of `a` and `b`. */ function sub(Unsigned memory a, Unsigned memory b) internal pure returns (Unsigned memory) { return Unsigned(a.rawValue.sub(b.rawValue)); } /** * @notice Subtracts an unscaled uint256 from an `Unsigned`, reverting on overflow. * @param a a FixedPoint. * @param b a uint256. * @return the difference of `a` and `b`. */ function sub(Unsigned memory a, uint256 b) internal pure returns (Unsigned memory) { return sub(a, fromUnscaledUint(b)); } /** * @notice Subtracts an `Unsigned` from an unscaled uint256, reverting on overflow. * @param a a uint256. * @param b a FixedPoint. * @return the difference of `a` and `b`. */ function sub(uint256 a, Unsigned memory b) internal pure returns (Unsigned memory) { return sub(fromUnscaledUint(a), b); } /** * @notice Multiplies two `Unsigned`s, reverting on overflow. * @dev This will "floor" the product. * @param a a FixedPoint. * @param b a FixedPoint. * @return the product of `a` and `b`. */ function mul(Unsigned memory a, Unsigned memory b) internal pure returns (Unsigned memory) { // There are two caveats with this computation: // 1. Max output for the represented number is ~10^41, otherwise an intermediate value overflows. 10^41 is // stored internally as a uint256 ~10^59. // 2. Results that can't be represented exactly are truncated not rounded. E.g., 1.4 * 2e-18 = 2.8e-18, which // would round to 3, but this computation produces the result 2. // No need to use SafeMath because FP_SCALING_FACTOR != 0. return Unsigned(a.rawValue.mul(b.rawValue) / FP_SCALING_FACTOR); } /** * @notice Multiplies an `Unsigned` and an unscaled uint256, reverting on overflow. * @dev This will "floor" the product. * @param a a FixedPoint. * @param b a uint256. * @return the product of `a` and `b`. */ function mul(Unsigned memory a, uint256 b) internal pure returns (Unsigned memory) { return Unsigned(a.rawValue.mul(b)); } /** * @notice Multiplies two `Unsigned`s and "ceil's" the product, reverting on overflow. * @param a a FixedPoint. * @param b a FixedPoint. * @return the product of `a` and `b`. */ function mulCeil(Unsigned memory a, Unsigned memory b) internal pure returns (Unsigned memory) { uint256 mulRaw = a.rawValue.mul(b.rawValue); uint256 mulFloor = mulRaw / FP_SCALING_FACTOR; uint256 mod = mulRaw.mod(FP_SCALING_FACTOR); if (mod != 0) { return Unsigned(mulFloor.add(1)); } else { return Unsigned(mulFloor); } } /** * @notice Multiplies an `Unsigned` and an unscaled uint256 and "ceil's" the product, reverting on overflow. * @param a a FixedPoint. * @param b a FixedPoint. * @return the product of `a` and `b`. */ function mulCeil(Unsigned memory a, uint256 b) internal pure returns (Unsigned memory) { // Since b is an int, there is no risk of truncation and we can just mul it normally return Unsigned(a.rawValue.mul(b)); } /** * @notice Divides one `Unsigned` by an `Unsigned`, reverting on overflow or division by 0. * @dev This will "floor" the quotient. * @param a a FixedPoint numerator. * @param b a FixedPoint denominator. * @return the quotient of `a` divided by `b`. */ function div(Unsigned memory a, Unsigned memory b) internal pure returns (Unsigned memory) { // There are two caveats with this computation: // 1. Max value for the number dividend `a` represents is ~10^41, otherwise an intermediate value overflows. // 10^41 is stored internally as a uint256 10^59. // 2. Results that can't be represented exactly are truncated not rounded. E.g., 2 / 3 = 0.6 repeating, which // would round to 0.666666666666666667, but this computation produces the result 0.666666666666666666. return Unsigned(a.rawValue.mul(FP_SCALING_FACTOR).div(b.rawValue)); } /** * @notice Divides one `Unsigned` by an unscaled uint256, reverting on overflow or division by 0. * @dev This will "floor" the quotient. * @param a a FixedPoint numerator. * @param b a uint256 denominator. * @return the quotient of `a` divided by `b`. */ function div(Unsigned memory a, uint256 b) internal pure returns (Unsigned memory) { return Unsigned(a.rawValue.div(b)); } /** * @notice Divides one unscaled uint256 by an `Unsigned`, reverting on overflow or division by 0. * @dev This will "floor" the quotient. * @param a a uint256 numerator. * @param b a FixedPoint denominator. * @return the quotient of `a` divided by `b`. */ function div(uint256 a, Unsigned memory b) internal pure returns (Unsigned memory) { return div(fromUnscaledUint(a), b); } /** * @notice Divides one `Unsigned` by an `Unsigned` and "ceil's" the quotient, reverting on overflow or division by 0. * @param a a FixedPoint numerator. * @param b a FixedPoint denominator. * @return the quotient of `a` divided by `b`. */ function divCeil(Unsigned memory a, Unsigned memory b) internal pure returns (Unsigned memory) { uint256 aScaled = a.rawValue.mul(FP_SCALING_FACTOR); uint256 divFloor = aScaled.div(b.rawValue); uint256 mod = aScaled.mod(b.rawValue); if (mod != 0) { return Unsigned(divFloor.add(1)); } else { return Unsigned(divFloor); } } /** * @notice Divides one `Unsigned` by an unscaled uint256 and "ceil's" the quotient, reverting on overflow or division by 0. * @param a a FixedPoint numerator. * @param b a uint256 denominator. * @return the quotient of `a` divided by `b`. */ function divCeil(Unsigned memory a, uint256 b) internal pure returns (Unsigned memory) { // Because it is possible that a quotient gets truncated, we can't just call "Unsigned(a.rawValue.div(b))" // similarly to mulCeil with a uint256 as the second parameter. Therefore we need to convert b into an Unsigned. // This creates the possibility of overflow if b is very large. return divCeil(a, fromUnscaledUint(b)); } /** * @notice Raises an `Unsigned` to the power of an unscaled uint256, reverting on overflow. E.g., `b=2` squares `a`. * @dev This will "floor" the result. * @param a a FixedPoint numerator. * @param b a uint256 denominator. * @return output is `a` to the power of `b`. */ function pow(Unsigned memory a, uint256 b) internal pure returns (Unsigned memory output) { output = fromUnscaledUint(1); for (uint256 i = 0; i < b; i = i.add(1)) { output = mul(output, a); } } // ------------------------------------------------- SIGNED ------------------------------------------------------------- // Supports 18 decimals. E.g., 1e18 represents "1", 5e17 represents "0.5". // For signed values: // This can represent a value up (or down) to +-(2^255 - 1)/10^18 = ~10^58. 10^58 will be stored internally as int256 10^76. int256 private constant SFP_SCALING_FACTOR = 10**18; struct Signed { int256 rawValue; } function fromSigned(Signed memory a) internal pure returns (Unsigned memory) { require(a.rawValue >= 0, "Negative value provided"); return Unsigned(uint256(a.rawValue)); } function fromUnsigned(Unsigned memory a) internal pure returns (Signed memory) { require(a.rawValue <= uint256(type(int256).max), "Unsigned too large"); return Signed(int256(a.rawValue)); } /** * @notice Constructs a `Signed` from an unscaled int, e.g., `b=5` gets stored internally as `5*(10**18)`. * @param a int to convert into a FixedPoint.Signed. * @return the converted FixedPoint.Signed. */ function fromUnscaledInt(int256 a) internal pure returns (Signed memory) { return Signed(a.mul(SFP_SCALING_FACTOR)); } /** * @notice Whether `a` is equal to `b`. * @param a a FixedPoint.Signed. * @param b a int256. * @return True if equal, or False. */ function isEqual(Signed memory a, int256 b) internal pure returns (bool) { return a.rawValue == fromUnscaledInt(b).rawValue; } /** * @notice Whether `a` is equal to `b`. * @param a a FixedPoint.Signed. * @param b a FixedPoint.Signed. * @return True if equal, or False. */ function isEqual(Signed memory a, Signed memory b) internal pure returns (bool) { return a.rawValue == b.rawValue; } /** * @notice Whether `a` is greater than `b`. * @param a a FixedPoint.Signed. * @param b a FixedPoint.Signed. * @return True if `a > b`, or False. */ function isGreaterThan(Signed memory a, Signed memory b) internal pure returns (bool) { return a.rawValue > b.rawValue; } /** * @notice Whether `a` is greater than `b`. * @param a a FixedPoint.Signed. * @param b an int256. * @return True if `a > b`, or False. */ function isGreaterThan(Signed memory a, int256 b) internal pure returns (bool) { return a.rawValue > fromUnscaledInt(b).rawValue; } /** * @notice Whether `a` is greater than `b`. * @param a an int256. * @param b a FixedPoint.Signed. * @return True if `a > b`, or False. */ function isGreaterThan(int256 a, Signed memory b) internal pure returns (bool) { return fromUnscaledInt(a).rawValue > b.rawValue; } /** * @notice Whether `a` is greater than or equal to `b`. * @param a a FixedPoint.Signed. * @param b a FixedPoint.Signed. * @return True if `a >= b`, or False. */ function isGreaterThanOrEqual(Signed memory a, Signed memory b) internal pure returns (bool) { return a.rawValue >= b.rawValue; } /** * @notice Whether `a` is greater than or equal to `b`. * @param a a FixedPoint.Signed. * @param b an int256. * @return True if `a >= b`, or False. */ function isGreaterThanOrEqual(Signed memory a, int256 b) internal pure returns (bool) { return a.rawValue >= fromUnscaledInt(b).rawValue; } /** * @notice Whether `a` is greater than or equal to `b`. * @param a an int256. * @param b a FixedPoint.Signed. * @return True if `a >= b`, or False. */ function isGreaterThanOrEqual(int256 a, Signed memory b) internal pure returns (bool) { return fromUnscaledInt(a).rawValue >= b.rawValue; } /** * @notice Whether `a` is less than `b`. * @param a a FixedPoint.Signed. * @param b a FixedPoint.Signed. * @return True if `a < b`, or False. */ function isLessThan(Signed memory a, Signed memory b) internal pure returns (bool) { return a.rawValue < b.rawValue; } /** * @notice Whether `a` is less than `b`. * @param a a FixedPoint.Signed. * @param b an int256. * @return True if `a < b`, or False. */ function isLessThan(Signed memory a, int256 b) internal pure returns (bool) { return a.rawValue < fromUnscaledInt(b).rawValue; } /** * @notice Whether `a` is less than `b`. * @param a an int256. * @param b a FixedPoint.Signed. * @return True if `a < b`, or False. */ function isLessThan(int256 a, Signed memory b) internal pure returns (bool) { return fromUnscaledInt(a).rawValue < b.rawValue; } /** * @notice Whether `a` is less than or equal to `b`. * @param a a FixedPoint.Signed. * @param b a FixedPoint.Signed. * @return True if `a <= b`, or False. */ function isLessThanOrEqual(Signed memory a, Signed memory b) internal pure returns (bool) { return a.rawValue <= b.rawValue; } /** * @notice Whether `a` is less than or equal to `b`. * @param a a FixedPoint.Signed. * @param b an int256. * @return True if `a <= b`, or False. */ function isLessThanOrEqual(Signed memory a, int256 b) internal pure returns (bool) { return a.rawValue <= fromUnscaledInt(b).rawValue; } /** * @notice Whether `a` is less than or equal to `b`. * @param a an int256. * @param b a FixedPoint.Signed. * @return True if `a <= b`, or False. */ function isLessThanOrEqual(int256 a, Signed memory b) internal pure returns (bool) { return fromUnscaledInt(a).rawValue <= b.rawValue; } /** * @notice The minimum of `a` and `b`. * @param a a FixedPoint.Signed. * @param b a FixedPoint.Signed. * @return the minimum of `a` and `b`. */ function min(Signed memory a, Signed memory b) internal pure returns (Signed memory) { return a.rawValue < b.rawValue ? a : b; } /** * @notice The maximum of `a` and `b`. * @param a a FixedPoint.Signed. * @param b a FixedPoint.Signed. * @return the maximum of `a` and `b`. */ function max(Signed memory a, Signed memory b) internal pure returns (Signed memory) { return a.rawValue > b.rawValue ? a : b; } /** * @notice Adds two `Signed`s, reverting on overflow. * @param a a FixedPoint.Signed. * @param b a FixedPoint.Signed. * @return the sum of `a` and `b`. */ function add(Signed memory a, Signed memory b) internal pure returns (Signed memory) { return Signed(a.rawValue.add(b.rawValue)); } /** * @notice Adds an `Signed` to an unscaled int, reverting on overflow. * @param a a FixedPoint.Signed. * @param b an int256. * @return the sum of `a` and `b`. */ function add(Signed memory a, int256 b) internal pure returns (Signed memory) { return add(a, fromUnscaledInt(b)); } /** * @notice Subtracts two `Signed`s, reverting on overflow. * @param a a FixedPoint.Signed. * @param b a FixedPoint.Signed. * @return the difference of `a` and `b`. */ function sub(Signed memory a, Signed memory b) internal pure returns (Signed memory) { return Signed(a.rawValue.sub(b.rawValue)); } /** * @notice Subtracts an unscaled int256 from an `Signed`, reverting on overflow. * @param a a FixedPoint.Signed. * @param b an int256. * @return the difference of `a` and `b`. */ function sub(Signed memory a, int256 b) internal pure returns (Signed memory) { return sub(a, fromUnscaledInt(b)); } /** * @notice Subtracts an `Signed` from an unscaled int256, reverting on overflow. * @param a an int256. * @param b a FixedPoint.Signed. * @return the difference of `a` and `b`. */ function sub(int256 a, Signed memory b) internal pure returns (Signed memory) { return sub(fromUnscaledInt(a), b); } /** * @notice Multiplies two `Signed`s, reverting on overflow. * @dev This will "floor" the product. * @param a a FixedPoint.Signed. * @param b a FixedPoint.Signed. * @return the product of `a` and `b`. */ function mul(Signed memory a, Signed memory b) internal pure returns (Signed memory) { // There are two caveats with this computation: // 1. Max output for the represented number is ~10^41, otherwise an intermediate value overflows. 10^41 is // stored internally as an int256 ~10^59. // 2. Results that can't be represented exactly are truncated not rounded. E.g., 1.4 * 2e-18 = 2.8e-18, which // would round to 3, but this computation produces the result 2. // No need to use SafeMath because SFP_SCALING_FACTOR != 0. return Signed(a.rawValue.mul(b.rawValue) / SFP_SCALING_FACTOR); } /** * @notice Multiplies an `Signed` and an unscaled int256, reverting on overflow. * @dev This will "floor" the product. * @param a a FixedPoint.Signed. * @param b an int256. * @return the product of `a` and `b`. */ function mul(Signed memory a, int256 b) internal pure returns (Signed memory) { return Signed(a.rawValue.mul(b)); } /** * @notice Multiplies two `Signed`s and "ceil's" the product, reverting on overflow. * @param a a FixedPoint.Signed. * @param b a FixedPoint.Signed. * @return the product of `a` and `b`. */ function mulAwayFromZero(Signed memory a, Signed memory b) internal pure returns (Signed memory) { int256 mulRaw = a.rawValue.mul(b.rawValue); int256 mulTowardsZero = mulRaw / SFP_SCALING_FACTOR; // Manual mod because SignedSafeMath doesn't support it. int256 mod = mulRaw % SFP_SCALING_FACTOR; if (mod != 0) { bool isResultPositive = isLessThan(a, 0) == isLessThan(b, 0); int256 valueToAdd = isResultPositive ? int256(1) : int256(-1); return Signed(mulTowardsZero.add(valueToAdd)); } else { return Signed(mulTowardsZero); } } /** * @notice Multiplies an `Signed` and an unscaled int256 and "ceil's" the product, reverting on overflow. * @param a a FixedPoint.Signed. * @param b a FixedPoint.Signed. * @return the product of `a` and `b`. */ function mulAwayFromZero(Signed memory a, int256 b) internal pure returns (Signed memory) { // Since b is an int, there is no risk of truncation and we can just mul it normally return Signed(a.rawValue.mul(b)); } /** * @notice Divides one `Signed` by an `Signed`, reverting on overflow or division by 0. * @dev This will "floor" the quotient. * @param a a FixedPoint numerator. * @param b a FixedPoint denominator. * @return the quotient of `a` divided by `b`. */ function div(Signed memory a, Signed memory b) internal pure returns (Signed memory) { // There are two caveats with this computation: // 1. Max value for the number dividend `a` represents is ~10^41, otherwise an intermediate value overflows. // 10^41 is stored internally as an int256 10^59. // 2. Results that can't be represented exactly are truncated not rounded. E.g., 2 / 3 = 0.6 repeating, which // would round to 0.666666666666666667, but this computation produces the result 0.666666666666666666. return Signed(a.rawValue.mul(SFP_SCALING_FACTOR).div(b.rawValue)); } /** * @notice Divides one `Signed` by an unscaled int256, reverting on overflow or division by 0. * @dev This will "floor" the quotient. * @param a a FixedPoint numerator. * @param b an int256 denominator. * @return the quotient of `a` divided by `b`. */ function div(Signed memory a, int256 b) internal pure returns (Signed memory) { return Signed(a.rawValue.div(b)); } /** * @notice Divides one unscaled int256 by an `Signed`, reverting on overflow or division by 0. * @dev This will "floor" the quotient. * @param a an int256 numerator. * @param b a FixedPoint denominator. * @return the quotient of `a` divided by `b`. */ function div(int256 a, Signed memory b) internal pure returns (Signed memory) { return div(fromUnscaledInt(a), b); } /** * @notice Divides one `Signed` by an `Signed` and "ceil's" the quotient, reverting on overflow or division by 0. * @param a a FixedPoint numerator. * @param b a FixedPoint denominator. * @return the quotient of `a` divided by `b`. */ function divAwayFromZero(Signed memory a, Signed memory b) internal pure returns (Signed memory) { int256 aScaled = a.rawValue.mul(SFP_SCALING_FACTOR); int256 divTowardsZero = aScaled.div(b.rawValue); // Manual mod because SignedSafeMath doesn't support it. int256 mod = aScaled % b.rawValue; if (mod != 0) { bool isResultPositive = isLessThan(a, 0) == isLessThan(b, 0); int256 valueToAdd = isResultPositive ? int256(1) : int256(-1); return Signed(divTowardsZero.add(valueToAdd)); } else { return Signed(divTowardsZero); } } /** * @notice Divides one `Signed` by an unscaled int256 and "ceil's" the quotient, reverting on overflow or division by 0. * @param a a FixedPoint numerator. * @param b an int256 denominator. * @return the quotient of `a` divided by `b`. */ function divAwayFromZero(Signed memory a, int256 b) internal pure returns (Signed memory) { // Because it is possible that a quotient gets truncated, we can't just call "Signed(a.rawValue.div(b))" // similarly to mulCeil with an int256 as the second parameter. Therefore we need to convert b into an Signed. // This creates the possibility of overflow if b is very large. return divAwayFromZero(a, fromUnscaledInt(b)); } /** * @notice Raises an `Signed` to the power of an unscaled uint256, reverting on overflow. E.g., `b=2` squares `a`. * @dev This will "floor" the result. * @param a a FixedPoint.Signed. * @param b a uint256 (negative exponents are not allowed). * @return output is `a` to the power of `b`. */ function pow(Signed memory a, uint256 b) internal pure returns (Signed memory output) { output = fromUnscaledInt(1); for (uint256 i = 0; i < b; i = i.add(1)) { output = mul(output, a); } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; // CAUTION // This version of SafeMath should only be used with Solidity 0.8 or later, // because it relies on the compiler's built in overflow checks. /** * @dev Wrappers over Solidity's arithmetic operations. * * NOTE: `SafeMath` is no longer needed starting with Solidity 0.8. The compiler * now has built in overflow checking. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b > a) return (false, 0); return (true, a - b); } } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b == 0) return (false, 0); return (true, a / b); } } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b == 0) return (false, 0); return (true, a % b); } } /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { return a + b; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return a - b; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { return a * b; } /** * @dev Returns the integer division of two unsigned integers, reverting on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { unchecked { require(b <= a, errorMessage); return a - b; } } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { unchecked { require(b > 0, errorMessage); return a / b; } } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { unchecked { require(b > 0, errorMessage); return a % b; } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Wrappers over Solidity's arithmetic operations. * * NOTE: `SignedSafeMath` is no longer needed starting with Solidity 0.8. The compiler * now has built in overflow checking. */ library SignedSafeMath { /** * @dev Returns the multiplication of two signed integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(int256 a, int256 b) internal pure returns (int256) { return a * b; } /** * @dev Returns the integer division of two signed integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. * * Requirements: * * - The divisor cannot be zero. */ function div(int256 a, int256 b) internal pure returns (int256) { return a / b; } /** * @dev Returns the subtraction of two signed integers, reverting on * overflow. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(int256 a, int256 b) internal pure returns (int256) { return a - b; } /** * @dev Returns the addition of two signed integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(int256 a, int256 b) internal pure returns (int256) { return a + b; } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.8.0; pragma abicoder v2; import "../../common/implementation/FixedPoint.sol"; import "../../common/implementation/Testable.sol"; import "../interfaces/OracleInterface.sol"; import "../interfaces/VotingInterface.sol"; // A mock oracle used for testing. Exports the voting & oracle interfaces and events that contain no ancillary data. abstract contract VotingInterfaceTesting is OracleInterface, VotingInterface, Testable { using FixedPoint for FixedPoint.Unsigned; // Events, data structures and functions not exported in the base interfaces, used for testing. event VoteCommitted( address indexed voter, uint256 indexed roundId, bytes32 indexed identifier, uint256 time, bytes ancillaryData ); event EncryptedVote( address indexed voter, uint256 indexed roundId, bytes32 indexed identifier, uint256 time, bytes ancillaryData, bytes encryptedVote ); event VoteRevealed( address indexed voter, uint256 indexed roundId, bytes32 indexed identifier, uint256 time, int256 price, bytes ancillaryData, uint256 numTokens ); event RewardsRetrieved( address indexed voter, uint256 indexed roundId, bytes32 indexed identifier, uint256 time, bytes ancillaryData, uint256 numTokens ); event PriceRequestAdded(uint256 indexed roundId, bytes32 indexed identifier, uint256 time); event PriceResolved( uint256 indexed roundId, bytes32 indexed identifier, uint256 time, int256 price, bytes ancillaryData ); struct Round { uint256 snapshotId; // Voting token snapshot ID for this round. 0 if no snapshot has been taken. FixedPoint.Unsigned inflationRate; // Inflation rate set for this round. FixedPoint.Unsigned gatPercentage; // Gat rate set for this round. uint256 rewardsExpirationTime; // Time that rewards for this round can be claimed until. } // Represents the status a price request has. enum RequestStatus { NotRequested, // Was never requested. Active, // Is being voted on in the current round. Resolved, // Was resolved in a previous round. Future // Is scheduled to be voted on in a future round. } // Only used as a return value in view methods -- never stored in the contract. struct RequestState { RequestStatus status; uint256 lastVotingRound; } function rounds(uint256 roundId) public view virtual returns (Round memory); function getPriceRequestStatuses(VotingInterface.PendingRequest[] memory requests) public view virtual returns (RequestState[] memory); function getPendingPriceRequestsArray() external view virtual returns (bytes32[] memory); } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.8.0; import "./Timer.sol"; /** * @title Base class that provides time overrides, but only if being run in test mode. */ abstract contract Testable { // If the contract is being run on the test network, then `timerAddress` will be the 0x0 address. // Note: this variable should be set on construction and never modified. address public timerAddress; /** * @notice Constructs the Testable contract. Called by child contracts. * @param _timerAddress Contract that stores the current time in a testing environment. * Must be set to 0x0 for production environments that use live time. */ constructor(address _timerAddress) { timerAddress = _timerAddress; } /** * @notice Reverts if not running in test mode. */ modifier onlyIfTest { require(timerAddress != address(0x0)); _; } /** * @notice Sets the current time. * @dev Will revert if not running in test mode. * @param time timestamp to set current Testable time to. */ function setCurrentTime(uint256 time) external onlyIfTest { Timer(timerAddress).setCurrentTime(time); } /** * @notice Gets the current time. Will return the last time set in `setCurrentTime` if running in test mode. * Otherwise, it will return the block timestamp. * @return uint for the current Testable timestamp. */ function getCurrentTime() public view returns (uint256) { if (timerAddress != address(0x0)) { return Timer(timerAddress).getCurrentTime(); } else { return block.timestamp; // solhint-disable-line not-rely-on-time } } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.8.0; /** * @title Financial contract facing Oracle interface. * @dev Interface used by financial contracts to interact with the Oracle. Voters will use a different interface. */ abstract contract OracleInterface { /** * @notice Enqueues a request (if a request isn't already present) for the given `identifier`, `time` pair. * @dev Time must be in the past and the identifier must be supported. * @param identifier uniquely identifies the price requested. eg BTC/USD (encoded as bytes32) could be requested. * @param time unix timestamp for the price request. */ function requestPrice(bytes32 identifier, uint256 time) public virtual; /** * @notice Whether the price for `identifier` and `time` is available. * @dev Time must be in the past and the identifier must be supported. * @param identifier uniquely identifies the price requested. eg BTC/USD (encoded as bytes32) could be requested. * @param time unix timestamp for the price request. * @return bool if the DVM has resolved to a price for the given identifier and timestamp. */ function hasPrice(bytes32 identifier, uint256 time) public view virtual returns (bool); /** * @notice Gets the price for `identifier` and `time` if it has already been requested and resolved. * @dev If the price is not available, the method reverts. * @param identifier uniquely identifies the price requested. eg BTC/USD (encoded as bytes32) could be requested. * @param time unix timestamp for the price request. * @return int256 representing the resolved price for the given identifier and timestamp. */ function getPrice(bytes32 identifier, uint256 time) public view virtual returns (int256); } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.8.0; pragma abicoder v2; import "../../common/implementation/FixedPoint.sol"; import "./VotingAncillaryInterface.sol"; /** * @title Interface that voters must use to Vote on price request resolutions. */ abstract contract VotingInterface { struct PendingRequest { bytes32 identifier; uint256 time; } // Captures the necessary data for making a commitment. // Used as a parameter when making batch commitments. // Not used as a data structure for storage. struct Commitment { bytes32 identifier; uint256 time; bytes32 hash; bytes encryptedVote; } // Captures the necessary data for revealing a vote. // Used as a parameter when making batch reveals. // Not used as a data structure for storage. struct Reveal { bytes32 identifier; uint256 time; int256 price; int256 salt; } /** * @notice Commit a vote for a price request for `identifier` at `time`. * @dev `identifier`, `time` must correspond to a price request that's currently in the commit phase. * Commits can be changed. * @dev Since transaction data is public, the salt will be revealed with the vote. While this is the system’s expected behavior, * voters should never reuse salts. If someone else is able to guess the voted price and knows that a salt will be reused, then * they can determine the vote pre-reveal. * @param identifier uniquely identifies the committed vote. EG BTC/USD price pair. * @param time unix timestamp of the price being voted on. * @param hash keccak256 hash of the `price`, `salt`, voter `address`, `time`, current `roundId`, and `identifier`. */ function commitVote( bytes32 identifier, uint256 time, bytes32 hash ) external virtual; /** * @notice Submit a batch of commits in a single transaction. * @dev Using `encryptedVote` is optional. If included then commitment is stored on chain. * Look at `project-root/common/Constants.js` for the tested maximum number of * commitments that can fit in one transaction. * @param commits array of structs that encapsulate an `identifier`, `time`, `hash` and optional `encryptedVote`. */ function batchCommit(Commitment[] memory commits) public virtual; /** * @notice commits a vote and logs an event with a data blob, typically an encrypted version of the vote * @dev An encrypted version of the vote is emitted in an event `EncryptedVote` to allow off-chain infrastructure to * retrieve the commit. The contents of `encryptedVote` are never used on chain: it is purely for convenience. * @param identifier unique price pair identifier. Eg: BTC/USD price pair. * @param time unix timestamp of for the price request. * @param hash keccak256 hash of the price you want to vote for and a `int256 salt`. * @param encryptedVote offchain encrypted blob containing the voters amount, time and salt. */ function commitAndEmitEncryptedVote( bytes32 identifier, uint256 time, bytes32 hash, bytes memory encryptedVote ) public virtual; /** * @notice snapshot the current round's token balances and lock in the inflation rate and GAT. * @dev This function can be called multiple times but each round will only every have one snapshot at the * time of calling `_freezeRoundVariables`. * @param signature signature required to prove caller is an EOA to prevent flash loans from being included in the * snapshot. */ function snapshotCurrentRound(bytes calldata signature) external virtual; /** * @notice Reveal a previously committed vote for `identifier` at `time`. * @dev The revealed `price`, `salt`, `address`, `time`, `roundId`, and `identifier`, must hash to the latest `hash` * that `commitVote()` was called with. Only the committer can reveal their vote. * @param identifier voted on in the commit phase. EG BTC/USD price pair. * @param time specifies the unix timestamp of the price is being voted on. * @param price voted on during the commit phase. * @param salt value used to hide the commitment price during the commit phase. */ function revealVote( bytes32 identifier, uint256 time, int256 price, int256 salt ) public virtual; /** * @notice Reveal multiple votes in a single transaction. * Look at `project-root/common/Constants.js` for the tested maximum number of reveals. * that can fit in one transaction. * @dev For more information on reveals, review the comment for `revealVote`. * @param reveals array of the Reveal struct which contains an identifier, time, price and salt. */ function batchReveal(Reveal[] memory reveals) public virtual; /** * @notice Gets the queries that are being voted on this round. * @return pendingRequests `PendingRequest` array containing identifiers * and timestamps for all pending requests. */ function getPendingRequests() external view virtual returns (VotingAncillaryInterface.PendingRequestAncillary[] memory); /** * @notice Returns the current voting phase, as a function of the current time. * @return Phase to indicate the current phase. Either { Commit, Reveal, NUM_PHASES_PLACEHOLDER }. */ function getVotePhase() external view virtual returns (VotingAncillaryInterface.Phase); /** * @notice Returns the current round ID, as a function of the current time. * @return uint256 representing the unique round ID. */ function getCurrentRoundId() external view virtual returns (uint256); /** * @notice Retrieves rewards owed for a set of resolved price requests. * @dev Can only retrieve rewards if calling for a valid round and if the * call is done within the timeout threshold (not expired). * @param voterAddress voter for which rewards will be retrieved. Does not have to be the caller. * @param roundId the round from which voting rewards will be retrieved from. * @param toRetrieve array of PendingRequests which rewards are retrieved from. * @return total amount of rewards returned to the voter. */ function retrieveRewards( address voterAddress, uint256 roundId, PendingRequest[] memory toRetrieve ) public virtual returns (FixedPoint.Unsigned memory); // Voting Owner functions. /** * @notice Disables this Voting contract in favor of the migrated one. * @dev Can only be called by the contract owner. * @param newVotingAddress the newly migrated contract address. */ function setMigrated(address newVotingAddress) external virtual; /** * @notice Resets the inflation rate. Note: this change only applies to rounds that have not yet begun. * @dev This method is public because calldata structs are not currently supported by solidity. * @param newInflationRate sets the next round's inflation rate. */ function setInflationRate(FixedPoint.Unsigned memory newInflationRate) public virtual; /** * @notice Resets the Gat percentage. Note: this change only applies to rounds that have not yet begun. * @dev This method is public because calldata structs are not currently supported by solidity. * @param newGatPercentage sets the next round's Gat percentage. */ function setGatPercentage(FixedPoint.Unsigned memory newGatPercentage) public virtual; /** * @notice Resets the rewards expiration timeout. * @dev This change only applies to rounds that have not yet begun. * @param NewRewardsExpirationTimeout how long a caller can wait before choosing to withdraw their rewards. */ function setRewardsExpirationTimeout(uint256 NewRewardsExpirationTimeout) public virtual; } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.8.0; /** * @title Universal store of current contract time for testing environments. */ contract Timer { uint256 private currentTime; constructor() { currentTime = block.timestamp; // solhint-disable-line not-rely-on-time } /** * @notice Sets the current time. * @dev Will revert if not running in test mode. * @param time timestamp to set `currentTime` to. */ function setCurrentTime(uint256 time) external { currentTime = time; } /** * @notice Gets the current time. Will return the last time set in `setCurrentTime` if running in test mode. * Otherwise, it will return the block timestamp. * @return uint256 for the current Testable timestamp. */ function getCurrentTime() public view returns (uint256) { return currentTime; } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.8.0; pragma abicoder v2; import "../../common/implementation/FixedPoint.sol"; /** * @title Interface that voters must use to Vote on price request resolutions. */ abstract contract VotingAncillaryInterface { struct PendingRequestAncillary { bytes32 identifier; uint256 time; bytes ancillaryData; } // Captures the necessary data for making a commitment. // Used as a parameter when making batch commitments. // Not used as a data structure for storage. struct CommitmentAncillary { bytes32 identifier; uint256 time; bytes ancillaryData; bytes32 hash; bytes encryptedVote; } // Captures the necessary data for revealing a vote. // Used as a parameter when making batch reveals. // Not used as a data structure for storage. struct RevealAncillary { bytes32 identifier; uint256 time; int256 price; bytes ancillaryData; int256 salt; } // Note: the phases must be in order. Meaning the first enum value must be the first phase, etc. // `NUM_PHASES_PLACEHOLDER` is to get the number of phases. It isn't an actual phase, and it should always be last. enum Phase { Commit, Reveal, NUM_PHASES_PLACEHOLDER } /** * @notice Commit a vote for a price request for `identifier` at `time`. * @dev `identifier`, `time` must correspond to a price request that's currently in the commit phase. * Commits can be changed. * @dev Since transaction data is public, the salt will be revealed with the vote. While this is the system’s expected behavior, * voters should never reuse salts. If someone else is able to guess the voted price and knows that a salt will be reused, then * they can determine the vote pre-reveal. * @param identifier uniquely identifies the committed vote. EG BTC/USD price pair. * @param time unix timestamp of the price being voted on. * @param hash keccak256 hash of the `price`, `salt`, voter `address`, `time`, current `roundId`, and `identifier`. */ function commitVote( bytes32 identifier, uint256 time, bytes memory ancillaryData, bytes32 hash ) public virtual; /** * @notice Submit a batch of commits in a single transaction. * @dev Using `encryptedVote` is optional. If included then commitment is stored on chain. * Look at `project-root/common/Constants.js` for the tested maximum number of * commitments that can fit in one transaction. * @param commits array of structs that encapsulate an `identifier`, `time`, `hash` and optional `encryptedVote`. */ function batchCommit(CommitmentAncillary[] memory commits) public virtual; /** * @notice commits a vote and logs an event with a data blob, typically an encrypted version of the vote * @dev An encrypted version of the vote is emitted in an event `EncryptedVote` to allow off-chain infrastructure to * retrieve the commit. The contents of `encryptedVote` are never used on chain: it is purely for convenience. * @param identifier unique price pair identifier. Eg: BTC/USD price pair. * @param time unix timestamp of for the price request. * @param hash keccak256 hash of the price you want to vote for and a `int256 salt`. * @param encryptedVote offchain encrypted blob containing the voters amount, time and salt. */ function commitAndEmitEncryptedVote( bytes32 identifier, uint256 time, bytes memory ancillaryData, bytes32 hash, bytes memory encryptedVote ) public virtual; /** * @notice snapshot the current round's token balances and lock in the inflation rate and GAT. * @dev This function can be called multiple times but each round will only every have one snapshot at the * time of calling `_freezeRoundVariables`. * @param signature signature required to prove caller is an EOA to prevent flash loans from being included in the * snapshot. */ function snapshotCurrentRound(bytes calldata signature) external virtual; /** * @notice Reveal a previously committed vote for `identifier` at `time`. * @dev The revealed `price`, `salt`, `address`, `time`, `roundId`, and `identifier`, must hash to the latest `hash` * that `commitVote()` was called with. Only the committer can reveal their vote. * @param identifier voted on in the commit phase. EG BTC/USD price pair. * @param time specifies the unix timestamp of the price is being voted on. * @param price voted on during the commit phase. * @param salt value used to hide the commitment price during the commit phase. */ function revealVote( bytes32 identifier, uint256 time, int256 price, bytes memory ancillaryData, int256 salt ) public virtual; /** * @notice Reveal multiple votes in a single transaction. * Look at `project-root/common/Constants.js` for the tested maximum number of reveals. * that can fit in one transaction. * @dev For more information on reveals, review the comment for `revealVote`. * @param reveals array of the Reveal struct which contains an identifier, time, price and salt. */ function batchReveal(RevealAncillary[] memory reveals) public virtual; /** * @notice Gets the queries that are being voted on this round. * @return pendingRequests `PendingRequest` array containing identifiers * and timestamps for all pending requests. */ function getPendingRequests() external view virtual returns (PendingRequestAncillary[] memory); /** * @notice Returns the current voting phase, as a function of the current time. * @return Phase to indicate the current phase. Either { Commit, Reveal, NUM_PHASES_PLACEHOLDER }. */ function getVotePhase() external view virtual returns (Phase); /** * @notice Returns the current round ID, as a function of the current time. * @return uint256 representing the unique round ID. */ function getCurrentRoundId() external view virtual returns (uint256); /** * @notice Retrieves rewards owed for a set of resolved price requests. * @dev Can only retrieve rewards if calling for a valid round and if the * call is done within the timeout threshold (not expired). * @param voterAddress voter for which rewards will be retrieved. Does not have to be the caller. * @param roundId the round from which voting rewards will be retrieved from. * @param toRetrieve array of PendingRequests which rewards are retrieved from. * @return total amount of rewards returned to the voter. */ function retrieveRewards( address voterAddress, uint256 roundId, PendingRequestAncillary[] memory toRetrieve ) public virtual returns (FixedPoint.Unsigned memory); // Voting Owner functions. /** * @notice Disables this Voting contract in favor of the migrated one. * @dev Can only be called by the contract owner. * @param newVotingAddress the newly migrated contract address. */ function setMigrated(address newVotingAddress) external virtual; /** * @notice Resets the inflation rate. Note: this change only applies to rounds that have not yet begun. * @dev This method is public because calldata structs are not currently supported by solidity. * @param newInflationRate sets the next round's inflation rate. */ function setInflationRate(FixedPoint.Unsigned memory newInflationRate) public virtual; /** * @notice Resets the Gat percentage. Note: this change only applies to rounds that have not yet begun. * @dev This method is public because calldata structs are not currently supported by solidity. * @param newGatPercentage sets the next round's Gat percentage. */ function setGatPercentage(FixedPoint.Unsigned memory newGatPercentage) public virtual; /** * @notice Resets the rewards expiration timeout. * @dev This change only applies to rounds that have not yet begun. * @param NewRewardsExpirationTimeout how long a caller can wait before choosing to withdraw their rewards. */ function setRewardsExpirationTimeout(uint256 NewRewardsExpirationTimeout) public virtual; } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.8.0; pragma abicoder v2; import "../../common/implementation/FixedPoint.sol"; import "../../common/implementation/Testable.sol"; import "../interfaces/FinderInterface.sol"; import "../interfaces/OracleInterface.sol"; import "../interfaces/OracleAncillaryInterface.sol"; import "../interfaces/VotingInterface.sol"; import "../interfaces/VotingAncillaryInterface.sol"; import "../interfaces/IdentifierWhitelistInterface.sol"; import "./Registry.sol"; import "./ResultComputation.sol"; import "./VoteTiming.sol"; import "./VotingToken.sol"; import "./Constants.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/utils/math/SafeMath.sol"; import "@openzeppelin/contracts/utils/cryptography/ECDSA.sol"; /** * @title Voting system for Oracle. * @dev Handles receiving and resolving price requests via a commit-reveal voting scheme. */ contract Voting is Testable, Ownable, OracleInterface, OracleAncillaryInterface, // Interface to support ancillary data with price requests. VotingInterface, VotingAncillaryInterface // Interface to support ancillary data with voting rounds. { using FixedPoint for FixedPoint.Unsigned; using SafeMath for uint256; using VoteTiming for VoteTiming.Data; using ResultComputation for ResultComputation.Data; /**************************************** * VOTING DATA STRUCTURES * ****************************************/ // Identifies a unique price request for which the Oracle will always return the same value. // Tracks ongoing votes as well as the result of the vote. struct PriceRequest { bytes32 identifier; uint256 time; // A map containing all votes for this price in various rounds. mapping(uint256 => VoteInstance) voteInstances; // If in the past, this was the voting round where this price was resolved. If current or the upcoming round, // this is the voting round where this price will be voted on, but not necessarily resolved. uint256 lastVotingRound; // The index in the `pendingPriceRequests` that references this PriceRequest. A value of UINT_MAX means that // this PriceRequest is resolved and has been cleaned up from `pendingPriceRequests`. uint256 index; bytes ancillaryData; } struct VoteInstance { // Maps (voterAddress) to their submission. mapping(address => VoteSubmission) voteSubmissions; // The data structure containing the computed voting results. ResultComputation.Data resultComputation; } struct VoteSubmission { // A bytes32 of `0` indicates no commit or a commit that was already revealed. bytes32 commit; // The hash of the value that was revealed. // Note: this is only used for computation of rewards. bytes32 revealHash; } struct Round { uint256 snapshotId; // Voting token snapshot ID for this round. 0 if no snapshot has been taken. FixedPoint.Unsigned inflationRate; // Inflation rate set for this round. FixedPoint.Unsigned gatPercentage; // Gat rate set for this round. uint256 rewardsExpirationTime; // Time that rewards for this round can be claimed until. } // Represents the status a price request has. enum RequestStatus { NotRequested, // Was never requested. Active, // Is being voted on in the current round. Resolved, // Was resolved in a previous round. Future // Is scheduled to be voted on in a future round. } // Only used as a return value in view methods -- never stored in the contract. struct RequestState { RequestStatus status; uint256 lastVotingRound; } /**************************************** * INTERNAL TRACKING * ****************************************/ // Maps round numbers to the rounds. mapping(uint256 => Round) public rounds; // Maps price request IDs to the PriceRequest struct. mapping(bytes32 => PriceRequest) private priceRequests; // Price request ids for price requests that haven't yet been marked as resolved. // These requests may be for future rounds. bytes32[] internal pendingPriceRequests; VoteTiming.Data public voteTiming; // Percentage of the total token supply that must be used in a vote to // create a valid price resolution. 1 == 100%. FixedPoint.Unsigned public gatPercentage; // Global setting for the rate of inflation per vote. This is the percentage of the snapshotted total supply that // should be split among the correct voters. // Note: this value is used to set per-round inflation at the beginning of each round. 1 = 100%. FixedPoint.Unsigned public inflationRate; // Time in seconds from the end of the round in which a price request is // resolved that voters can still claim their rewards. uint256 public rewardsExpirationTimeout; // Reference to the voting token. VotingToken public votingToken; // Reference to the Finder. FinderInterface private finder; // If non-zero, this contract has been migrated to this address. All voters and // financial contracts should query the new address only. address public migratedAddress; // Max value of an unsigned integer. uint256 private constant UINT_MAX = ~uint256(0); // Max length in bytes of ancillary data that can be appended to a price request. // As of December 2020, the current Ethereum gas limit is 12.5 million. This requestPrice function's gas primarily // comes from computing a Keccak-256 hash in _encodePriceRequest and writing a new PriceRequest to // storage. We have empirically determined an ancillary data limit of 8192 bytes that keeps this function // well within the gas limit at ~8 million gas. To learn more about the gas limit and EVM opcode costs go here: // - https://etherscan.io/chart/gaslimit // - https://github.com/djrtwo/evm-opcode-gas-costs uint256 public constant ancillaryBytesLimit = 8192; bytes32 public snapshotMessageHash = ECDSA.toEthSignedMessageHash(keccak256(bytes("Sign For Snapshot"))); /*************************************** * EVENTS * ****************************************/ event VoteCommitted( address indexed voter, uint256 indexed roundId, bytes32 indexed identifier, uint256 time, bytes ancillaryData ); event EncryptedVote( address indexed voter, uint256 indexed roundId, bytes32 indexed identifier, uint256 time, bytes ancillaryData, bytes encryptedVote ); event VoteRevealed( address indexed voter, uint256 indexed roundId, bytes32 indexed identifier, uint256 time, int256 price, bytes ancillaryData, uint256 numTokens ); event RewardsRetrieved( address indexed voter, uint256 indexed roundId, bytes32 indexed identifier, uint256 time, bytes ancillaryData, uint256 numTokens ); event PriceRequestAdded(uint256 indexed roundId, bytes32 indexed identifier, uint256 time); event PriceResolved( uint256 indexed roundId, bytes32 indexed identifier, uint256 time, int256 price, bytes ancillaryData ); /** * @notice Construct the Voting contract. * @param _phaseLength length of the commit and reveal phases in seconds. * @param _gatPercentage of the total token supply that must be used in a vote to create a valid price resolution. * @param _inflationRate percentage inflation per round used to increase token supply of correct voters. * @param _rewardsExpirationTimeout timeout, in seconds, within which rewards must be claimed. * @param _votingToken address of the UMA token contract used to commit votes. * @param _finder keeps track of all contracts within the system based on their interfaceName. * @param _timerAddress Contract that stores the current time in a testing environment. * Must be set to 0x0 for production environments that use live time. */ constructor( uint256 _phaseLength, FixedPoint.Unsigned memory _gatPercentage, FixedPoint.Unsigned memory _inflationRate, uint256 _rewardsExpirationTimeout, address _votingToken, address _finder, address _timerAddress ) Testable(_timerAddress) { voteTiming.init(_phaseLength); require(_gatPercentage.isLessThanOrEqual(1), "GAT percentage must be <= 100%"); gatPercentage = _gatPercentage; inflationRate = _inflationRate; votingToken = VotingToken(_votingToken); finder = FinderInterface(_finder); rewardsExpirationTimeout = _rewardsExpirationTimeout; } /*************************************** MODIFIERS ****************************************/ modifier onlyRegisteredContract() { if (migratedAddress != address(0)) { require(msg.sender == migratedAddress, "Caller must be migrated address"); } else { Registry registry = Registry(finder.getImplementationAddress(OracleInterfaces.Registry)); require(registry.isContractRegistered(msg.sender), "Called must be registered"); } _; } modifier onlyIfNotMigrated() { require(migratedAddress == address(0), "Only call this if not migrated"); _; } /**************************************** * PRICE REQUEST AND ACCESS FUNCTIONS * ****************************************/ /** * @notice Enqueues a request (if a request isn't already present) for the given `identifier`, `time` pair. * @dev Time must be in the past and the identifier must be supported. The length of the ancillary data * is limited such that this method abides by the EVM transaction gas limit. * @param identifier uniquely identifies the price requested. eg BTC/USD (encoded as bytes32) could be requested. * @param time unix timestamp for the price request. * @param ancillaryData arbitrary data appended to a price request to give the voters more info from the caller. */ function requestPrice( bytes32 identifier, uint256 time, bytes memory ancillaryData ) public override onlyRegisteredContract() { uint256 blockTime = getCurrentTime(); require(time <= blockTime, "Can only request in past"); require(_getIdentifierWhitelist().isIdentifierSupported(identifier), "Unsupported identifier request"); require(ancillaryData.length <= ancillaryBytesLimit, "Invalid ancillary data"); bytes32 priceRequestId = _encodePriceRequest(identifier, time, ancillaryData); PriceRequest storage priceRequest = priceRequests[priceRequestId]; uint256 currentRoundId = voteTiming.computeCurrentRoundId(blockTime); RequestStatus requestStatus = _getRequestStatus(priceRequest, currentRoundId); if (requestStatus == RequestStatus.NotRequested) { // Price has never been requested. // Price requests always go in the next round, so add 1 to the computed current round. uint256 nextRoundId = currentRoundId.add(1); PriceRequest storage newPriceRequest = priceRequests[priceRequestId]; newPriceRequest.identifier = identifier; newPriceRequest.time = time; newPriceRequest.lastVotingRound = nextRoundId; newPriceRequest.index = pendingPriceRequests.length; newPriceRequest.ancillaryData = ancillaryData; pendingPriceRequests.push(priceRequestId); emit PriceRequestAdded(nextRoundId, identifier, time); } } // Overloaded method to enable short term backwards compatibility. Will be deprecated in the next DVM version. function requestPrice(bytes32 identifier, uint256 time) public override { requestPrice(identifier, time, ""); } /** * @notice Whether the price for `identifier` and `time` is available. * @dev Time must be in the past and the identifier must be supported. * @param identifier uniquely identifies the price requested. eg BTC/USD (encoded as bytes32) could be requested. * @param time unix timestamp of for the price request. * @param ancillaryData arbitrary data appended to a price request to give the voters more info from the caller. * @return _hasPrice bool if the DVM has resolved to a price for the given identifier and timestamp. */ function hasPrice( bytes32 identifier, uint256 time, bytes memory ancillaryData ) public view override onlyRegisteredContract() returns (bool) { (bool _hasPrice, , ) = _getPriceOrError(identifier, time, ancillaryData); return _hasPrice; } // Overloaded method to enable short term backwards compatibility. Will be deprecated in the next DVM version. function hasPrice(bytes32 identifier, uint256 time) public view override returns (bool) { return hasPrice(identifier, time, ""); } /** * @notice Gets the price for `identifier` and `time` if it has already been requested and resolved. * @dev If the price is not available, the method reverts. * @param identifier uniquely identifies the price requested. eg BTC/USD (encoded as bytes32) could be requested. * @param time unix timestamp of for the price request. * @param ancillaryData arbitrary data appended to a price request to give the voters more info from the caller. * @return int256 representing the resolved price for the given identifier and timestamp. */ function getPrice( bytes32 identifier, uint256 time, bytes memory ancillaryData ) public view override onlyRegisteredContract() returns (int256) { (bool _hasPrice, int256 price, string memory message) = _getPriceOrError(identifier, time, ancillaryData); // If the price wasn't available, revert with the provided message. require(_hasPrice, message); return price; } // Overloaded method to enable short term backwards compatibility. Will be deprecated in the next DVM version. function getPrice(bytes32 identifier, uint256 time) public view override returns (int256) { return getPrice(identifier, time, ""); } /** * @notice Gets the status of a list of price requests, identified by their identifier and time. * @dev If the status for a particular request is NotRequested, the lastVotingRound will always be 0. * @param requests array of type PendingRequest which includes an identifier and timestamp for each request. * @return requestStates a list, in the same order as the input list, giving the status of each of the specified price requests. */ function getPriceRequestStatuses(PendingRequestAncillary[] memory requests) public view returns (RequestState[] memory) { RequestState[] memory requestStates = new RequestState[](requests.length); uint256 currentRoundId = voteTiming.computeCurrentRoundId(getCurrentTime()); for (uint256 i = 0; i < requests.length; i++) { PriceRequest storage priceRequest = _getPriceRequest(requests[i].identifier, requests[i].time, requests[i].ancillaryData); RequestStatus status = _getRequestStatus(priceRequest, currentRoundId); // If it's an active request, its true lastVotingRound is the current one, even if it hasn't been updated. if (status == RequestStatus.Active) { requestStates[i].lastVotingRound = currentRoundId; } else { requestStates[i].lastVotingRound = priceRequest.lastVotingRound; } requestStates[i].status = status; } return requestStates; } // Overloaded method to enable short term backwards compatibility. Will be deprecated in the next DVM version. function getPriceRequestStatuses(PendingRequest[] memory requests) public view returns (RequestState[] memory) { PendingRequestAncillary[] memory requestsAncillary = new PendingRequestAncillary[](requests.length); for (uint256 i = 0; i < requests.length; i++) { requestsAncillary[i].identifier = requests[i].identifier; requestsAncillary[i].time = requests[i].time; requestsAncillary[i].ancillaryData = ""; } return getPriceRequestStatuses(requestsAncillary); } /**************************************** * VOTING FUNCTIONS * ****************************************/ /** * @notice Commit a vote for a price request for `identifier` at `time`. * @dev `identifier`, `time` must correspond to a price request that's currently in the commit phase. * Commits can be changed. * @dev Since transaction data is public, the salt will be revealed with the vote. While this is the system’s expected behavior, * voters should never reuse salts. If someone else is able to guess the voted price and knows that a salt will be reused, then * they can determine the vote pre-reveal. * @param identifier uniquely identifies the committed vote. EG BTC/USD price pair. * @param time unix timestamp of the price being voted on. * @param ancillaryData arbitrary data appended to a price request to give the voters more info from the caller. * @param hash keccak256 hash of the `price`, `salt`, voter `address`, `time`, current `roundId`, and `identifier`. */ function commitVote( bytes32 identifier, uint256 time, bytes memory ancillaryData, bytes32 hash ) public override onlyIfNotMigrated() { require(hash != bytes32(0), "Invalid provided hash"); // Current time is required for all vote timing queries. uint256 blockTime = getCurrentTime(); require( voteTiming.computeCurrentPhase(blockTime) == VotingAncillaryInterface.Phase.Commit, "Cannot commit in reveal phase" ); // At this point, the computed and last updated round ID should be equal. uint256 currentRoundId = voteTiming.computeCurrentRoundId(blockTime); PriceRequest storage priceRequest = _getPriceRequest(identifier, time, ancillaryData); require( _getRequestStatus(priceRequest, currentRoundId) == RequestStatus.Active, "Cannot commit inactive request" ); priceRequest.lastVotingRound = currentRoundId; VoteInstance storage voteInstance = priceRequest.voteInstances[currentRoundId]; voteInstance.voteSubmissions[msg.sender].commit = hash; emit VoteCommitted(msg.sender, currentRoundId, identifier, time, ancillaryData); } // Overloaded method to enable short term backwards compatibility. Will be deprecated in the next DVM version. function commitVote( bytes32 identifier, uint256 time, bytes32 hash ) public override onlyIfNotMigrated() { commitVote(identifier, time, "", hash); } /** * @notice Snapshot the current round's token balances and lock in the inflation rate and GAT. * @dev This function can be called multiple times, but only the first call per round into this function or `revealVote` * will create the round snapshot. Any later calls will be a no-op. Will revert unless called during reveal period. * @param signature signature required to prove caller is an EOA to prevent flash loans from being included in the * snapshot. */ function snapshotCurrentRound(bytes calldata signature) external override(VotingInterface, VotingAncillaryInterface) onlyIfNotMigrated() { uint256 blockTime = getCurrentTime(); require(voteTiming.computeCurrentPhase(blockTime) == Phase.Reveal, "Only snapshot in reveal phase"); // Require public snapshot require signature to ensure caller is an EOA. require(ECDSA.recover(snapshotMessageHash, signature) == msg.sender, "Signature must match sender"); uint256 roundId = voteTiming.computeCurrentRoundId(blockTime); _freezeRoundVariables(roundId); } /** * @notice Reveal a previously committed vote for `identifier` at `time`. * @dev The revealed `price`, `salt`, `address`, `time`, `roundId`, and `identifier`, must hash to the latest `hash` * that `commitVote()` was called with. Only the committer can reveal their vote. * @param identifier voted on in the commit phase. EG BTC/USD price pair. * @param time specifies the unix timestamp of the price being voted on. * @param price voted on during the commit phase. * @param ancillaryData arbitrary data appended to a price request to give the voters more info from the caller. * @param salt value used to hide the commitment price during the commit phase. */ function revealVote( bytes32 identifier, uint256 time, int256 price, bytes memory ancillaryData, int256 salt ) public override onlyIfNotMigrated() { require(voteTiming.computeCurrentPhase(getCurrentTime()) == Phase.Reveal, "Cannot reveal in commit phase"); // Note: computing the current round is required to disallow people from revealing an old commit after the round is over. uint256 roundId = voteTiming.computeCurrentRoundId(getCurrentTime()); PriceRequest storage priceRequest = _getPriceRequest(identifier, time, ancillaryData); VoteInstance storage voteInstance = priceRequest.voteInstances[roundId]; VoteSubmission storage voteSubmission = voteInstance.voteSubmissions[msg.sender]; // Scoping to get rid of a stack too deep error. { // 0 hashes are disallowed in the commit phase, so they indicate a different error. // Cannot reveal an uncommitted or previously revealed hash require(voteSubmission.commit != bytes32(0), "Invalid hash reveal"); require( keccak256(abi.encodePacked(price, salt, msg.sender, time, ancillaryData, roundId, identifier)) == voteSubmission.commit, "Revealed data != commit hash" ); // To protect against flash loans, we require snapshot be validated as EOA. require(rounds[roundId].snapshotId != 0, "Round has no snapshot"); } // Get the frozen snapshotId uint256 snapshotId = rounds[roundId].snapshotId; delete voteSubmission.commit; // Get the voter's snapshotted balance. Since balances are returned pre-scaled by 10**18, we can directly // initialize the Unsigned value with the returned uint. FixedPoint.Unsigned memory balance = FixedPoint.Unsigned(votingToken.balanceOfAt(msg.sender, snapshotId)); // Set the voter's submission. voteSubmission.revealHash = keccak256(abi.encode(price)); // Add vote to the results. voteInstance.resultComputation.addVote(price, balance); emit VoteRevealed(msg.sender, roundId, identifier, time, price, ancillaryData, balance.rawValue); } // Overloaded method to enable short term backwards compatibility. Will be deprecated in the next DVM version. function revealVote( bytes32 identifier, uint256 time, int256 price, int256 salt ) public override { revealVote(identifier, time, price, "", salt); } /** * @notice commits a vote and logs an event with a data blob, typically an encrypted version of the vote * @dev An encrypted version of the vote is emitted in an event `EncryptedVote` to allow off-chain infrastructure to * retrieve the commit. The contents of `encryptedVote` are never used on chain: it is purely for convenience. * @param identifier unique price pair identifier. Eg: BTC/USD price pair. * @param time unix timestamp of for the price request. * @param ancillaryData arbitrary data appended to a price request to give the voters more info from the caller. * @param hash keccak256 hash of the price you want to vote for and a `int256 salt`. * @param encryptedVote offchain encrypted blob containing the voters amount, time and salt. */ function commitAndEmitEncryptedVote( bytes32 identifier, uint256 time, bytes memory ancillaryData, bytes32 hash, bytes memory encryptedVote ) public override { commitVote(identifier, time, ancillaryData, hash); uint256 roundId = voteTiming.computeCurrentRoundId(getCurrentTime()); emit EncryptedVote(msg.sender, roundId, identifier, time, ancillaryData, encryptedVote); } // Overloaded method to enable short term backwards compatibility. Will be deprecated in the next DVM version. function commitAndEmitEncryptedVote( bytes32 identifier, uint256 time, bytes32 hash, bytes memory encryptedVote ) public override { commitVote(identifier, time, "", hash); commitAndEmitEncryptedVote(identifier, time, "", hash, encryptedVote); } /** * @notice Submit a batch of commits in a single transaction. * @dev Using `encryptedVote` is optional. If included then commitment is emitted in an event. * Look at `project-root/common/Constants.js` for the tested maximum number of * commitments that can fit in one transaction. * @param commits struct to encapsulate an `identifier`, `time`, `hash` and optional `encryptedVote`. */ function batchCommit(CommitmentAncillary[] memory commits) public override { for (uint256 i = 0; i < commits.length; i++) { if (commits[i].encryptedVote.length == 0) { commitVote(commits[i].identifier, commits[i].time, commits[i].ancillaryData, commits[i].hash); } else { commitAndEmitEncryptedVote( commits[i].identifier, commits[i].time, commits[i].ancillaryData, commits[i].hash, commits[i].encryptedVote ); } } } // Overloaded method to enable short term backwards compatibility. Will be deprecated in the next DVM version. function batchCommit(Commitment[] memory commits) public override { CommitmentAncillary[] memory commitsAncillary = new CommitmentAncillary[](commits.length); for (uint256 i = 0; i < commits.length; i++) { commitsAncillary[i].identifier = commits[i].identifier; commitsAncillary[i].time = commits[i].time; commitsAncillary[i].ancillaryData = ""; commitsAncillary[i].hash = commits[i].hash; commitsAncillary[i].encryptedVote = commits[i].encryptedVote; } batchCommit(commitsAncillary); } /** * @notice Reveal multiple votes in a single transaction. * Look at `project-root/common/Constants.js` for the tested maximum number of reveals. * that can fit in one transaction. * @dev For more info on reveals, review the comment for `revealVote`. * @param reveals array of the Reveal struct which contains an identifier, time, price and salt. */ function batchReveal(RevealAncillary[] memory reveals) public override { for (uint256 i = 0; i < reveals.length; i++) { revealVote( reveals[i].identifier, reveals[i].time, reveals[i].price, reveals[i].ancillaryData, reveals[i].salt ); } } // Overloaded method to enable short term backwards compatibility. Will be deprecated in the next DVM version. function batchReveal(Reveal[] memory reveals) public override { RevealAncillary[] memory revealsAncillary = new RevealAncillary[](reveals.length); for (uint256 i = 0; i < reveals.length; i++) { revealsAncillary[i].identifier = reveals[i].identifier; revealsAncillary[i].time = reveals[i].time; revealsAncillary[i].price = reveals[i].price; revealsAncillary[i].ancillaryData = ""; revealsAncillary[i].salt = reveals[i].salt; } batchReveal(revealsAncillary); } /** * @notice Retrieves rewards owed for a set of resolved price requests. * @dev Can only retrieve rewards if calling for a valid round and if the call is done within the timeout threshold * (not expired). Note that a named return value is used here to avoid a stack to deep error. * @param voterAddress voter for which rewards will be retrieved. Does not have to be the caller. * @param roundId the round from which voting rewards will be retrieved from. * @param toRetrieve array of PendingRequests which rewards are retrieved from. * @return totalRewardToIssue total amount of rewards returned to the voter. */ function retrieveRewards( address voterAddress, uint256 roundId, PendingRequestAncillary[] memory toRetrieve ) public override returns (FixedPoint.Unsigned memory totalRewardToIssue) { if (migratedAddress != address(0)) { require(msg.sender == migratedAddress, "Can only call from migrated"); } require(roundId < voteTiming.computeCurrentRoundId(getCurrentTime()), "Invalid roundId"); Round storage round = rounds[roundId]; bool isExpired = getCurrentTime() > round.rewardsExpirationTime; FixedPoint.Unsigned memory snapshotBalance = FixedPoint.Unsigned(votingToken.balanceOfAt(voterAddress, round.snapshotId)); // Compute the total amount of reward that will be issued for each of the votes in the round. FixedPoint.Unsigned memory snapshotTotalSupply = FixedPoint.Unsigned(votingToken.totalSupplyAt(round.snapshotId)); FixedPoint.Unsigned memory totalRewardPerVote = round.inflationRate.mul(snapshotTotalSupply); // Keep track of the voter's accumulated token reward. totalRewardToIssue = FixedPoint.Unsigned(0); for (uint256 i = 0; i < toRetrieve.length; i++) { PriceRequest storage priceRequest = _getPriceRequest(toRetrieve[i].identifier, toRetrieve[i].time, toRetrieve[i].ancillaryData); VoteInstance storage voteInstance = priceRequest.voteInstances[priceRequest.lastVotingRound]; // Only retrieve rewards for votes resolved in same round require(priceRequest.lastVotingRound == roundId, "Retrieve for votes same round"); _resolvePriceRequest(priceRequest, voteInstance); if (voteInstance.voteSubmissions[voterAddress].revealHash == 0) { continue; } else if (isExpired) { // Emit a 0 token retrieval on expired rewards. emit RewardsRetrieved( voterAddress, roundId, toRetrieve[i].identifier, toRetrieve[i].time, toRetrieve[i].ancillaryData, 0 ); } else if ( voteInstance.resultComputation.wasVoteCorrect(voteInstance.voteSubmissions[voterAddress].revealHash) ) { // The price was successfully resolved during the voter's last voting round, the voter revealed // and was correct, so they are eligible for a reward. // Compute the reward and add to the cumulative reward. FixedPoint.Unsigned memory reward = snapshotBalance.mul(totalRewardPerVote).div( voteInstance.resultComputation.getTotalCorrectlyVotedTokens() ); totalRewardToIssue = totalRewardToIssue.add(reward); // Emit reward retrieval for this vote. emit RewardsRetrieved( voterAddress, roundId, toRetrieve[i].identifier, toRetrieve[i].time, toRetrieve[i].ancillaryData, reward.rawValue ); } else { // Emit a 0 token retrieval on incorrect votes. emit RewardsRetrieved( voterAddress, roundId, toRetrieve[i].identifier, toRetrieve[i].time, toRetrieve[i].ancillaryData, 0 ); } // Delete the submission to capture any refund and clean up storage. delete voteInstance.voteSubmissions[voterAddress].revealHash; } // Issue any accumulated rewards. if (totalRewardToIssue.isGreaterThan(0)) { require(votingToken.mint(voterAddress, totalRewardToIssue.rawValue), "Voting token issuance failed"); } } // Overloaded method to enable short term backwards compatibility. Will be deprecated in the next DVM version. function retrieveRewards( address voterAddress, uint256 roundId, PendingRequest[] memory toRetrieve ) public override returns (FixedPoint.Unsigned memory) { PendingRequestAncillary[] memory toRetrieveAncillary = new PendingRequestAncillary[](toRetrieve.length); for (uint256 i = 0; i < toRetrieve.length; i++) { toRetrieveAncillary[i].identifier = toRetrieve[i].identifier; toRetrieveAncillary[i].time = toRetrieve[i].time; toRetrieveAncillary[i].ancillaryData = ""; } return retrieveRewards(voterAddress, roundId, toRetrieveAncillary); } /**************************************** * VOTING GETTER FUNCTIONS * ****************************************/ /** * @notice Gets the queries that are being voted on this round. * @return pendingRequests array containing identifiers of type `PendingRequest`. * and timestamps for all pending requests. */ function getPendingRequests() external view override(VotingInterface, VotingAncillaryInterface) returns (PendingRequestAncillary[] memory) { uint256 blockTime = getCurrentTime(); uint256 currentRoundId = voteTiming.computeCurrentRoundId(blockTime); // Solidity memory arrays aren't resizable (and reading storage is expensive). Hence this hackery to filter // `pendingPriceRequests` only to those requests that have an Active RequestStatus. PendingRequestAncillary[] memory unresolved = new PendingRequestAncillary[](pendingPriceRequests.length); uint256 numUnresolved = 0; for (uint256 i = 0; i < pendingPriceRequests.length; i++) { PriceRequest storage priceRequest = priceRequests[pendingPriceRequests[i]]; if (_getRequestStatus(priceRequest, currentRoundId) == RequestStatus.Active) { unresolved[numUnresolved] = PendingRequestAncillary({ identifier: priceRequest.identifier, time: priceRequest.time, ancillaryData: priceRequest.ancillaryData }); numUnresolved++; } } PendingRequestAncillary[] memory pendingRequests = new PendingRequestAncillary[](numUnresolved); for (uint256 i = 0; i < numUnresolved; i++) { pendingRequests[i] = unresolved[i]; } return pendingRequests; } /** * @notice Returns the current voting phase, as a function of the current time. * @return Phase to indicate the current phase. Either { Commit, Reveal, NUM_PHASES_PLACEHOLDER }. */ function getVotePhase() external view override(VotingInterface, VotingAncillaryInterface) returns (Phase) { return voteTiming.computeCurrentPhase(getCurrentTime()); } /** * @notice Returns the current round ID, as a function of the current time. * @return uint256 representing the unique round ID. */ function getCurrentRoundId() external view override(VotingInterface, VotingAncillaryInterface) returns (uint256) { return voteTiming.computeCurrentRoundId(getCurrentTime()); } /**************************************** * OWNER ADMIN FUNCTIONS * ****************************************/ /** * @notice Disables this Voting contract in favor of the migrated one. * @dev Can only be called by the contract owner. * @param newVotingAddress the newly migrated contract address. */ function setMigrated(address newVotingAddress) external override(VotingInterface, VotingAncillaryInterface) onlyOwner { migratedAddress = newVotingAddress; } /** * @notice Resets the inflation rate. Note: this change only applies to rounds that have not yet begun. * @dev This method is public because calldata structs are not currently supported by solidity. * @param newInflationRate sets the next round's inflation rate. */ function setInflationRate(FixedPoint.Unsigned memory newInflationRate) public override(VotingInterface, VotingAncillaryInterface) onlyOwner { inflationRate = newInflationRate; } /** * @notice Resets the Gat percentage. Note: this change only applies to rounds that have not yet begun. * @dev This method is public because calldata structs are not currently supported by solidity. * @param newGatPercentage sets the next round's Gat percentage. */ function setGatPercentage(FixedPoint.Unsigned memory newGatPercentage) public override(VotingInterface, VotingAncillaryInterface) onlyOwner { require(newGatPercentage.isLessThan(1), "GAT percentage must be < 100%"); gatPercentage = newGatPercentage; } /** * @notice Resets the rewards expiration timeout. * @dev This change only applies to rounds that have not yet begun. * @param NewRewardsExpirationTimeout how long a caller can wait before choosing to withdraw their rewards. */ function setRewardsExpirationTimeout(uint256 NewRewardsExpirationTimeout) public override(VotingInterface, VotingAncillaryInterface) onlyOwner { rewardsExpirationTimeout = NewRewardsExpirationTimeout; } /**************************************** * PRIVATE AND INTERNAL FUNCTIONS * ****************************************/ // Returns the price for a given identifer. Three params are returns: bool if there was an error, int to represent // the resolved price and a string which is filled with an error message, if there was an error or "". function _getPriceOrError( bytes32 identifier, uint256 time, bytes memory ancillaryData ) private view returns ( bool, int256, string memory ) { PriceRequest storage priceRequest = _getPriceRequest(identifier, time, ancillaryData); uint256 currentRoundId = voteTiming.computeCurrentRoundId(getCurrentTime()); RequestStatus requestStatus = _getRequestStatus(priceRequest, currentRoundId); if (requestStatus == RequestStatus.Active) { return (false, 0, "Current voting round not ended"); } else if (requestStatus == RequestStatus.Resolved) { VoteInstance storage voteInstance = priceRequest.voteInstances[priceRequest.lastVotingRound]; (, int256 resolvedPrice) = voteInstance.resultComputation.getResolvedPrice(_computeGat(priceRequest.lastVotingRound)); return (true, resolvedPrice, ""); } else if (requestStatus == RequestStatus.Future) { return (false, 0, "Price is still to be voted on"); } else { return (false, 0, "Price was never requested"); } } function _getPriceRequest( bytes32 identifier, uint256 time, bytes memory ancillaryData ) private view returns (PriceRequest storage) { return priceRequests[_encodePriceRequest(identifier, time, ancillaryData)]; } function _encodePriceRequest( bytes32 identifier, uint256 time, bytes memory ancillaryData ) private pure returns (bytes32) { return keccak256(abi.encode(identifier, time, ancillaryData)); } function _freezeRoundVariables(uint256 roundId) private { Round storage round = rounds[roundId]; // Only on the first reveal should the snapshot be captured for that round. if (round.snapshotId == 0) { // There is no snapshot ID set, so create one. round.snapshotId = votingToken.snapshot(); // Set the round inflation rate to the current global inflation rate. rounds[roundId].inflationRate = inflationRate; // Set the round gat percentage to the current global gat rate. rounds[roundId].gatPercentage = gatPercentage; // Set the rewards expiration time based on end of time of this round and the current global timeout. rounds[roundId].rewardsExpirationTime = voteTiming.computeRoundEndTime(roundId).add( rewardsExpirationTimeout ); } } function _resolvePriceRequest(PriceRequest storage priceRequest, VoteInstance storage voteInstance) private { if (priceRequest.index == UINT_MAX) { return; } (bool isResolved, int256 resolvedPrice) = voteInstance.resultComputation.getResolvedPrice(_computeGat(priceRequest.lastVotingRound)); require(isResolved, "Can't resolve unresolved request"); // Delete the resolved price request from pendingPriceRequests. uint256 lastIndex = pendingPriceRequests.length - 1; PriceRequest storage lastPriceRequest = priceRequests[pendingPriceRequests[lastIndex]]; lastPriceRequest.index = priceRequest.index; pendingPriceRequests[priceRequest.index] = pendingPriceRequests[lastIndex]; pendingPriceRequests.pop(); priceRequest.index = UINT_MAX; emit PriceResolved( priceRequest.lastVotingRound, priceRequest.identifier, priceRequest.time, resolvedPrice, priceRequest.ancillaryData ); } function _computeGat(uint256 roundId) private view returns (FixedPoint.Unsigned memory) { uint256 snapshotId = rounds[roundId].snapshotId; if (snapshotId == 0) { // No snapshot - return max value to err on the side of caution. return FixedPoint.Unsigned(UINT_MAX); } // Grab the snapshotted supply from the voting token. It's already scaled by 10**18, so we can directly // initialize the Unsigned value with the returned uint. FixedPoint.Unsigned memory snapshottedSupply = FixedPoint.Unsigned(votingToken.totalSupplyAt(snapshotId)); // Multiply the total supply at the snapshot by the gatPercentage to get the GAT in number of tokens. return snapshottedSupply.mul(rounds[roundId].gatPercentage); } function _getRequestStatus(PriceRequest storage priceRequest, uint256 currentRoundId) private view returns (RequestStatus) { if (priceRequest.lastVotingRound == 0) { return RequestStatus.NotRequested; } else if (priceRequest.lastVotingRound < currentRoundId) { VoteInstance storage voteInstance = priceRequest.voteInstances[priceRequest.lastVotingRound]; (bool isResolved, ) = voteInstance.resultComputation.getResolvedPrice(_computeGat(priceRequest.lastVotingRound)); return isResolved ? RequestStatus.Resolved : RequestStatus.Active; } else if (priceRequest.lastVotingRound == currentRoundId) { return RequestStatus.Active; } else { // Means than priceRequest.lastVotingRound > currentRoundId return RequestStatus.Future; } } function _getIdentifierWhitelist() private view returns (IdentifierWhitelistInterface supportedIdentifiers) { return IdentifierWhitelistInterface(finder.getImplementationAddress(OracleInterfaces.IdentifierWhitelist)); } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.8.0; /** * @title Provides addresses of the live contracts implementing certain interfaces. * @dev Examples are the Oracle or Store interfaces. */ interface FinderInterface { /** * @notice Updates the address of the contract that implements `interfaceName`. * @param interfaceName bytes32 encoding of the interface name that is either changed or registered. * @param implementationAddress address of the deployed contract that implements the interface. */ function changeImplementationAddress(bytes32 interfaceName, address implementationAddress) external; /** * @notice Gets the address of the contract that implements the given `interfaceName`. * @param interfaceName queried interface. * @return implementationAddress address of the deployed contract that implements the interface. */ function getImplementationAddress(bytes32 interfaceName) external view returns (address); } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.8.0; /** * @title Financial contract facing Oracle interface. * @dev Interface used by financial contracts to interact with the Oracle. Voters will use a different interface. */ abstract contract OracleAncillaryInterface { /** * @notice Enqueues a request (if a request isn't already present) for the given `identifier`, `time` pair. * @dev Time must be in the past and the identifier must be supported. * @param identifier uniquely identifies the price requested. eg BTC/USD (encoded as bytes32) could be requested. * @param ancillaryData arbitrary data appended to a price request to give the voters more info from the caller. * @param time unix timestamp for the price request. */ function requestPrice( bytes32 identifier, uint256 time, bytes memory ancillaryData ) public virtual; /** * @notice Whether the price for `identifier` and `time` is available. * @dev Time must be in the past and the identifier must be supported. * @param identifier uniquely identifies the price requested. eg BTC/USD (encoded as bytes32) could be requested. * @param time unix timestamp for the price request. * @param ancillaryData arbitrary data appended to a price request to give the voters more info from the caller. * @return bool if the DVM has resolved to a price for the given identifier and timestamp. */ function hasPrice( bytes32 identifier, uint256 time, bytes memory ancillaryData ) public view virtual returns (bool); /** * @notice Gets the price for `identifier` and `time` if it has already been requested and resolved. * @dev If the price is not available, the method reverts. * @param identifier uniquely identifies the price requested. eg BTC/USD (encoded as bytes32) could be requested. * @param time unix timestamp for the price request. * @param ancillaryData arbitrary data appended to a price request to give the voters more info from the caller. * @return int256 representing the resolved price for the given identifier and timestamp. */ function getPrice( bytes32 identifier, uint256 time, bytes memory ancillaryData ) public view virtual returns (int256); } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.8.0; pragma abicoder v2; /** * @title Interface for whitelists of supported identifiers that the oracle can provide prices for. */ interface IdentifierWhitelistInterface { /** * @notice Adds the provided identifier as a supported identifier. * @dev Price requests using this identifier will succeed after this call. * @param identifier bytes32 encoding of the string identifier. Eg: BTC/USD. */ function addSupportedIdentifier(bytes32 identifier) external; /** * @notice Removes the identifier from the whitelist. * @dev Price requests using this identifier will no longer succeed after this call. * @param identifier bytes32 encoding of the string identifier. Eg: BTC/USD. */ function removeSupportedIdentifier(bytes32 identifier) external; /** * @notice Checks whether an identifier is on the whitelist. * @param identifier bytes32 encoding of the string identifier. Eg: BTC/USD. * @return bool if the identifier is supported (or not). */ function isIdentifierSupported(bytes32 identifier) external view returns (bool); } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.8.0; pragma abicoder v2; import "../../common/implementation/MultiRole.sol"; import "../interfaces/RegistryInterface.sol"; import "@openzeppelin/contracts/utils/math/SafeMath.sol"; /** * @title Registry for financial contracts and approved financial contract creators. * @dev Maintains a whitelist of financial contract creators that are allowed * to register new financial contracts and stores party members of a financial contract. */ contract Registry is RegistryInterface, MultiRole { using SafeMath for uint256; /**************************************** * INTERNAL VARIABLES AND STORAGE * ****************************************/ enum Roles { Owner, // The owner manages the set of ContractCreators. ContractCreator // Can register financial contracts. } // This enum is required because a `WasValid` state is required // to ensure that financial contracts cannot be re-registered. enum Validity { Invalid, Valid } // Local information about a contract. struct FinancialContract { Validity valid; uint128 index; } struct Party { address[] contracts; // Each financial contract address is stored in this array. // The address of each financial contract is mapped to its index for constant time look up and deletion. mapping(address => uint256) contractIndex; } // Array of all contracts that are approved to use the UMA Oracle. address[] public registeredContracts; // Map of financial contract contracts to the associated FinancialContract struct. mapping(address => FinancialContract) public contractMap; // Map each party member to their their associated Party struct. mapping(address => Party) private partyMap; /**************************************** * EVENTS * ****************************************/ event NewContractRegistered(address indexed contractAddress, address indexed creator, address[] parties); event PartyAdded(address indexed contractAddress, address indexed party); event PartyRemoved(address indexed contractAddress, address indexed party); /** * @notice Construct the Registry contract. */ constructor() { _createExclusiveRole(uint256(Roles.Owner), uint256(Roles.Owner), msg.sender); // Start with no contract creators registered. _createSharedRole(uint256(Roles.ContractCreator), uint256(Roles.Owner), new address[](0)); } /**************************************** * REGISTRATION FUNCTIONS * ****************************************/ /** * @notice Registers a new financial contract. * @dev Only authorized contract creators can call this method. * @param parties array of addresses who become parties in the contract. * @param contractAddress address of the contract against which the parties are registered. */ function registerContract(address[] calldata parties, address contractAddress) external override onlyRoleHolder(uint256(Roles.ContractCreator)) { FinancialContract storage financialContract = contractMap[contractAddress]; require(contractMap[contractAddress].valid == Validity.Invalid, "Can only register once"); // Store contract address as a registered contract. registeredContracts.push(contractAddress); // No length check necessary because we should never hit (2^127 - 1) contracts. financialContract.index = uint128(registeredContracts.length.sub(1)); // For all parties in the array add them to the contract's parties. financialContract.valid = Validity.Valid; for (uint256 i = 0; i < parties.length; i = i.add(1)) { _addPartyToContract(parties[i], contractAddress); } emit NewContractRegistered(contractAddress, msg.sender, parties); } /** * @notice Adds a party member to the calling contract. * @dev msg.sender will be used to determine the contract that this party is added to. * @param party new party for the calling contract. */ function addPartyToContract(address party) external override { address contractAddress = msg.sender; require(contractMap[contractAddress].valid == Validity.Valid, "Can only add to valid contract"); _addPartyToContract(party, contractAddress); } /** * @notice Removes a party member from the calling contract. * @dev msg.sender will be used to determine the contract that this party is removed from. * @param partyAddress address to be removed from the calling contract. */ function removePartyFromContract(address partyAddress) external override { address contractAddress = msg.sender; Party storage party = partyMap[partyAddress]; uint256 numberOfContracts = party.contracts.length; require(numberOfContracts != 0, "Party has no contracts"); require(contractMap[contractAddress].valid == Validity.Valid, "Remove only from valid contract"); require(isPartyMemberOfContract(partyAddress, contractAddress), "Can only remove existing party"); // Index of the current location of the contract to remove. uint256 deleteIndex = party.contractIndex[contractAddress]; // Store the last contract's address to update the lookup map. address lastContractAddress = party.contracts[numberOfContracts - 1]; // Swap the contract to be removed with the last contract. party.contracts[deleteIndex] = lastContractAddress; // Update the lookup index with the new location. party.contractIndex[lastContractAddress] = deleteIndex; // Pop the last contract from the array and update the lookup map. party.contracts.pop(); delete party.contractIndex[contractAddress]; emit PartyRemoved(contractAddress, partyAddress); } /**************************************** * REGISTRY STATE GETTERS * ****************************************/ /** * @notice Returns whether the contract has been registered with the registry. * @dev If it is registered, it is an authorized participant in the UMA system. * @param contractAddress address of the financial contract. * @return bool indicates whether the contract is registered. */ function isContractRegistered(address contractAddress) external view override returns (bool) { return contractMap[contractAddress].valid == Validity.Valid; } /** * @notice Returns a list of all contracts that are associated with a particular party. * @param party address of the party. * @return an array of the contracts the party is registered to. */ function getRegisteredContracts(address party) external view override returns (address[] memory) { return partyMap[party].contracts; } /** * @notice Returns all registered contracts. * @return all registered contract addresses within the system. */ function getAllRegisteredContracts() external view override returns (address[] memory) { return registeredContracts; } /** * @notice checks if an address is a party of a contract. * @param party party to check. * @param contractAddress address to check against the party. * @return bool indicating if the address is a party of the contract. */ function isPartyMemberOfContract(address party, address contractAddress) public view override returns (bool) { uint256 index = partyMap[party].contractIndex[contractAddress]; return partyMap[party].contracts.length > index && partyMap[party].contracts[index] == contractAddress; } /**************************************** * INTERNAL FUNCTIONS * ****************************************/ function _addPartyToContract(address party, address contractAddress) internal { require(!isPartyMemberOfContract(party, contractAddress), "Can only register a party once"); uint256 contractIndex = partyMap[party].contracts.length; partyMap[party].contracts.push(contractAddress); partyMap[party].contractIndex[contractAddress] = contractIndex; emit PartyAdded(contractAddress, party); } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.8.0; import "../../common/implementation/FixedPoint.sol"; /** * @title Computes vote results. * @dev The result is the mode of the added votes. Otherwise, the vote is unresolved. */ library ResultComputation { using FixedPoint for FixedPoint.Unsigned; /**************************************** * INTERNAL LIBRARY DATA STRUCTURE * ****************************************/ struct Data { // Maps price to number of tokens that voted for that price. mapping(int256 => FixedPoint.Unsigned) voteFrequency; // The total votes that have been added. FixedPoint.Unsigned totalVotes; // The price that is the current mode, i.e., the price with the highest frequency in `voteFrequency`. int256 currentMode; } /**************************************** * VOTING FUNCTIONS * ****************************************/ /** * @notice Adds a new vote to be used when computing the result. * @param data contains information to which the vote is applied. * @param votePrice value specified in the vote for the given `numberTokens`. * @param numberTokens number of tokens that voted on the `votePrice`. */ function addVote( Data storage data, int256 votePrice, FixedPoint.Unsigned memory numberTokens ) internal { data.totalVotes = data.totalVotes.add(numberTokens); data.voteFrequency[votePrice] = data.voteFrequency[votePrice].add(numberTokens); if ( votePrice != data.currentMode && data.voteFrequency[votePrice].isGreaterThan(data.voteFrequency[data.currentMode]) ) { data.currentMode = votePrice; } } /**************************************** * VOTING STATE GETTERS * ****************************************/ /** * @notice Returns whether the result is resolved, and if so, what value it resolved to. * @dev `price` should be ignored if `isResolved` is false. * @param data contains information against which the `minVoteThreshold` is applied. * @param minVoteThreshold min (exclusive) number of tokens that must have voted for the result to be valid. Can be * used to enforce a minimum voter participation rate, regardless of how the votes are distributed. * @return isResolved indicates if the price has been resolved correctly. * @return price the price that the dvm resolved to. */ function getResolvedPrice(Data storage data, FixedPoint.Unsigned memory minVoteThreshold) internal view returns (bool isResolved, int256 price) { FixedPoint.Unsigned memory modeThreshold = FixedPoint.fromUnscaledUint(50).div(100); if ( data.totalVotes.isGreaterThan(minVoteThreshold) && data.voteFrequency[data.currentMode].div(data.totalVotes).isGreaterThan(modeThreshold) ) { // `modeThreshold` and `minVoteThreshold` are exceeded, so the current mode is the resolved price. isResolved = true; price = data.currentMode; } else { isResolved = false; } } /** * @notice Checks whether a `voteHash` is considered correct. * @dev Should only be called after a vote is resolved, i.e., via `getResolvedPrice`. * @param data contains information against which the `voteHash` is checked. * @param voteHash committed hash submitted by the voter. * @return bool true if the vote was correct. */ function wasVoteCorrect(Data storage data, bytes32 voteHash) internal view returns (bool) { return voteHash == keccak256(abi.encode(data.currentMode)); } /** * @notice Gets the total number of tokens whose votes are considered correct. * @dev Should only be called after a vote is resolved, i.e., via `getResolvedPrice`. * @param data contains all votes against which the correctly voted tokens are counted. * @return FixedPoint.Unsigned which indicates the frequency of the correctly voted tokens. */ function getTotalCorrectlyVotedTokens(Data storage data) internal view returns (FixedPoint.Unsigned memory) { return data.voteFrequency[data.currentMode]; } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.8.0; import "@openzeppelin/contracts/utils/math/SafeMath.sol"; import "../interfaces/VotingInterface.sol"; /** * @title Library to compute rounds and phases for an equal length commit-reveal voting cycle. */ library VoteTiming { using SafeMath for uint256; struct Data { uint256 phaseLength; } /** * @notice Initializes the data object. Sets the phase length based on the input. */ function init(Data storage data, uint256 phaseLength) internal { // This should have a require message but this results in an internal Solidity error. require(phaseLength > 0); data.phaseLength = phaseLength; } /** * @notice Computes the roundID based off the current time as floor(timestamp/roundLength). * @dev The round ID depends on the global timestamp but not on the lifetime of the system. * The consequence is that the initial round ID starts at an arbitrary number (that increments, as expected, for subsequent rounds) instead of zero or one. * @param data input data object. * @param currentTime input unix timestamp used to compute the current roundId. * @return roundId defined as a function of the currentTime and `phaseLength` from `data`. */ function computeCurrentRoundId(Data storage data, uint256 currentTime) internal view returns (uint256) { uint256 roundLength = data.phaseLength.mul(uint256(VotingAncillaryInterface.Phase.NUM_PHASES_PLACEHOLDER)); return currentTime.div(roundLength); } /** * @notice compute the round end time as a function of the round Id. * @param data input data object. * @param roundId uniquely identifies the current round. * @return timestamp unix time of when the current round will end. */ function computeRoundEndTime(Data storage data, uint256 roundId) internal view returns (uint256) { uint256 roundLength = data.phaseLength.mul(uint256(VotingAncillaryInterface.Phase.NUM_PHASES_PLACEHOLDER)); return roundLength.mul(roundId.add(1)); } /** * @notice Computes the current phase based only on the current time. * @param data input data object. * @param currentTime input unix timestamp used to compute the current roundId. * @return current voting phase based on current time and vote phases configuration. */ function computeCurrentPhase(Data storage data, uint256 currentTime) internal view returns (VotingAncillaryInterface.Phase) { // This employs some hacky casting. We could make this an if-statement if we're worried about type safety. return VotingAncillaryInterface.Phase( currentTime.div(data.phaseLength).mod(uint256(VotingAncillaryInterface.Phase.NUM_PHASES_PLACEHOLDER)) ); } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.8.0; import "../../common/implementation/ExpandedERC20.sol"; import "@openzeppelin/contracts/token/ERC20/extensions/ERC20Snapshot.sol"; /** * @title Ownership of this token allows a voter to respond to price requests. * @dev Supports snapshotting and allows the Oracle to mint new tokens as rewards. */ contract VotingToken is ExpandedERC20, ERC20Snapshot { /** * @notice Constructs the VotingToken. */ constructor() ExpandedERC20("UMA Voting Token v1", "UMA", 18) ERC20Snapshot() {} function decimals() public view virtual override(ERC20, ExpandedERC20) returns (uint8) { return super.decimals(); } /** * @notice Creates a new snapshot ID. * @return uint256 Thew new snapshot ID. */ function snapshot() external returns (uint256) { return _snapshot(); } // _transfer, _mint and _burn are ERC20 internal methods that are overridden by ERC20Snapshot, // therefore the compiler will complain that VotingToken must override these methods // because the two base classes (ERC20 and ERC20Snapshot) both define the same functions function _transfer( address from, address to, uint256 value ) internal override(ERC20) { super._transfer(from, to, value); } function _mint(address account, uint256 value) internal virtual override(ERC20) { super._mint(account, value); } function _burn(address account, uint256 value) internal virtual override(ERC20) { super._burn(account, value); } function _beforeTokenTransfer( address from, address to, uint256 amount ) internal virtual override(ERC20, ERC20Snapshot) { super._beforeTokenTransfer(from, to, amount); } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.8.0; /** * @title Stores common interface names used throughout the DVM by registration in the Finder. */ library OracleInterfaces { bytes32 public constant Oracle = "Oracle"; bytes32 public constant IdentifierWhitelist = "IdentifierWhitelist"; bytes32 public constant Store = "Store"; bytes32 public constant FinancialContractsAdmin = "FinancialContractsAdmin"; bytes32 public constant Registry = "Registry"; bytes32 public constant CollateralWhitelist = "CollateralWhitelist"; bytes32 public constant OptimisticOracle = "OptimisticOracle"; bytes32 public constant Bridge = "Bridge"; bytes32 public constant GenericHandler = "GenericHandler"; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../utils/Context.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor () { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Elliptic Curve Digital Signature Algorithm (ECDSA) operations. * * These functions can be used to verify that a message was signed by the holder * of the private keys of a given address. */ library ECDSA { /** * @dev Returns the address that signed a hashed message (`hash`) with * `signature`. This address can then be used for verification purposes. * * The `ecrecover` EVM opcode allows for malleable (non-unique) signatures: * this function rejects them by requiring the `s` value to be in the lower * half order, and the `v` value to be either 27 or 28. * * IMPORTANT: `hash` _must_ be the result of a hash operation for the * verification to be secure: it is possible to craft signatures that * recover to arbitrary addresses for non-hashed data. A safe way to ensure * this is by receiving a hash of the original message (which may otherwise * be too long), and then calling {toEthSignedMessageHash} on it. */ function recover(bytes32 hash, bytes memory signature) internal pure returns (address) { // Divide the signature in r, s and v variables bytes32 r; bytes32 s; uint8 v; // Check the signature length // - case 65: r,s,v signature (standard) // - case 64: r,vs signature (cf https://eips.ethereum.org/EIPS/eip-2098) _Available since v4.1._ if (signature.length == 65) { // ecrecover takes the signature parameters, and the only way to get them // currently is to use assembly. // solhint-disable-next-line no-inline-assembly assembly { r := mload(add(signature, 0x20)) s := mload(add(signature, 0x40)) v := byte(0, mload(add(signature, 0x60))) } } else if (signature.length == 64) { // ecrecover takes the signature parameters, and the only way to get them // currently is to use assembly. // solhint-disable-next-line no-inline-assembly assembly { let vs := mload(add(signature, 0x40)) r := mload(add(signature, 0x20)) s := and(vs, 0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff) v := add(shr(255, vs), 27) } } else { revert("ECDSA: invalid signature length"); } return recover(hash, v, r, s); } /** * @dev Overload of {ECDSA-recover} that receives the `v`, * `r` and `s` signature fields separately. */ function recover(bytes32 hash, uint8 v, bytes32 r, bytes32 s) internal pure returns (address) { // EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature // unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines // the valid range for s in (281): 0 < s < secp256k1n ÷ 2 + 1, and for v in (282): v ∈ {27, 28}. Most // signatures from current libraries generate a unique signature with an s-value in the lower half order. // // If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value // with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or // vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept // these malleable signatures as well. require(uint256(s) <= 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0, "ECDSA: invalid signature 's' value"); require(v == 27 || v == 28, "ECDSA: invalid signature 'v' value"); // If the signature is valid (and not malleable), return the signer address address signer = ecrecover(hash, v, r, s); require(signer != address(0), "ECDSA: invalid signature"); return signer; } /** * @dev Returns an Ethereum Signed Message, created from a `hash`. This * 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: AGPL-3.0-only pragma solidity ^0.8.0; library Exclusive { struct RoleMembership { address member; } function isMember(RoleMembership storage roleMembership, address memberToCheck) internal view returns (bool) { return roleMembership.member == memberToCheck; } function resetMember(RoleMembership storage roleMembership, address newMember) internal { require(newMember != address(0x0), "Cannot set an exclusive role to 0x0"); roleMembership.member = newMember; } function getMember(RoleMembership storage roleMembership) internal view returns (address) { return roleMembership.member; } function init(RoleMembership storage roleMembership, address initialMember) internal { resetMember(roleMembership, initialMember); } } library Shared { struct RoleMembership { mapping(address => bool) members; } function isMember(RoleMembership storage roleMembership, address memberToCheck) internal view returns (bool) { return roleMembership.members[memberToCheck]; } function addMember(RoleMembership storage roleMembership, address memberToAdd) internal { require(memberToAdd != address(0x0), "Cannot add 0x0 to a shared role"); roleMembership.members[memberToAdd] = true; } function removeMember(RoleMembership storage roleMembership, address memberToRemove) internal { roleMembership.members[memberToRemove] = false; } function init(RoleMembership storage roleMembership, address[] memory initialMembers) internal { for (uint256 i = 0; i < initialMembers.length; i++) { addMember(roleMembership, initialMembers[i]); } } } /** * @title Base class to manage permissions for the derived class. */ abstract contract MultiRole { using Exclusive for Exclusive.RoleMembership; using Shared for Shared.RoleMembership; enum RoleType { Invalid, Exclusive, Shared } struct Role { uint256 managingRole; RoleType roleType; Exclusive.RoleMembership exclusiveRoleMembership; Shared.RoleMembership sharedRoleMembership; } mapping(uint256 => Role) private roles; event ResetExclusiveMember(uint256 indexed roleId, address indexed newMember, address indexed manager); event AddedSharedMember(uint256 indexed roleId, address indexed newMember, address indexed manager); event RemovedSharedMember(uint256 indexed roleId, address indexed oldMember, address indexed manager); /** * @notice Reverts unless the caller is a member of the specified roleId. */ modifier onlyRoleHolder(uint256 roleId) { require(holdsRole(roleId, msg.sender), "Sender does not hold required role"); _; } /** * @notice Reverts unless the caller is a member of the manager role for the specified roleId. */ modifier onlyRoleManager(uint256 roleId) { require(holdsRole(roles[roleId].managingRole, msg.sender), "Can only be called by a role manager"); _; } /** * @notice Reverts unless the roleId represents an initialized, exclusive roleId. */ modifier onlyExclusive(uint256 roleId) { require(roles[roleId].roleType == RoleType.Exclusive, "Must be called on an initialized Exclusive role"); _; } /** * @notice Reverts unless the roleId represents an initialized, shared roleId. */ modifier onlyShared(uint256 roleId) { require(roles[roleId].roleType == RoleType.Shared, "Must be called on an initialized Shared role"); _; } /** * @notice Whether `memberToCheck` is a member of roleId. * @dev Reverts if roleId does not correspond to an initialized role. * @param roleId the Role to check. * @param memberToCheck the address to check. * @return True if `memberToCheck` is a member of `roleId`. */ function holdsRole(uint256 roleId, address memberToCheck) public view returns (bool) { Role storage role = roles[roleId]; if (role.roleType == RoleType.Exclusive) { return role.exclusiveRoleMembership.isMember(memberToCheck); } else if (role.roleType == RoleType.Shared) { return role.sharedRoleMembership.isMember(memberToCheck); } revert("Invalid roleId"); } /** * @notice Changes the exclusive role holder of `roleId` to `newMember`. * @dev Reverts if the caller is not a member of the managing role for `roleId` or if `roleId` is not an * initialized, ExclusiveRole. * @param roleId the ExclusiveRole membership to modify. * @param newMember the new ExclusiveRole member. */ function resetMember(uint256 roleId, address newMember) public onlyExclusive(roleId) onlyRoleManager(roleId) { roles[roleId].exclusiveRoleMembership.resetMember(newMember); emit ResetExclusiveMember(roleId, newMember, msg.sender); } /** * @notice Gets the current holder of the exclusive role, `roleId`. * @dev Reverts if `roleId` does not represent an initialized, exclusive role. * @param roleId the ExclusiveRole membership to check. * @return the address of the current ExclusiveRole member. */ function getMember(uint256 roleId) public view onlyExclusive(roleId) returns (address) { return roles[roleId].exclusiveRoleMembership.getMember(); } /** * @notice Adds `newMember` to the shared role, `roleId`. * @dev Reverts if `roleId` does not represent an initialized, SharedRole or if the caller is not a member of the * managing role for `roleId`. * @param roleId the SharedRole membership to modify. * @param newMember the new SharedRole member. */ function addMember(uint256 roleId, address newMember) public onlyShared(roleId) onlyRoleManager(roleId) { roles[roleId].sharedRoleMembership.addMember(newMember); emit AddedSharedMember(roleId, newMember, msg.sender); } /** * @notice Removes `memberToRemove` from the shared role, `roleId`. * @dev Reverts if `roleId` does not represent an initialized, SharedRole or if the caller is not a member of the * managing role for `roleId`. * @param roleId the SharedRole membership to modify. * @param memberToRemove the current SharedRole member to remove. */ function removeMember(uint256 roleId, address memberToRemove) public onlyShared(roleId) onlyRoleManager(roleId) { roles[roleId].sharedRoleMembership.removeMember(memberToRemove); emit RemovedSharedMember(roleId, memberToRemove, msg.sender); } /** * @notice Removes caller from the role, `roleId`. * @dev Reverts if the caller is not a member of the role for `roleId` or if `roleId` is not an * initialized, SharedRole. * @param roleId the SharedRole membership to modify. */ function renounceMembership(uint256 roleId) public onlyShared(roleId) onlyRoleHolder(roleId) { roles[roleId].sharedRoleMembership.removeMember(msg.sender); emit RemovedSharedMember(roleId, msg.sender, msg.sender); } /** * @notice Reverts if `roleId` is not initialized. */ modifier onlyValidRole(uint256 roleId) { require(roles[roleId].roleType != RoleType.Invalid, "Attempted to use an invalid roleId"); _; } /** * @notice Reverts if `roleId` is initialized. */ modifier onlyInvalidRole(uint256 roleId) { require(roles[roleId].roleType == RoleType.Invalid, "Cannot use a pre-existing role"); _; } /** * @notice Internal method to initialize a shared role, `roleId`, which will be managed by `managingRoleId`. * `initialMembers` will be immediately added to the role. * @dev Should be called by derived contracts, usually at construction time. Will revert if the role is already * initialized. */ function _createSharedRole( uint256 roleId, uint256 managingRoleId, address[] memory initialMembers ) internal onlyInvalidRole(roleId) { Role storage role = roles[roleId]; role.roleType = RoleType.Shared; role.managingRole = managingRoleId; role.sharedRoleMembership.init(initialMembers); require( roles[managingRoleId].roleType != RoleType.Invalid, "Attempted to use an invalid role to manage a shared role" ); } /** * @notice Internal method to initialize an exclusive role, `roleId`, which will be managed by `managingRoleId`. * `initialMember` will be immediately added to the role. * @dev Should be called by derived contracts, usually at construction time. Will revert if the role is already * initialized. */ function _createExclusiveRole( uint256 roleId, uint256 managingRoleId, address initialMember ) internal onlyInvalidRole(roleId) { Role storage role = roles[roleId]; role.roleType = RoleType.Exclusive; role.managingRole = managingRoleId; role.exclusiveRoleMembership.init(initialMember); require( roles[managingRoleId].roleType != RoleType.Invalid, "Attempted to use an invalid role to manage an exclusive role" ); } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.8.0; pragma abicoder v2; /** * @title Interface for a registry of contracts and contract creators. */ interface RegistryInterface { /** * @notice Registers a new contract. * @dev Only authorized contract creators can call this method. * @param parties an array of addresses who become parties in the contract. * @param contractAddress defines the address of the deployed contract. */ function registerContract(address[] calldata parties, address contractAddress) external; /** * @notice Returns whether the contract has been registered with the registry. * @dev If it is registered, it is an authorized participant in the UMA system. * @param contractAddress address of the contract. * @return bool indicates whether the contract is registered. */ function isContractRegistered(address contractAddress) external view returns (bool); /** * @notice Returns a list of all contracts that are associated with a particular party. * @param party address of the party. * @return an array of the contracts the party is registered to. */ function getRegisteredContracts(address party) external view returns (address[] memory); /** * @notice Returns all registered contracts. * @return all registered contract addresses within the system. */ function getAllRegisteredContracts() external view returns (address[] memory); /** * @notice Adds a party to the calling contract. * @dev msg.sender must be the contract to which the party member is added. * @param party address to be added to the contract. */ function addPartyToContract(address party) external; /** * @notice Removes a party member to the calling contract. * @dev msg.sender must be the contract to which the party member is added. * @param party address to be removed from the contract. */ function removePartyFromContract(address party) external; /** * @notice checks if an address is a party in a contract. * @param party party to check. * @param contractAddress address to check against the party. * @return bool indicating if the address is a party of the contract. */ function isPartyMemberOfContract(address party, address contractAddress) external view returns (bool); } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.8.0; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "./MultiRole.sol"; import "../interfaces/ExpandedIERC20.sol"; /** * @title An ERC20 with permissioned burning and minting. The contract deployer will initially * be the owner who is capable of adding new roles. */ contract ExpandedERC20 is ExpandedIERC20, ERC20, MultiRole { enum Roles { // Can set the minter and burner. Owner, // Addresses that can mint new tokens. Minter, // Addresses that can burn tokens that address owns. Burner } uint8 _decimals; /** * @notice Constructs the ExpandedERC20. * @param _tokenName The name which describes the new token. * @param _tokenSymbol The ticker abbreviation of the name. Ideally < 5 chars. * @param _tokenDecimals The number of decimals to define token precision. */ constructor( string memory _tokenName, string memory _tokenSymbol, uint8 _tokenDecimals ) ERC20(_tokenName, _tokenSymbol) { _decimals = _tokenDecimals; _createExclusiveRole(uint256(Roles.Owner), uint256(Roles.Owner), msg.sender); _createSharedRole(uint256(Roles.Minter), uint256(Roles.Owner), new address[](0)); _createSharedRole(uint256(Roles.Burner), uint256(Roles.Owner), new address[](0)); } function decimals() public view virtual override(ERC20) returns (uint8) { return _decimals; } /** * @dev Mints `value` tokens to `recipient`, returning true on success. * @param recipient address to mint to. * @param value amount of tokens to mint. * @return True if the mint succeeded, or False. */ function mint(address recipient, uint256 value) external override onlyRoleHolder(uint256(Roles.Minter)) returns (bool) { _mint(recipient, value); return true; } /** * @dev Burns `value` tokens owned by `msg.sender`. * @param value amount of tokens to burn. */ function burn(uint256 value) external override onlyRoleHolder(uint256(Roles.Burner)) { _burn(msg.sender, value); } /** * @notice Add Minter role to account. * @dev The caller must have the Owner role. * @param account The address to which the Minter role is added. */ function addMinter(address account) external virtual override { addMember(uint256(Roles.Minter), account); } /** * @notice Add Burner role to account. * @dev The caller must have the Owner role. * @param account The address to which the Burner role is added. */ function addBurner(address account) external virtual override { addMember(uint256(Roles.Burner), account); } /** * @notice Reset Owner role to account. * @dev The caller must have the Owner role. * @param account The new holder of the Owner role. */ function resetOwner(address account) external virtual override { resetMember(uint256(Roles.Owner), account); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../ERC20.sol"; import "../../../utils/Arrays.sol"; import "../../../utils/Counters.sol"; /** * @dev This contract extends an ERC20 token with a snapshot mechanism. When a snapshot is created, the balances and * total supply at the time are recorded for later access. * * This can be used to safely create mechanisms based on token balances such as trustless dividends or weighted voting. * In naive implementations it's possible to perform a "double spend" attack by reusing the same balance from different * accounts. By using snapshots to calculate dividends or voting power, those attacks no longer apply. It can also be * used to create an efficient ERC20 forking mechanism. * * Snapshots are created by the internal {_snapshot} function, which will emit the {Snapshot} event and return a * snapshot id. To get the total supply at the time of a snapshot, call the function {totalSupplyAt} with the snapshot * id. To get the balance of an account at the time of a snapshot, call the {balanceOfAt} function with the snapshot id * and the account address. * * ==== Gas Costs * * Snapshots are efficient. Snapshot creation is _O(1)_. Retrieval of balances or total supply from a snapshot is _O(log * n)_ in the number of snapshots that have been created, although _n_ for a specific account will generally be much * smaller since identical balances in subsequent snapshots are stored as a single entry. * * There is a constant overhead for normal ERC20 transfers due to the additional snapshot bookkeeping. This overhead is * only significant for the first transfer that immediately follows a snapshot for a particular account. Subsequent * transfers will have normal cost until the next snapshot, and so on. */ abstract contract ERC20Snapshot is ERC20 { // Inspired by Jordi Baylina's MiniMeToken to record historical balances: // https://github.com/Giveth/minimd/blob/ea04d950eea153a04c51fa510b068b9dded390cb/contracts/MiniMeToken.sol using Arrays for uint256[]; using Counters for Counters.Counter; // Snapshotted values have arrays of ids and the value corresponding to that id. These could be an array of a // Snapshot struct, but that would impede usage of functions that work on an array. struct Snapshots { uint256[] ids; uint256[] values; } mapping (address => Snapshots) private _accountBalanceSnapshots; Snapshots private _totalSupplySnapshots; // Snapshot ids increase monotonically, with the first value being 1. An id of 0 is invalid. Counters.Counter private _currentSnapshotId; /** * @dev Emitted by {_snapshot} when a snapshot identified by `id` is created. */ event Snapshot(uint256 id); /** * @dev Creates a new snapshot and returns its snapshot id. * * Emits a {Snapshot} event that contains the same id. * * {_snapshot} is `internal` and you have to decide how to expose it externally. Its usage may be restricted to a * set of accounts, for example using {AccessControl}, or it may be open to the public. * * [WARNING] * ==== * While an open way of calling {_snapshot} is required for certain trust minimization mechanisms such as forking, * you must consider that it can potentially be used by attackers in two ways. * * First, it can be used to increase the cost of retrieval of values from snapshots, although it will grow * logarithmically thus rendering this attack ineffective in the long term. Second, it can be used to target * specific accounts and increase the cost of ERC20 transfers for them, in the ways specified in the Gas Costs * section above. * * We haven't measured the actual numbers; if this is something you're interested in please reach out to us. * ==== */ function _snapshot() internal virtual returns (uint256) { _currentSnapshotId.increment(); uint256 currentId = _currentSnapshotId.current(); emit Snapshot(currentId); return currentId; } /** * @dev Retrieves the balance of `account` at the time `snapshotId` was created. */ function balanceOfAt(address account, uint256 snapshotId) public view virtual returns (uint256) { (bool snapshotted, uint256 value) = _valueAt(snapshotId, _accountBalanceSnapshots[account]); return snapshotted ? value : balanceOf(account); } /** * @dev Retrieves the total supply at the time `snapshotId` was created. */ function totalSupplyAt(uint256 snapshotId) public view virtual returns(uint256) { (bool snapshotted, uint256 value) = _valueAt(snapshotId, _totalSupplySnapshots); return snapshotted ? value : totalSupply(); } // Update balance and/or total supply snapshots before the values are modified. This is implemented // in the _beforeTokenTransfer hook, which is executed for _mint, _burn, and _transfer operations. function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual override { super._beforeTokenTransfer(from, to, amount); if (from == address(0)) { // mint _updateAccountSnapshot(to); _updateTotalSupplySnapshot(); } else if (to == address(0)) { // burn _updateAccountSnapshot(from); _updateTotalSupplySnapshot(); } else { // transfer _updateAccountSnapshot(from); _updateAccountSnapshot(to); } } function _valueAt(uint256 snapshotId, Snapshots storage snapshots) private view returns (bool, uint256) { require(snapshotId > 0, "ERC20Snapshot: id is 0"); // solhint-disable-next-line max-line-length require(snapshotId <= _currentSnapshotId.current(), "ERC20Snapshot: nonexistent id"); // When a valid snapshot is queried, there are three possibilities: // a) The queried value was not modified after the snapshot was taken. Therefore, a snapshot entry was never // created for this id, and all stored snapshot ids are smaller than the requested one. The value that corresponds // to this id is the current one. // b) The queried value was modified after the snapshot was taken. Therefore, there will be an entry with the // requested id, and its value is the one to return. // c) More snapshots were created after the requested one, and the queried value was later modified. There will be // no entry for the requested id: the value that corresponds to it is that of the smallest snapshot id that is // larger than the requested one. // // In summary, we need to find an element in an array, returning the index of the smallest value that is larger if // it is not found, unless said value doesn't exist (e.g. when all values are smaller). Arrays.findUpperBound does // exactly this. uint256 index = snapshots.ids.findUpperBound(snapshotId); if (index == snapshots.ids.length) { return (false, 0); } else { return (true, snapshots.values[index]); } } function _updateAccountSnapshot(address account) private { _updateSnapshot(_accountBalanceSnapshots[account], balanceOf(account)); } function _updateTotalSupplySnapshot() private { _updateSnapshot(_totalSupplySnapshots, totalSupply()); } function _updateSnapshot(Snapshots storage snapshots, uint256 currentValue) private { uint256 currentId = _currentSnapshotId.current(); if (_lastSnapshotId(snapshots.ids) < currentId) { snapshots.ids.push(currentId); snapshots.values.push(currentValue); } } function _lastSnapshotId(uint256[] storage ids) private view returns (uint256) { if (ids.length == 0) { return 0; } else { return ids[ids.length - 1]; } } } // 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 guidelines: functions revert instead * of returning `false` on failure. This behavior is nonetheless conventional * and does not conflict with the expectations of ERC20 applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */ contract ERC20 is Context, IERC20, IERC20Metadata { mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; /** * @dev Sets the values for {name} and {symbol}. * * The defaut value of {decimals} is 18. To select a different value for * {decimals} you should overload it. * * All two of these values are immutable: they can only be set once during * construction. */ constructor (string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @dev Returns the name of the token. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless this function is * overridden; * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view virtual override returns (uint8) { return 18; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view virtual override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}. * * Requirements: * * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) { _transfer(sender, recipient, amount); uint256 currentAllowance = _allowances[sender][_msgSender()]; require(currentAllowance >= amount, "ERC20: transfer amount exceeds allowance"); _approve(sender, _msgSender(), currentAllowance - amount); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender] + addedValue); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { uint256 currentAllowance = _allowances[_msgSender()][spender]; require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero"); _approve(_msgSender(), spender, currentAllowance - subtractedValue); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer(address sender, address recipient, uint256 amount) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); uint256 senderBalance = _balances[sender]; require(senderBalance >= amount, "ERC20: transfer amount exceeds balance"); _balances[sender] = senderBalance - amount; _balances[recipient] += amount; emit Transfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements: * * - `to` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply += amount; _balances[account] += amount; emit Transfer(address(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 { } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.8.0; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; /** * @title ERC20 interface that includes burn and mint methods. */ abstract contract ExpandedIERC20 is IERC20 { /** * @notice Burns a specific amount of the caller's tokens. * @dev Only burns the caller's tokens, so it is safe to leave this method permissionless. */ function burn(uint256 value) external virtual; /** * @notice Mints tokens and adds them to the balance of the `to` address. * @dev This method should be permissioned to only allow designated parties to mint tokens. */ function mint(address to, uint256 value) external virtual returns (bool); function addMinter(address account) external virtual; function addBurner(address account) external virtual; function resetOwner(address account) external virtual; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../IERC20.sol"; /** * @dev Interface for the optional metadata functions from the ERC20 standard. * * _Available since v4.1._ */ interface IERC20Metadata is IERC20 { /** * @dev Returns the name of the token. */ function name() external view returns (string memory); /** * @dev Returns the symbol of the token. */ function symbol() external view returns (string memory); /** * @dev Returns the decimals places of the token. */ function decimals() external view returns (uint8); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./math/Math.sol"; /** * @dev Collection of functions related to array types. */ library Arrays { /** * @dev Searches a sorted `array` and returns the first index that contains * a value greater or equal to `element`. If no such index exists (i.e. all * values in the array are strictly less than `element`), the array length is * returned. Time complexity O(log n). * * `array` is expected to be sorted in ascending order, and to contain no * repeated elements. */ function findUpperBound(uint256[] storage array, uint256 element) internal view returns (uint256) { if (array.length == 0) { return 0; } uint256 low = 0; uint256 high = array.length; while (low < high) { uint256 mid = Math.average(low, high); // Note that mid will always be strictly less than high (i.e. it will be a valid array index) // because Math.average rounds down (it does integer division with truncation). if (array[mid] > element) { high = mid; } else { low = mid + 1; } } // At this point `low` is the exclusive upper bound. We will return the inclusive upper bound. if (low > 0 && array[low - 1] == element) { return low - 1; } else { return low; } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @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;` */ 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; } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Standard math utilities missing in the Solidity language. */ library Math { /** * @dev Returns the largest of two numbers. */ function max(uint256 a, uint256 b) internal pure returns (uint256) { return a >= b ? a : b; } /** * @dev Returns the smallest of two numbers. */ function min(uint256 a, uint256 b) internal pure returns (uint256) { return a < b ? a : b; } /** * @dev Returns the average of two numbers. The result is rounded towards * zero. */ function average(uint256 a, uint256 b) internal pure returns (uint256) { // (a + b) / 2 can overflow, so we distribute return (a / 2) + (b / 2) + ((a % 2 + b % 2) / 2); } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.8.0; import "../oracle/implementation/Finder.sol"; import "../oracle/implementation/Constants.sol"; import "../oracle/implementation/Voting.sol"; /** * @title A contract that executes a short series of upgrade calls that must be performed atomically as a part of the * upgrade process for Voting.sol. * @dev Note: the complete upgrade process requires more than just the transactions in this contract. These are only * the ones that need to be performed atomically. */ contract VotingUpgrader { // Existing governor is the only one who can initiate the upgrade. address public governor; // Existing Voting contract needs to be informed of the address of the new Voting contract. Voting public existingVoting; // New governor will be the new owner of the finder. // Finder contract to push upgrades to. Finder public finder; // Addresses to upgrade. address public newVoting; // Address to call setMigrated on the old voting contract. address public setMigratedAddress; /** * @notice Removes an address from the whitelist. * @param _governor the Governor contract address. * @param _existingVoting the current/existing Voting contract address. * @param _newVoting the new Voting deployment address. * @param _finder the Finder contract address. * @param _setMigratedAddress the address to set migrated. This address will be able to continue making calls to * old voting contract (used to claim rewards on others' behalf). Note: this address * can always be changed by the voters. */ constructor( address _governor, address _existingVoting, address _newVoting, address _finder, address _setMigratedAddress ) { governor = _governor; existingVoting = Voting(_existingVoting); newVoting = _newVoting; finder = Finder(_finder); setMigratedAddress = _setMigratedAddress; } /** * @notice Performs the atomic portion of the upgrade process. * @dev This method updates the Voting address in the finder, sets the old voting contract to migrated state, and * returns ownership of the existing Voting contract and Finder back to the Governor. */ function upgrade() external { require(msg.sender == governor, "Upgrade can only be initiated by the existing governor."); // Change the addresses in the Finder. finder.changeImplementationAddress(OracleInterfaces.Oracle, newVoting); // Set the preset "migrated" address to allow this address to claim rewards on voters' behalf. // This also effectively shuts down the existing voting contract so new votes cannot be triggered. existingVoting.setMigrated(setMigratedAddress); // Transfer back ownership of old voting contract and the finder to the governor. existingVoting.transferOwnership(governor); finder.transferOwnership(governor); } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.8.0; import "@openzeppelin/contracts/access/Ownable.sol"; import "../interfaces/FinderInterface.sol"; /** * @title Provides addresses of the live contracts implementing certain interfaces. * @dev Examples of interfaces with implementations that Finder locates are the Oracle and Store interfaces. */ contract Finder is FinderInterface, Ownable { mapping(bytes32 => address) public interfacesImplemented; event InterfaceImplementationChanged(bytes32 indexed interfaceName, address indexed newImplementationAddress); /** * @notice Updates the address of the contract that implements `interfaceName`. * @param interfaceName bytes32 of the interface name that is either changed or registered. * @param implementationAddress address of the implementation contract. */ function changeImplementationAddress(bytes32 interfaceName, address implementationAddress) external override onlyOwner { interfacesImplemented[interfaceName] = implementationAddress; emit InterfaceImplementationChanged(interfaceName, implementationAddress); } /** * @notice Gets the address of the contract that implements the given `interfaceName`. * @param interfaceName queried interface. * @return implementationAddress address of the defined interface. */ function getImplementationAddress(bytes32 interfaceName) external view override returns (address) { address implementationAddress = interfacesImplemented[interfaceName]; require(implementationAddress != address(0x0), "Implementation not found"); return implementationAddress; } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.8.0; import "../oracle/implementation/Finder.sol"; import "../oracle/implementation/Constants.sol"; import "../oracle/implementation/Voting.sol"; /** * @title A contract to track a whitelist of addresses. */ contract Umip3Upgrader { // Existing governor is the only one who can initiate the upgrade. address public existingGovernor; // Existing Voting contract needs to be informed of the address of the new Voting contract. Voting public existingVoting; // New governor will be the new owner of the finder. address public newGovernor; // Finder contract to push upgrades to. Finder public finder; // Addresses to upgrade. address public voting; address public identifierWhitelist; address public store; address public financialContractsAdmin; address public registry; constructor( address _existingGovernor, address _existingVoting, address _finder, address _voting, address _identifierWhitelist, address _store, address _financialContractsAdmin, address _registry, address _newGovernor ) { existingGovernor = _existingGovernor; existingVoting = Voting(_existingVoting); finder = Finder(_finder); voting = _voting; identifierWhitelist = _identifierWhitelist; store = _store; financialContractsAdmin = _financialContractsAdmin; registry = _registry; newGovernor = _newGovernor; } function upgrade() external { require(msg.sender == existingGovernor, "Upgrade can only be initiated by the existing governor."); // Change the addresses in the Finder. finder.changeImplementationAddress(OracleInterfaces.Oracle, voting); finder.changeImplementationAddress(OracleInterfaces.IdentifierWhitelist, identifierWhitelist); finder.changeImplementationAddress(OracleInterfaces.Store, store); finder.changeImplementationAddress(OracleInterfaces.FinancialContractsAdmin, financialContractsAdmin); finder.changeImplementationAddress(OracleInterfaces.Registry, registry); // Transfer the ownership of the Finder to the new Governor now that all the addresses have been updated. finder.transferOwnership(newGovernor); // Inform the existing Voting contract of the address of the new Voting contract and transfer its // ownership to the new governor to allow for any future changes to the migrated contract. existingVoting.setMigrated(voting); existingVoting.transferOwnership(newGovernor); } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.8.0; pragma abicoder v2; import "../../common/implementation/Testable.sol"; import "../interfaces/OracleAncillaryInterface.sol"; import "../interfaces/IdentifierWhitelistInterface.sol"; import "../interfaces/FinderInterface.sol"; import "../implementation/Constants.sol"; // A mock oracle used for testing. contract MockOracleAncillary is OracleAncillaryInterface, Testable { // Represents an available price. Have to keep a separate bool to allow for price=0. struct Price { bool isAvailable; int256 price; // Time the verified price became available. uint256 verifiedTime; } // The two structs below are used in an array and mapping to keep track of prices that have been requested but are // not yet available. struct QueryIndex { bool isValid; uint256 index; } // Represents a (identifier, time) point that has been queried. struct QueryPoint { bytes32 identifier; uint256 time; bytes ancillaryData; } // Reference to the Finder. FinderInterface private finder; // Conceptually we want a (time, identifier) -> price map. mapping(bytes32 => mapping(uint256 => mapping(bytes => Price))) private verifiedPrices; // The mapping and array allow retrieving all the elements in a mapping and finding/deleting elements. // Can we generalize this data structure? mapping(bytes32 => mapping(uint256 => mapping(bytes => QueryIndex))) private queryIndices; QueryPoint[] private requestedPrices; event PriceRequestAdded(address indexed requester, bytes32 indexed identifier, uint256 time, bytes ancillaryData); event PushedPrice( address indexed pusher, bytes32 indexed identifier, uint256 time, bytes ancillaryData, int256 price ); constructor(address _finderAddress, address _timerAddress) Testable(_timerAddress) { finder = FinderInterface(_finderAddress); } // Enqueues a request (if a request isn't already present) for the given (identifier, time) pair. function requestPrice( bytes32 identifier, uint256 time, bytes memory ancillaryData ) public override { require(_getIdentifierWhitelist().isIdentifierSupported(identifier)); Price storage lookup = verifiedPrices[identifier][time][ancillaryData]; if (!lookup.isAvailable && !queryIndices[identifier][time][ancillaryData].isValid) { // New query, enqueue it for review. queryIndices[identifier][time][ancillaryData] = QueryIndex(true, requestedPrices.length); requestedPrices.push(QueryPoint(identifier, time, ancillaryData)); emit PriceRequestAdded(msg.sender, identifier, time, ancillaryData); } } // Pushes the verified price for a requested query. function pushPrice( bytes32 identifier, uint256 time, bytes memory ancillaryData, int256 price ) external { verifiedPrices[identifier][time][ancillaryData] = Price(true, price, getCurrentTime()); QueryIndex storage queryIndex = queryIndices[identifier][time][ancillaryData]; require(queryIndex.isValid, "Can't push prices that haven't been requested"); // Delete from the array. Instead of shifting the queries over, replace the contents of `indexToReplace` with // the contents of the last index (unless it is the last index). uint256 indexToReplace = queryIndex.index; delete queryIndices[identifier][time][ancillaryData]; uint256 lastIndex = requestedPrices.length - 1; if (lastIndex != indexToReplace) { QueryPoint storage queryToCopy = requestedPrices[lastIndex]; queryIndices[queryToCopy.identifier][queryToCopy.time][queryToCopy.ancillaryData].index = indexToReplace; requestedPrices[indexToReplace] = queryToCopy; } emit PushedPrice(msg.sender, identifier, time, ancillaryData, price); } // Checks whether a price has been resolved. function hasPrice( bytes32 identifier, uint256 time, bytes memory ancillaryData ) public view override returns (bool) { require(_getIdentifierWhitelist().isIdentifierSupported(identifier)); Price storage lookup = verifiedPrices[identifier][time][ancillaryData]; return lookup.isAvailable; } // Gets a price that has already been resolved. function getPrice( bytes32 identifier, uint256 time, bytes memory ancillaryData ) public view override returns (int256) { require(_getIdentifierWhitelist().isIdentifierSupported(identifier)); Price storage lookup = verifiedPrices[identifier][time][ancillaryData]; require(lookup.isAvailable); return lookup.price; } // Gets the queries that still need verified prices. function getPendingQueries() external view returns (QueryPoint[] memory) { return requestedPrices; } function _getIdentifierWhitelist() private view returns (IdentifierWhitelistInterface supportedIdentifiers) { return IdentifierWhitelistInterface(finder.getImplementationAddress(OracleInterfaces.IdentifierWhitelist)); } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.8.0; pragma abicoder v2; import "../../common/implementation/Testable.sol"; import "../interfaces/OracleInterface.sol"; import "../interfaces/IdentifierWhitelistInterface.sol"; import "../interfaces/FinderInterface.sol"; import "../implementation/Constants.sol"; // A mock oracle used for testing. contract MockOracle is OracleInterface, Testable { // Represents an available price. Have to keep a separate bool to allow for price=0. struct Price { bool isAvailable; int256 price; // Time the verified price became available. uint256 verifiedTime; } // The two structs below are used in an array and mapping to keep track of prices that have been requested but are // not yet available. struct QueryIndex { bool isValid; uint256 index; } // Represents a (identifier, time) point that has been queried. struct QueryPoint { bytes32 identifier; uint256 time; } // Reference to the Finder. FinderInterface private finder; // Conceptually we want a (time, identifier) -> price map. mapping(bytes32 => mapping(uint256 => Price)) private verifiedPrices; // The mapping and array allow retrieving all the elements in a mapping and finding/deleting elements. // Can we generalize this data structure? mapping(bytes32 => mapping(uint256 => QueryIndex)) private queryIndices; QueryPoint[] private requestedPrices; constructor(address _finderAddress, address _timerAddress) Testable(_timerAddress) { finder = FinderInterface(_finderAddress); } // Enqueues a request (if a request isn't already present) for the given (identifier, time) pair. function requestPrice(bytes32 identifier, uint256 time) public override { require(_getIdentifierWhitelist().isIdentifierSupported(identifier)); Price storage lookup = verifiedPrices[identifier][time]; if (!lookup.isAvailable && !queryIndices[identifier][time].isValid) { // New query, enqueue it for review. queryIndices[identifier][time] = QueryIndex(true, requestedPrices.length); requestedPrices.push(QueryPoint(identifier, time)); } } // Pushes the verified price for a requested query. function pushPrice( bytes32 identifier, uint256 time, int256 price ) external { verifiedPrices[identifier][time] = Price(true, price, getCurrentTime()); QueryIndex storage queryIndex = queryIndices[identifier][time]; require(queryIndex.isValid, "Can't push prices that haven't been requested"); // Delete from the array. Instead of shifting the queries over, replace the contents of `indexToReplace` with // the contents of the last index (unless it is the last index). uint256 indexToReplace = queryIndex.index; delete queryIndices[identifier][time]; uint256 lastIndex = requestedPrices.length - 1; if (lastIndex != indexToReplace) { QueryPoint storage queryToCopy = requestedPrices[lastIndex]; queryIndices[queryToCopy.identifier][queryToCopy.time].index = indexToReplace; requestedPrices[indexToReplace] = queryToCopy; } } // Checks whether a price has been resolved. function hasPrice(bytes32 identifier, uint256 time) public view override returns (bool) { require(_getIdentifierWhitelist().isIdentifierSupported(identifier)); Price storage lookup = verifiedPrices[identifier][time]; return lookup.isAvailable; } // Gets a price that has already been resolved. function getPrice(bytes32 identifier, uint256 time) public view override returns (int256) { require(_getIdentifierWhitelist().isIdentifierSupported(identifier)); Price storage lookup = verifiedPrices[identifier][time]; require(lookup.isAvailable); return lookup.price; } // Gets the queries that still need verified prices. function getPendingQueries() external view returns (QueryPoint[] memory) { return requestedPrices; } function _getIdentifierWhitelist() private view returns (IdentifierWhitelistInterface supportedIdentifiers) { return IdentifierWhitelistInterface(finder.getImplementationAddress(OracleInterfaces.IdentifierWhitelist)); } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.8.0; pragma abicoder v2; import "../../common/implementation/MultiRole.sol"; import "../../common/implementation/FixedPoint.sol"; import "../../common/implementation/Testable.sol"; import "../interfaces/FinderInterface.sol"; import "../interfaces/IdentifierWhitelistInterface.sol"; import "../interfaces/OracleInterface.sol"; import "./Constants.sol"; import "@openzeppelin/contracts/utils/math/SafeMath.sol"; import "@openzeppelin/contracts/utils/Address.sol"; /** * @title Takes proposals for certain governance actions and allows UMA token holders to vote on them. */ contract Governor is MultiRole, Testable { using SafeMath for uint256; using Address for address; /**************************************** * INTERNAL VARIABLES AND STORAGE * ****************************************/ enum Roles { Owner, // Can set the proposer. Proposer // Address that can make proposals. } struct Transaction { address to; uint256 value; bytes data; } struct Proposal { Transaction[] transactions; uint256 requestTime; } FinderInterface private finder; Proposal[] public proposals; /**************************************** * EVENTS * ****************************************/ // Emitted when a new proposal is created. event NewProposal(uint256 indexed id, Transaction[] transactions); // Emitted when an existing proposal is executed. event ProposalExecuted(uint256 indexed id, uint256 transactionIndex); /** * @notice Construct the Governor contract. * @param _finderAddress keeps track of all contracts within the system based on their interfaceName. * @param _startingId the initial proposal id that the contract will begin incrementing from. * @param _timerAddress Contract that stores the current time in a testing environment. * Must be set to 0x0 for production environments that use live time. */ constructor( address _finderAddress, uint256 _startingId, address _timerAddress ) Testable(_timerAddress) { finder = FinderInterface(_finderAddress); _createExclusiveRole(uint256(Roles.Owner), uint256(Roles.Owner), msg.sender); _createExclusiveRole(uint256(Roles.Proposer), uint256(Roles.Owner), msg.sender); // Ensure the startingId is not set unreasonably high to avoid it being set such that new proposals overwrite // other storage slots in the contract. uint256 maxStartingId = 10**18; require(_startingId <= maxStartingId, "Cannot set startingId larger than 10^18"); // This just sets the initial length of the array to the startingId since modifying length directly has been // disallowed in solidity 0.6. assembly { sstore(proposals.slot, _startingId) } } /**************************************** * PROPOSAL ACTIONS * ****************************************/ /** * @notice Proposes a new governance action. Can only be called by the holder of the Proposer role. * @param transactions list of transactions that are being proposed. * @dev You can create the data portion of each transaction by doing the following: * ``` * const truffleContractInstance = await TruffleContract.deployed() * const data = truffleContractInstance.methods.methodToCall(arg1, arg2).encodeABI() * ``` * Note: this method must be public because of a solidity limitation that * disallows structs arrays to be passed to external functions. */ function propose(Transaction[] memory transactions) public onlyRoleHolder(uint256(Roles.Proposer)) { uint256 id = proposals.length; uint256 time = getCurrentTime(); // Note: doing all of this array manipulation manually is necessary because directly setting an array of // structs in storage to an an array of structs in memory is currently not implemented in solidity :/. // Add a zero-initialized element to the proposals array. proposals.push(); // Initialize the new proposal. Proposal storage proposal = proposals[id]; proposal.requestTime = time; // Initialize the transaction array. for (uint256 i = 0; i < transactions.length; i++) { require(transactions[i].to != address(0), "The `to` address cannot be 0x0"); // If the transaction has any data with it the recipient must be a contract, not an EOA. if (transactions[i].data.length > 0) { require(transactions[i].to.isContract(), "EOA can't accept tx with data"); } proposal.transactions.push(transactions[i]); } bytes32 identifier = _constructIdentifier(id); // Request a vote on this proposal in the DVM. OracleInterface oracle = _getOracle(); IdentifierWhitelistInterface supportedIdentifiers = _getIdentifierWhitelist(); supportedIdentifiers.addSupportedIdentifier(identifier); oracle.requestPrice(identifier, time); supportedIdentifiers.removeSupportedIdentifier(identifier); emit NewProposal(id, transactions); } /** * @notice Executes a proposed governance action that has been approved by voters. * @dev This can be called by any address. Caller is expected to send enough ETH to execute payable transactions. * @param id unique id for the executed proposal. * @param transactionIndex unique transaction index for the executed proposal. */ function executeProposal(uint256 id, uint256 transactionIndex) external payable { Proposal storage proposal = proposals[id]; int256 price = _getOracle().getPrice(_constructIdentifier(id), proposal.requestTime); Transaction memory transaction = proposal.transactions[transactionIndex]; require( transactionIndex == 0 || proposal.transactions[transactionIndex.sub(1)].to == address(0), "Previous tx not yet executed" ); require(transaction.to != address(0), "Tx already executed"); require(price != 0, "Proposal was rejected"); require(msg.value == transaction.value, "Must send exact amount of ETH"); // Delete the transaction before execution to avoid any potential re-entrancy issues. delete proposal.transactions[transactionIndex]; require(_executeCall(transaction.to, transaction.value, transaction.data), "Tx execution failed"); emit ProposalExecuted(id, transactionIndex); } /**************************************** * GOVERNOR STATE GETTERS * ****************************************/ /** * @notice Gets the total number of proposals (includes executed and non-executed). * @return uint256 representing the current number of proposals. */ function numProposals() external view returns (uint256) { return proposals.length; } /** * @notice Gets the proposal data for a particular id. * @dev after a proposal is executed, its data will be zeroed out, except for the request time. * @param id uniquely identify the identity of the proposal. * @return proposal struct containing transactions[] and requestTime. */ function getProposal(uint256 id) external view returns (Proposal memory) { return proposals[id]; } /**************************************** * PRIVATE GETTERS AND FUNCTIONS * ****************************************/ function _executeCall( address to, uint256 value, bytes memory data ) private returns (bool) { // Mostly copied from: // solhint-disable-next-line max-line-length // https://github.com/gnosis/safe-contracts/blob/59cfdaebcd8b87a0a32f87b50fead092c10d3a05/contracts/base/Executor.sol#L23-L31 // solhint-disable-next-line no-inline-assembly bool success; assembly { let inputData := add(data, 0x20) let inputDataSize := mload(data) success := call(gas(), to, value, inputData, inputDataSize, 0, 0) } return success; } function _getOracle() private view returns (OracleInterface) { return OracleInterface(finder.getImplementationAddress(OracleInterfaces.Oracle)); } function _getIdentifierWhitelist() private view returns (IdentifierWhitelistInterface supportedIdentifiers) { return IdentifierWhitelistInterface(finder.getImplementationAddress(OracleInterfaces.IdentifierWhitelist)); } // Returns a UTF-8 identifier representing a particular admin proposal. // The identifier is of the form "Admin n", where n is the proposal id provided. function _constructIdentifier(uint256 id) internal pure returns (bytes32) { bytes32 bytesId = _uintToUtf8(id); return _addPrefix(bytesId, "Admin ", 6); } // This method converts the integer `v` into a base-10, UTF-8 representation stored in a `bytes32` type. // If the input cannot be represented by 32 base-10 digits, it returns only the highest 32 digits. // This method is based off of this code: https://ethereum.stackexchange.com/a/6613/47801. function _uintToUtf8(uint256 v) internal pure returns (bytes32) { bytes32 ret; if (v == 0) { // Handle 0 case explicitly. ret = "0"; } else { // Constants. uint256 bitsPerByte = 8; uint256 base = 10; // Note: the output should be base-10. The below implementation will not work for bases > 10. uint256 utf8NumberOffset = 48; while (v > 0) { // Downshift the entire bytes32 to allow the new digit to be added at the "front" of the bytes32, which // translates to the beginning of the UTF-8 representation. ret = ret >> bitsPerByte; // Separate the last digit that remains in v by modding by the base of desired output representation. uint256 leastSignificantDigit = v % base; // Digits 0-9 are represented by 48-57 in UTF-8, so an offset must be added to create the character. bytes32 utf8Digit = bytes32(leastSignificantDigit + utf8NumberOffset); // The top byte of ret has already been cleared to make room for the new digit. // Upshift by 31 bytes to put it in position, and OR it with ret to leave the other characters untouched. ret |= utf8Digit << (31 * bitsPerByte); // Divide v by the base to remove the digit that was just added. v /= base; } } return ret; } // This method takes two UTF-8 strings represented as bytes32 and outputs one as a prefixed by the other. // `input` is the UTF-8 that should have the prefix prepended. // `prefix` is the UTF-8 that should be prepended onto input. // `prefixLength` is number of UTF-8 characters represented by `prefix`. // Notes: // 1. If the resulting UTF-8 is larger than 32 characters, then only the first 32 characters will be represented // by the bytes32 output. // 2. If `prefix` has more characters than `prefixLength`, the function will produce an invalid result. function _addPrefix( bytes32 input, bytes32 prefix, uint256 prefixLength ) internal pure returns (bytes32) { // Downshift `input` to open space at the "front" of the bytes32 bytes32 shiftedInput = input >> (prefixLength * 8); return shiftedInput | prefix; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: value }(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.delegatecall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.8.0; pragma abicoder v2; import "../Governor.sol"; // GovernorTest exposes internal methods in the Governor for testing. contract GovernorTest is Governor { constructor(address _timerAddress) Governor(address(0), 0, _timerAddress) {} function addPrefix( bytes32 input, bytes32 prefix, uint256 prefixLength ) external pure returns (bytes32) { return _addPrefix(input, prefix, prefixLength); } function uintToUtf8(uint256 v) external pure returns (bytes32 ret) { return _uintToUtf8(v); } function constructIdentifier(uint256 id) external pure returns (bytes32 identifier) { return _constructIdentifier(id); } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.8.0; pragma abicoder v2; 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 "../interfaces/StoreInterface.sol"; import "../interfaces/OracleAncillaryInterface.sol"; import "../interfaces/FinderInterface.sol"; import "../interfaces/IdentifierWhitelistInterface.sol"; import "../interfaces/OptimisticOracleInterface.sol"; import "./Constants.sol"; import "../../common/implementation/Testable.sol"; import "../../common/implementation/Lockable.sol"; import "../../common/implementation/FixedPoint.sol"; import "../../common/implementation/AddressWhitelist.sol"; /** * @title Optimistic Requester. * @notice Optional interface that requesters can implement to receive callbacks. * @dev this contract does _not_ work with ERC777 collateral currencies or any others that call into the receiver on * transfer(). Using an ERC777 token would allow a user to maliciously grief other participants (while also losing * money themselves). */ interface OptimisticRequester { /** * @notice Callback for proposals. * @param identifier price identifier being requested. * @param timestamp timestamp of the price being requested. * @param ancillaryData ancillary data of the price being requested. */ function priceProposed( bytes32 identifier, uint256 timestamp, bytes memory ancillaryData ) external; /** * @notice Callback for disputes. * @param identifier price identifier being requested. * @param timestamp timestamp of the price being requested. * @param ancillaryData ancillary data of the price being requested. * @param refund refund received in the case that refundOnDispute was enabled. */ function priceDisputed( bytes32 identifier, uint256 timestamp, bytes memory ancillaryData, uint256 refund ) external; /** * @notice Callback for settlement. * @param identifier price identifier being requested. * @param timestamp timestamp of the price being requested. * @param ancillaryData ancillary data of the price being requested. * @param price price that was resolved by the escalation process. */ function priceSettled( bytes32 identifier, uint256 timestamp, bytes memory ancillaryData, int256 price ) external; } /** * @title Optimistic Oracle. * @notice Pre-DVM escalation contract that allows faster settlement. */ contract OptimisticOracle is OptimisticOracleInterface, Testable, Lockable { using SafeMath for uint256; using SafeERC20 for IERC20; using Address for address; event RequestPrice( address indexed requester, bytes32 identifier, uint256 timestamp, bytes ancillaryData, address currency, uint256 reward, uint256 finalFee ); event ProposePrice( address indexed requester, address indexed proposer, bytes32 identifier, uint256 timestamp, bytes ancillaryData, int256 proposedPrice, uint256 expirationTimestamp, address currency ); event DisputePrice( address indexed requester, address indexed proposer, address indexed disputer, bytes32 identifier, uint256 timestamp, bytes ancillaryData, int256 proposedPrice ); event Settle( address indexed requester, address indexed proposer, address indexed disputer, bytes32 identifier, uint256 timestamp, bytes ancillaryData, int256 price, uint256 payout ); mapping(bytes32 => Request) public requests; // Finder to provide addresses for DVM contracts. FinderInterface public finder; // Default liveness value for all price requests. uint256 public defaultLiveness; /** * @notice Constructor. * @param _liveness default liveness applied to each price request. * @param _finderAddress finder to use to get addresses of DVM contracts. * @param _timerAddress address of the timer contract. Should be 0x0 in prod. */ constructor( uint256 _liveness, address _finderAddress, address _timerAddress ) Testable(_timerAddress) { finder = FinderInterface(_finderAddress); _validateLiveness(_liveness); defaultLiveness = _liveness; } /** * @notice Requests a new price. * @param identifier price identifier being requested. * @param timestamp timestamp of the price being requested. * @param ancillaryData ancillary data representing additional args being passed with the price request. * @param currency ERC20 token used for payment of rewards and fees. Must be approved for use with the DVM. * @param reward reward offered to a successful proposer. Will be pulled from the caller. Note: this can be 0, * which could make sense if the contract requests and proposes the value in the same call or * provides its own reward system. * @return totalBond default bond (final fee) + final fee that the proposer and disputer will be required to pay. * This can be changed with a subsequent call to setBond(). */ function requestPrice( bytes32 identifier, uint256 timestamp, bytes memory ancillaryData, IERC20 currency, uint256 reward ) external override nonReentrant() returns (uint256 totalBond) { require(getState(msg.sender, identifier, timestamp, ancillaryData) == State.Invalid, "requestPrice: Invalid"); require(_getIdentifierWhitelist().isIdentifierSupported(identifier), "Unsupported identifier"); require(_getCollateralWhitelist().isOnWhitelist(address(currency)), "Unsupported currency"); require(timestamp <= getCurrentTime(), "Timestamp in future"); require(ancillaryData.length <= ancillaryBytesLimit, "Invalid ancillary data"); uint256 finalFee = _getStore().computeFinalFee(address(currency)).rawValue; requests[_getId(msg.sender, identifier, timestamp, ancillaryData)] = Request({ proposer: address(0), disputer: address(0), currency: currency, settled: false, refundOnDispute: false, proposedPrice: 0, resolvedPrice: 0, expirationTime: 0, reward: reward, finalFee: finalFee, bond: finalFee, customLiveness: 0 }); if (reward > 0) { currency.safeTransferFrom(msg.sender, address(this), reward); } emit RequestPrice(msg.sender, identifier, timestamp, ancillaryData, address(currency), reward, finalFee); // This function returns the initial proposal bond for this request, which can be customized by calling // setBond() with the same identifier and timestamp. return finalFee.mul(2); } /** * @notice Set the proposal bond associated with a price request. * @param identifier price identifier to identify the existing request. * @param timestamp timestamp to identify the existing request. * @param ancillaryData ancillary data of the price being requested. * @param bond custom bond amount to set. * @return totalBond new bond + final fee that the proposer and disputer will be required to pay. This can be * changed again with a subsequent call to setBond(). */ function setBond( bytes32 identifier, uint256 timestamp, bytes memory ancillaryData, uint256 bond ) external override nonReentrant() returns (uint256 totalBond) { require(getState(msg.sender, identifier, timestamp, ancillaryData) == State.Requested, "setBond: Requested"); Request storage request = _getRequest(msg.sender, identifier, timestamp, ancillaryData); request.bond = bond; // Total bond is the final fee + the newly set bond. return bond.add(request.finalFee); } /** * @notice Sets the request to refund the reward if the proposal is disputed. This can help to "hedge" the caller * in the event of a dispute-caused delay. Note: in the event of a dispute, the winner still receives the other's * bond, so there is still profit to be made even if the reward is refunded. * @param identifier price identifier to identify the existing request. * @param timestamp timestamp to identify the existing request. * @param ancillaryData ancillary data of the price being requested. */ function setRefundOnDispute( bytes32 identifier, uint256 timestamp, bytes memory ancillaryData ) external override nonReentrant() { require( getState(msg.sender, identifier, timestamp, ancillaryData) == State.Requested, "setRefundOnDispute: Requested" ); _getRequest(msg.sender, identifier, timestamp, ancillaryData).refundOnDispute = true; } /** * @notice Sets a custom liveness value for the request. Liveness is the amount of time a proposal must wait before * being auto-resolved. * @param identifier price identifier to identify the existing request. * @param timestamp timestamp to identify the existing request. * @param ancillaryData ancillary data of the price being requested. * @param customLiveness new custom liveness. */ function setCustomLiveness( bytes32 identifier, uint256 timestamp, bytes memory ancillaryData, uint256 customLiveness ) external override nonReentrant() { require( getState(msg.sender, identifier, timestamp, ancillaryData) == State.Requested, "setCustomLiveness: Requested" ); _validateLiveness(customLiveness); _getRequest(msg.sender, identifier, timestamp, ancillaryData).customLiveness = customLiveness; } /** * @notice Proposes a price value on another address' behalf. Note: this address will receive any rewards that come * from this proposal. However, any bonds are pulled from the caller. * @param proposer address to set as the proposer. * @param requester sender of the initial price request. * @param identifier price identifier to identify the existing request. * @param timestamp timestamp to identify the existing request. * @param ancillaryData ancillary data of the price being requested. * @param proposedPrice price being proposed. * @return totalBond the amount that's pulled from the caller's wallet as a bond. The bond will be returned to * the proposer once settled if the proposal is correct. */ function proposePriceFor( address proposer, address requester, bytes32 identifier, uint256 timestamp, bytes memory ancillaryData, int256 proposedPrice ) public override nonReentrant() returns (uint256 totalBond) { require(proposer != address(0), "proposer address must be non 0"); require( getState(requester, identifier, timestamp, ancillaryData) == State.Requested, "proposePriceFor: Requested" ); Request storage request = _getRequest(requester, identifier, timestamp, ancillaryData); request.proposer = proposer; request.proposedPrice = proposedPrice; // If a custom liveness has been set, use it instead of the default. request.expirationTime = getCurrentTime().add( request.customLiveness != 0 ? request.customLiveness : defaultLiveness ); totalBond = request.bond.add(request.finalFee); if (totalBond > 0) { request.currency.safeTransferFrom(msg.sender, address(this), totalBond); } emit ProposePrice( requester, proposer, identifier, timestamp, ancillaryData, proposedPrice, request.expirationTime, address(request.currency) ); // Callback. if (address(requester).isContract()) try OptimisticRequester(requester).priceProposed(identifier, timestamp, ancillaryData) {} catch {} } /** * @notice Proposes a price value for an existing price request. * @param requester sender of the initial price request. * @param identifier price identifier to identify the existing request. * @param timestamp timestamp to identify the existing request. * @param ancillaryData ancillary data of the price being requested. * @param proposedPrice price being proposed. * @return totalBond the amount that's pulled from the proposer's wallet as a bond. The bond will be returned to * the proposer once settled if the proposal is correct. */ function proposePrice( address requester, bytes32 identifier, uint256 timestamp, bytes memory ancillaryData, int256 proposedPrice ) external override returns (uint256 totalBond) { // Note: re-entrancy guard is done in the inner call. return proposePriceFor(msg.sender, requester, identifier, timestamp, ancillaryData, proposedPrice); } /** * @notice Disputes a price request with an active proposal on another address' behalf. Note: this address will * receive any rewards that come from this dispute. However, any bonds are pulled from the caller. * @param disputer address to set as the disputer. * @param requester sender of the initial price request. * @param identifier price identifier to identify the existing request. * @param timestamp timestamp to identify the existing request. * @param ancillaryData ancillary data of the price being requested. * @return totalBond the amount that's pulled from the caller's wallet as a bond. The bond will be returned to * the disputer once settled if the dispute was valid (the proposal was incorrect). */ function disputePriceFor( address disputer, address requester, bytes32 identifier, uint256 timestamp, bytes memory ancillaryData ) public override nonReentrant() returns (uint256 totalBond) { require(disputer != address(0), "disputer address must be non 0"); require( getState(requester, identifier, timestamp, ancillaryData) == State.Proposed, "disputePriceFor: Proposed" ); Request storage request = _getRequest(requester, identifier, timestamp, ancillaryData); request.disputer = disputer; uint256 finalFee = request.finalFee; uint256 bond = request.bond; totalBond = bond.add(finalFee); if (totalBond > 0) { request.currency.safeTransferFrom(msg.sender, address(this), totalBond); } StoreInterface store = _getStore(); // Avoids stack too deep compilation error. { // Along with the final fee, "burn" part of the loser's bond to ensure that a larger bond always makes it // proportionally more expensive to delay the resolution even if the proposer and disputer are the same // party. uint256 burnedBond = _computeBurnedBond(request); // The total fee is the burned bond and the final fee added together. uint256 totalFee = finalFee.add(burnedBond); if (totalFee > 0) { request.currency.safeIncreaseAllowance(address(store), totalFee); _getStore().payOracleFeesErc20(address(request.currency), FixedPoint.Unsigned(totalFee)); } } _getOracle().requestPrice(identifier, timestamp, _stampAncillaryData(ancillaryData, requester)); // Compute refund. uint256 refund = 0; if (request.reward > 0 && request.refundOnDispute) { refund = request.reward; request.reward = 0; request.currency.safeTransfer(requester, refund); } emit DisputePrice( requester, request.proposer, disputer, identifier, timestamp, ancillaryData, request.proposedPrice ); // Callback. if (address(requester).isContract()) try OptimisticRequester(requester).priceDisputed(identifier, timestamp, ancillaryData, refund) {} catch {} } /** * @notice Disputes a price value for an existing price request with an active proposal. * @param requester sender of the initial price request. * @param identifier price identifier to identify the existing request. * @param timestamp timestamp to identify the existing request. * @param ancillaryData ancillary data of the price being requested. * @return totalBond the amount that's pulled from the disputer's wallet as a bond. The bond will be returned to * the disputer once settled if the dispute was valid (the proposal was incorrect). */ function disputePrice( address requester, bytes32 identifier, uint256 timestamp, bytes memory ancillaryData ) external override returns (uint256 totalBond) { // Note: re-entrancy guard is done in the inner call. return disputePriceFor(msg.sender, requester, identifier, timestamp, ancillaryData); } /** * @notice Retrieves a price that was previously requested by a caller. Reverts if the request is not settled * or settleable. Note: this method is not view so that this call may actually settle the price request if it * hasn't been settled. * @param identifier price identifier to identify the existing request. * @param timestamp timestamp to identify the existing request. * @param ancillaryData ancillary data of the price being requested. * @return resolved price. */ function settleAndGetPrice( bytes32 identifier, uint256 timestamp, bytes memory ancillaryData ) external override nonReentrant() returns (int256) { if (getState(msg.sender, identifier, timestamp, ancillaryData) != State.Settled) { _settle(msg.sender, identifier, timestamp, ancillaryData); } return _getRequest(msg.sender, identifier, timestamp, ancillaryData).resolvedPrice; } /** * @notice Attempts to settle an outstanding price request. Will revert if it isn't settleable. * @param requester sender of the initial price request. * @param identifier price identifier to identify the existing request. * @param timestamp timestamp to identify the existing request. * @param ancillaryData ancillary data of the price being requested. * @return payout the amount that the "winner" (proposer or disputer) receives on settlement. This amount includes * the returned bonds as well as additional rewards. */ function settle( address requester, bytes32 identifier, uint256 timestamp, bytes memory ancillaryData ) external override nonReentrant() returns (uint256 payout) { return _settle(requester, identifier, timestamp, ancillaryData); } /** * @notice Gets the current data structure containing all information about a price request. * @param requester sender of the initial price request. * @param identifier price identifier to identify the existing request. * @param timestamp timestamp to identify the existing request. * @param ancillaryData ancillary data of the price being requested. * @return the Request data structure. */ function getRequest( address requester, bytes32 identifier, uint256 timestamp, bytes memory ancillaryData ) public view override returns (Request memory) { return _getRequest(requester, identifier, timestamp, ancillaryData); } /** * @notice Computes the current state of a price request. See the State enum for more details. * @param requester sender of the initial price request. * @param identifier price identifier to identify the existing request. * @param timestamp timestamp to identify the existing request. * @param ancillaryData ancillary data of the price being requested. * @return the State. */ function getState( address requester, bytes32 identifier, uint256 timestamp, bytes memory ancillaryData ) public view override returns (State) { Request storage request = _getRequest(requester, identifier, timestamp, ancillaryData); if (address(request.currency) == address(0)) { return State.Invalid; } if (request.proposer == address(0)) { return State.Requested; } if (request.settled) { return State.Settled; } if (request.disputer == address(0)) { return request.expirationTime <= getCurrentTime() ? State.Expired : State.Proposed; } return _getOracle().hasPrice(identifier, timestamp, _stampAncillaryData(ancillaryData, requester)) ? State.Resolved : State.Disputed; } /** * @notice Checks if a given request has resolved, expired or been settled (i.e the optimistic oracle has a price). * @param requester sender of the initial price request. * @param identifier price identifier to identify the existing request. * @param timestamp timestamp to identify the existing request. * @param ancillaryData ancillary data of the price being requested. * @return boolean indicating true if price exists and false if not. */ function hasPrice( address requester, bytes32 identifier, uint256 timestamp, bytes memory ancillaryData ) public view override returns (bool) { State state = getState(requester, identifier, timestamp, ancillaryData); return state == State.Settled || state == State.Resolved || state == State.Expired; } /** * @notice Generates stamped ancillary data in the format that it would be used in the case of a price dispute. * @param ancillaryData ancillary data of the price being requested. * @param requester sender of the initial price request. * @return the stampped ancillary bytes. */ function stampAncillaryData(bytes memory ancillaryData, address requester) public pure returns (bytes memory) { return _stampAncillaryData(ancillaryData, requester); } function _getId( address requester, bytes32 identifier, uint256 timestamp, bytes memory ancillaryData ) private pure returns (bytes32) { return keccak256(abi.encodePacked(requester, identifier, timestamp, ancillaryData)); } function _settle( address requester, bytes32 identifier, uint256 timestamp, bytes memory ancillaryData ) private returns (uint256 payout) { State state = getState(requester, identifier, timestamp, ancillaryData); // Set it to settled so this function can never be entered again. Request storage request = _getRequest(requester, identifier, timestamp, ancillaryData); request.settled = true; if (state == State.Expired) { // In the expiry case, just pay back the proposer's bond and final fee along with the reward. request.resolvedPrice = request.proposedPrice; payout = request.bond.add(request.finalFee).add(request.reward); request.currency.safeTransfer(request.proposer, payout); } else if (state == State.Resolved) { // In the Resolved case, pay either the disputer or the proposer the entire payout (+ bond and reward). request.resolvedPrice = _getOracle().getPrice( identifier, timestamp, _stampAncillaryData(ancillaryData, requester) ); bool disputeSuccess = request.resolvedPrice != request.proposedPrice; uint256 bond = request.bond; // Unburned portion of the loser's bond = 1 - burned bond. uint256 unburnedBond = bond.sub(_computeBurnedBond(request)); // Winner gets: // - Their bond back. // - The unburned portion of the loser's bond. // - Their final fee back. // - The request reward (if not already refunded -- if refunded, it will be set to 0). payout = bond.add(unburnedBond).add(request.finalFee).add(request.reward); request.currency.safeTransfer(disputeSuccess ? request.disputer : request.proposer, payout); } else { revert("_settle: not settleable"); } emit Settle( requester, request.proposer, request.disputer, identifier, timestamp, ancillaryData, request.resolvedPrice, payout ); // Callback. if (address(requester).isContract()) try OptimisticRequester(requester).priceSettled(identifier, timestamp, ancillaryData, request.resolvedPrice) {} catch {} } function _getRequest( address requester, bytes32 identifier, uint256 timestamp, bytes memory ancillaryData ) private view returns (Request storage) { return requests[_getId(requester, identifier, timestamp, ancillaryData)]; } function _computeBurnedBond(Request storage request) private view returns (uint256) { // burnedBond = floor(bond / 2) return request.bond.div(2); } function _validateLiveness(uint256 _liveness) private pure { require(_liveness < 5200 weeks, "Liveness too large"); require(_liveness > 0, "Liveness cannot be 0"); } function _getOracle() internal view returns (OracleAncillaryInterface) { return OracleAncillaryInterface(finder.getImplementationAddress(OracleInterfaces.Oracle)); } function _getCollateralWhitelist() internal view returns (AddressWhitelist) { return AddressWhitelist(finder.getImplementationAddress(OracleInterfaces.CollateralWhitelist)); } function _getStore() internal view returns (StoreInterface) { return StoreInterface(finder.getImplementationAddress(OracleInterfaces.Store)); } function _getIdentifierWhitelist() internal view returns (IdentifierWhitelistInterface) { return IdentifierWhitelistInterface(finder.getImplementationAddress(OracleInterfaces.IdentifierWhitelist)); } // Stamps the ancillary data blob with the optimistic oracle tag denoting what contract requested it. function _stampAncillaryData(bytes memory ancillaryData, address requester) internal pure returns (bytes memory) { return abi.encodePacked(ancillaryData, "OptimisticOracle", requester); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../IERC20.sol"; import "../../../utils/Address.sol"; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using Address for address; function safeTransfer(IERC20 token, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove(IERC20 token, address spender, uint256 value) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' // solhint-disable-next-line max-line-length require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender) + value; _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal { unchecked { uint256 oldAllowance = token.allowance(address(this), spender); require(oldAllowance >= value, "SafeERC20: decreased allowance below zero"); uint256 newAllowance = oldAllowance - value; _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.8.0; pragma abicoder v2; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "../../common/implementation/FixedPoint.sol"; /** * @title Interface that allows financial contracts to pay oracle fees for their use of the system. */ interface StoreInterface { /** * @notice Pays Oracle fees in ETH to the store. * @dev To be used by contracts whose margin currency is ETH. */ function payOracleFees() external payable; /** * @notice Pays oracle fees in the margin currency, erc20Address, to the store. * @dev To be used if the margin currency is an ERC20 token rather than ETH. * @param erc20Address address of the ERC20 token used to pay the fee. * @param amount number of tokens to transfer. An approval for at least this amount must exist. */ function payOracleFeesErc20(address erc20Address, FixedPoint.Unsigned calldata amount) external; /** * @notice Computes the regular oracle fees that a contract should pay for a period. * @param startTime defines the beginning time from which the fee is paid. * @param endTime end time until which the fee is paid. * @param pfc "profit from corruption", or the maximum amount of margin currency that a * token sponsor could extract from the contract through corrupting the price feed in their favor. * @return regularFee amount owed for the duration from start to end time for the given pfc. * @return latePenalty for paying the fee after the deadline. */ function computeRegularFee( uint256 startTime, uint256 endTime, FixedPoint.Unsigned calldata pfc ) external view returns (FixedPoint.Unsigned memory regularFee, FixedPoint.Unsigned memory latePenalty); /** * @notice Computes the final oracle fees that a contract should pay at settlement. * @param currency token used to pay the final fee. * @return finalFee amount due. */ function computeFinalFee(address currency) external view returns (FixedPoint.Unsigned memory); } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.8.0; pragma abicoder v2; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; /** * @title Financial contract facing Oracle interface. * @dev Interface used by financial contracts to interact with the Oracle. Voters will use a different interface. */ abstract contract OptimisticOracleInterface { // Struct representing the state of a price request. enum State { Invalid, // Never requested. Requested, // Requested, no other actions taken. Proposed, // Proposed, but not expired or disputed yet. Expired, // Proposed, not disputed, past liveness. Disputed, // Disputed, but no DVM price returned yet. Resolved, // Disputed and DVM price is available. Settled // Final price has been set in the contract (can get here from Expired or Resolved). } // Struct representing a price request. struct Request { address proposer; // Address of the proposer. address disputer; // Address of the disputer. IERC20 currency; // ERC20 token used to pay rewards and fees. bool settled; // True if the request is settled. bool refundOnDispute; // True if the requester should be refunded their reward on dispute. int256 proposedPrice; // Price that the proposer submitted. int256 resolvedPrice; // Price resolved once the request is settled. uint256 expirationTime; // Time at which the request auto-settles without a dispute. uint256 reward; // Amount of the currency to pay to the proposer on settlement. uint256 finalFee; // Final fee to pay to the Store upon request to the DVM. uint256 bond; // Bond that the proposer and disputer must pay on top of the final fee. uint256 customLiveness; // Custom liveness value set by the requester. } // This value must be <= the Voting contract's `ancillaryBytesLimit` value otherwise it is possible // that a price can be requested to this contract successfully, but cannot be disputed because the DVM refuses // to accept a price request made with ancillary data length of a certain size. uint256 public constant ancillaryBytesLimit = 8192; /** * @notice Requests a new price. * @param identifier price identifier being requested. * @param timestamp timestamp of the price being requested. * @param ancillaryData ancillary data representing additional args being passed with the price request. * @param currency ERC20 token used for payment of rewards and fees. Must be approved for use with the DVM. * @param reward reward offered to a successful proposer. Will be pulled from the caller. Note: this can be 0, * which could make sense if the contract requests and proposes the value in the same call or * provides its own reward system. * @return totalBond default bond (final fee) + final fee that the proposer and disputer will be required to pay. * This can be changed with a subsequent call to setBond(). */ function requestPrice( bytes32 identifier, uint256 timestamp, bytes memory ancillaryData, IERC20 currency, uint256 reward ) external virtual returns (uint256 totalBond); /** * @notice Set the proposal bond associated with a price request. * @param identifier price identifier to identify the existing request. * @param timestamp timestamp to identify the existing request. * @param ancillaryData ancillary data of the price being requested. * @param bond custom bond amount to set. * @return totalBond new bond + final fee that the proposer and disputer will be required to pay. This can be * changed again with a subsequent call to setBond(). */ function setBond( bytes32 identifier, uint256 timestamp, bytes memory ancillaryData, uint256 bond ) external virtual returns (uint256 totalBond); /** * @notice Sets the request to refund the reward if the proposal is disputed. This can help to "hedge" the caller * in the event of a dispute-caused delay. Note: in the event of a dispute, the winner still receives the other's * bond, so there is still profit to be made even if the reward is refunded. * @param identifier price identifier to identify the existing request. * @param timestamp timestamp to identify the existing request. * @param ancillaryData ancillary data of the price being requested. */ function setRefundOnDispute( bytes32 identifier, uint256 timestamp, bytes memory ancillaryData ) external virtual; /** * @notice Sets a custom liveness value for the request. Liveness is the amount of time a proposal must wait before * being auto-resolved. * @param identifier price identifier to identify the existing request. * @param timestamp timestamp to identify the existing request. * @param ancillaryData ancillary data of the price being requested. * @param customLiveness new custom liveness. */ function setCustomLiveness( bytes32 identifier, uint256 timestamp, bytes memory ancillaryData, uint256 customLiveness ) external virtual; /** * @notice Proposes a price value on another address' behalf. Note: this address will receive any rewards that come * from this proposal. However, any bonds are pulled from the caller. * @param proposer address to set as the proposer. * @param requester sender of the initial price request. * @param identifier price identifier to identify the existing request. * @param timestamp timestamp to identify the existing request. * @param ancillaryData ancillary data of the price being requested. * @param proposedPrice price being proposed. * @return totalBond the amount that's pulled from the caller's wallet as a bond. The bond will be returned to * the proposer once settled if the proposal is correct. */ function proposePriceFor( address proposer, address requester, bytes32 identifier, uint256 timestamp, bytes memory ancillaryData, int256 proposedPrice ) public virtual returns (uint256 totalBond); /** * @notice Proposes a price value for an existing price request. * @param requester sender of the initial price request. * @param identifier price identifier to identify the existing request. * @param timestamp timestamp to identify the existing request. * @param ancillaryData ancillary data of the price being requested. * @param proposedPrice price being proposed. * @return totalBond the amount that's pulled from the proposer's wallet as a bond. The bond will be returned to * the proposer once settled if the proposal is correct. */ function proposePrice( address requester, bytes32 identifier, uint256 timestamp, bytes memory ancillaryData, int256 proposedPrice ) external virtual returns (uint256 totalBond); /** * @notice Disputes a price request with an active proposal on another address' behalf. Note: this address will * receive any rewards that come from this dispute. However, any bonds are pulled from the caller. * @param disputer address to set as the disputer. * @param requester sender of the initial price request. * @param identifier price identifier to identify the existing request. * @param timestamp timestamp to identify the existing request. * @param ancillaryData ancillary data of the price being requested. * @return totalBond the amount that's pulled from the caller's wallet as a bond. The bond will be returned to * the disputer once settled if the dispute was value (the proposal was incorrect). */ function disputePriceFor( address disputer, address requester, bytes32 identifier, uint256 timestamp, bytes memory ancillaryData ) public virtual returns (uint256 totalBond); /** * @notice Disputes a price value for an existing price request with an active proposal. * @param requester sender of the initial price request. * @param identifier price identifier to identify the existing request. * @param timestamp timestamp to identify the existing request. * @param ancillaryData ancillary data of the price being requested. * @return totalBond the amount that's pulled from the disputer's wallet as a bond. The bond will be returned to * the disputer once settled if the dispute was valid (the proposal was incorrect). */ function disputePrice( address requester, bytes32 identifier, uint256 timestamp, bytes memory ancillaryData ) external virtual returns (uint256 totalBond); /** * @notice Retrieves a price that was previously requested by a caller. Reverts if the request is not settled * or settleable. Note: this method is not view so that this call may actually settle the price request if it * hasn't been settled. * @param identifier price identifier to identify the existing request. * @param timestamp timestamp to identify the existing request. * @param ancillaryData ancillary data of the price being requested. * @return resolved price. */ function settleAndGetPrice( bytes32 identifier, uint256 timestamp, bytes memory ancillaryData ) external virtual returns (int256); /** * @notice Attempts to settle an outstanding price request. Will revert if it isn't settleable. * @param requester sender of the initial price request. * @param identifier price identifier to identify the existing request. * @param timestamp timestamp to identify the existing request. * @param ancillaryData ancillary data of the price being requested. * @return payout the amount that the "winner" (proposer or disputer) receives on settlement. This amount includes * the returned bonds as well as additional rewards. */ function settle( address requester, bytes32 identifier, uint256 timestamp, bytes memory ancillaryData ) external virtual returns (uint256 payout); /** * @notice Gets the current data structure containing all information about a price request. * @param requester sender of the initial price request. * @param identifier price identifier to identify the existing request. * @param timestamp timestamp to identify the existing request. * @param ancillaryData ancillary data of the price being requested. * @return the Request data structure. */ function getRequest( address requester, bytes32 identifier, uint256 timestamp, bytes memory ancillaryData ) public view virtual returns (Request memory); function getState( address requester, bytes32 identifier, uint256 timestamp, bytes memory ancillaryData ) public view virtual returns (State); /** * @notice Checks if a given request has resolved or been settled (i.e the optimistic oracle has a price). * @param requester sender of the initial price request. * @param identifier price identifier to identify the existing request. * @param timestamp timestamp to identify the existing request. * @param ancillaryData ancillary data of the price being requested. * @return the State. */ function hasPrice( address requester, bytes32 identifier, uint256 timestamp, bytes memory ancillaryData ) public view virtual returns (bool); } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.8.0; /** * @title A contract that provides modifiers to prevent reentrancy to state-changing and view-only methods. This contract * is inspired by https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/utils/ReentrancyGuard.sol * and https://github.com/balancer-labs/balancer-core/blob/master/contracts/BPool.sol. */ contract Lockable { bool private _notEntered; constructor() { // Storing an initial non-zero value makes deployment a bit more // expensive, but in exchange the refund on every call to nonReentrant // will be lower in amount. Since refunds are capped to a percetange of // the total transaction's gas, it is best to keep them low in cases // like this one, to increase the likelihood of the full refund coming // into effect. _notEntered = true; } /** * @dev Prevents a contract from calling itself, directly or indirectly. * Calling a `nonReentrant` function from another `nonReentrant` * function is not supported. It is possible to prevent this from happening * by making the `nonReentrant` function external, and make it call a * `private` function that does the actual work. */ modifier nonReentrant() { _preEntranceCheck(); _preEntranceSet(); _; _postEntranceReset(); } /** * @dev Designed to prevent a view-only method from being re-entered during a call to a `nonReentrant()` state-changing method. */ modifier nonReentrantView() { _preEntranceCheck(); _; } // Internal methods are used to avoid copying the require statement's bytecode to every `nonReentrant()` method. // On entry into a function, `_preEntranceCheck()` should always be called to check if the function is being re-entered. // Then, if the function modifies state, it should call `_postEntranceSet()`, perform its logic, and then call `_postEntranceReset()`. // View-only methods can simply call `_preEntranceCheck()` to make sure that it is not being re-entered. function _preEntranceCheck() internal view { // On the first call to nonReentrant, _notEntered will be true require(_notEntered, "ReentrancyGuard: reentrant call"); } function _preEntranceSet() internal { // Any calls to nonReentrant after this point will fail _notEntered = false; } function _postEntranceReset() internal { // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) _notEntered = true; } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.8.0; import "@openzeppelin/contracts/access/Ownable.sol"; import "./Lockable.sol"; /** * @title A contract to track a whitelist of addresses. */ contract AddressWhitelist is Ownable, Lockable { enum Status { None, In, Out } mapping(address => Status) public whitelist; address[] public whitelistIndices; event AddedToWhitelist(address indexed addedAddress); event RemovedFromWhitelist(address indexed removedAddress); /** * @notice Adds an address to the whitelist. * @param newElement the new address to add. */ function addToWhitelist(address newElement) external nonReentrant() onlyOwner { // Ignore if address is already included if (whitelist[newElement] == Status.In) { return; } // Only append new addresses to the array, never a duplicate if (whitelist[newElement] == Status.None) { whitelistIndices.push(newElement); } whitelist[newElement] = Status.In; emit AddedToWhitelist(newElement); } /** * @notice Removes an address from the whitelist. * @param elementToRemove the existing address to remove. */ function removeFromWhitelist(address elementToRemove) external nonReentrant() onlyOwner { if (whitelist[elementToRemove] != Status.Out) { whitelist[elementToRemove] = Status.Out; emit RemovedFromWhitelist(elementToRemove); } } /** * @notice Checks whether an address is on the whitelist. * @param elementToCheck the address to check. * @return True if `elementToCheck` is on the whitelist, or False. */ function isOnWhitelist(address elementToCheck) external view nonReentrantView() returns (bool) { return whitelist[elementToCheck] == Status.In; } /** * @notice Gets all addresses that are currently included in the whitelist. * @dev Note: This method skips over, but still iterates through addresses. It is possible for this call to run out * of gas if a large number of addresses have been removed. To reduce the likelihood of this unlikely scenario, we * can modify the implementation so that when addresses are removed, the last addresses in the array is moved to * the empty index. * @return activeWhitelist the list of addresses on the whitelist. */ function getWhitelist() external view nonReentrantView() returns (address[] memory activeWhitelist) { // Determine size of whitelist first uint256 activeCount = 0; for (uint256 i = 0; i < whitelistIndices.length; i++) { if (whitelist[whitelistIndices[i]] == Status.In) { activeCount++; } } // Populate whitelist activeWhitelist = new address[](activeCount); activeCount = 0; for (uint256 i = 0; i < whitelistIndices.length; i++) { address addr = whitelistIndices[i]; if (whitelist[addr] == Status.In) { activeWhitelist[activeCount] = addr; activeCount++; } } } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.8.0; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "../OptimisticOracle.sol"; // This is just a test contract to make requests to the optimistic oracle. contract OptimisticRequesterTest is OptimisticRequester { OptimisticOracle optimisticOracle; bool public shouldRevert = false; // State variables to track incoming calls. bytes32 public identifier; uint256 public timestamp; bytes public ancillaryData; uint256 public refund; int256 public price; // Implement collateralCurrency so that this contract simulates a financial contract whose collateral // token can be fetched by off-chain clients. IERC20 public collateralCurrency; // Manually set an expiration timestamp to simulate expiry price requests uint256 public expirationTimestamp; constructor(OptimisticOracle _optimisticOracle) { optimisticOracle = _optimisticOracle; } function requestPrice( bytes32 _identifier, uint256 _timestamp, bytes memory _ancillaryData, IERC20 currency, uint256 reward ) external { // Set collateral currency to last requested currency: collateralCurrency = currency; currency.approve(address(optimisticOracle), reward); optimisticOracle.requestPrice(_identifier, _timestamp, _ancillaryData, currency, reward); } function settleAndGetPrice( bytes32 _identifier, uint256 _timestamp, bytes memory _ancillaryData ) external returns (int256) { return optimisticOracle.settleAndGetPrice(_identifier, _timestamp, _ancillaryData); } function setBond( bytes32 _identifier, uint256 _timestamp, bytes memory _ancillaryData, uint256 bond ) external { optimisticOracle.setBond(_identifier, _timestamp, _ancillaryData, bond); } function setRefundOnDispute( bytes32 _identifier, uint256 _timestamp, bytes memory _ancillaryData ) external { optimisticOracle.setRefundOnDispute(_identifier, _timestamp, _ancillaryData); } function setCustomLiveness( bytes32 _identifier, uint256 _timestamp, bytes memory _ancillaryData, uint256 customLiveness ) external { optimisticOracle.setCustomLiveness(_identifier, _timestamp, _ancillaryData, customLiveness); } function setRevert(bool _shouldRevert) external { shouldRevert = _shouldRevert; } function setExpirationTimestamp(uint256 _expirationTimestamp) external { expirationTimestamp = _expirationTimestamp; } function clearState() external { delete identifier; delete timestamp; delete refund; delete price; } function priceProposed( bytes32 _identifier, uint256 _timestamp, bytes memory _ancillaryData ) external override { require(!shouldRevert); identifier = _identifier; timestamp = _timestamp; ancillaryData = _ancillaryData; } function priceDisputed( bytes32 _identifier, uint256 _timestamp, bytes memory _ancillaryData, uint256 _refund ) external override { require(!shouldRevert); identifier = _identifier; timestamp = _timestamp; ancillaryData = _ancillaryData; refund = _refund; } function priceSettled( bytes32 _identifier, uint256 _timestamp, bytes memory _ancillaryData, int256 _price ) external override { require(!shouldRevert); identifier = _identifier; timestamp = _timestamp; ancillaryData = _ancillaryData; price = _price; } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.8.0; pragma abicoder v2; import "@openzeppelin/contracts/utils/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; import "../../common/implementation/FixedPoint.sol"; import "../../common/implementation/MultiRole.sol"; import "../../common/implementation/Withdrawable.sol"; import "../../common/implementation/Testable.sol"; import "../interfaces/StoreInterface.sol"; /** * @title An implementation of Store that can accept Oracle fees in ETH or any arbitrary ERC20 token. */ contract Store is StoreInterface, Withdrawable, Testable { using SafeMath for uint256; using FixedPoint for FixedPoint.Unsigned; using FixedPoint for uint256; using SafeERC20 for IERC20; /**************************************** * INTERNAL VARIABLES AND STORAGE * ****************************************/ enum Roles { Owner, Withdrawer } FixedPoint.Unsigned public fixedOracleFeePerSecondPerPfc; // Percentage of 1 E.g., .1 is 10% Oracle fee. FixedPoint.Unsigned public weeklyDelayFeePerSecondPerPfc; // Percentage of 1 E.g., .1 is 10% weekly delay fee. mapping(address => FixedPoint.Unsigned) public finalFees; uint256 public constant SECONDS_PER_WEEK = 604800; /**************************************** * EVENTS * ****************************************/ event NewFixedOracleFeePerSecondPerPfc(FixedPoint.Unsigned newOracleFee); event NewWeeklyDelayFeePerSecondPerPfc(FixedPoint.Unsigned newWeeklyDelayFeePerSecondPerPfc); event NewFinalFee(FixedPoint.Unsigned newFinalFee); /** * @notice Construct the Store contract. */ constructor( FixedPoint.Unsigned memory _fixedOracleFeePerSecondPerPfc, FixedPoint.Unsigned memory _weeklyDelayFeePerSecondPerPfc, address _timerAddress ) Testable(_timerAddress) { _createExclusiveRole(uint256(Roles.Owner), uint256(Roles.Owner), msg.sender); _createWithdrawRole(uint256(Roles.Withdrawer), uint256(Roles.Owner), msg.sender); setFixedOracleFeePerSecondPerPfc(_fixedOracleFeePerSecondPerPfc); setWeeklyDelayFeePerSecondPerPfc(_weeklyDelayFeePerSecondPerPfc); } /**************************************** * ORACLE FEE CALCULATION AND PAYMENT * ****************************************/ /** * @notice Pays Oracle fees in ETH to the store. * @dev To be used by contracts whose margin currency is ETH. */ function payOracleFees() external payable override { require(msg.value > 0, "Value sent can't be zero"); } /** * @notice Pays oracle fees in the margin currency, erc20Address, to the store. * @dev To be used if the margin currency is an ERC20 token rather than ETH. * @param erc20Address address of the ERC20 token used to pay the fee. * @param amount number of tokens to transfer. An approval for at least this amount must exist. */ function payOracleFeesErc20(address erc20Address, FixedPoint.Unsigned calldata amount) external override { IERC20 erc20 = IERC20(erc20Address); require(amount.isGreaterThan(0), "Amount sent can't be zero"); erc20.safeTransferFrom(msg.sender, address(this), amount.rawValue); } /** * @notice Computes the regular oracle fees that a contract should pay for a period. * @dev The late penalty is similar to the regular fee in that is is charged per second over the period between * startTime and endTime. * * The late penalty percentage increases over time as follows: * * - 0-1 week since startTime: no late penalty * * - 1-2 weeks since startTime: 1x late penalty percentage is applied * * - 2-3 weeks since startTime: 2x late penalty percentage is applied * * - ... * * @param startTime defines the beginning time from which the fee is paid. * @param endTime end time until which the fee is paid. * @param pfc "profit from corruption", or the maximum amount of margin currency that a * token sponsor could extract from the contract through corrupting the price feed in their favor. * @return regularFee amount owed for the duration from start to end time for the given pfc. * @return latePenalty penalty percentage, if any, for paying the fee after the deadline. */ function computeRegularFee( uint256 startTime, uint256 endTime, FixedPoint.Unsigned calldata pfc ) external view override returns (FixedPoint.Unsigned memory regularFee, FixedPoint.Unsigned memory latePenalty) { uint256 timeDiff = endTime.sub(startTime); // Multiply by the unscaled `timeDiff` first, to get more accurate results. regularFee = pfc.mul(timeDiff).mul(fixedOracleFeePerSecondPerPfc); // Compute how long ago the start time was to compute the delay penalty. uint256 paymentDelay = getCurrentTime().sub(startTime); // Compute the additional percentage (per second) that will be charged because of the penalty. // Note: if less than a week has gone by since the startTime, paymentDelay / SECONDS_PER_WEEK will truncate to // 0, causing no penalty to be charged. FixedPoint.Unsigned memory penaltyPercentagePerSecond = weeklyDelayFeePerSecondPerPfc.mul(paymentDelay.div(SECONDS_PER_WEEK)); // Apply the penaltyPercentagePerSecond to the payment period. latePenalty = pfc.mul(timeDiff).mul(penaltyPercentagePerSecond); } /** * @notice Computes the final oracle fees that a contract should pay at settlement. * @param currency token used to pay the final fee. * @return finalFee amount due denominated in units of `currency`. */ function computeFinalFee(address currency) external view override returns (FixedPoint.Unsigned memory) { return finalFees[currency]; } /**************************************** * ADMIN STATE MODIFYING FUNCTIONS * ****************************************/ /** * @notice Sets a new oracle fee per second. * @param newFixedOracleFeePerSecondPerPfc new fee per second charged to use the oracle. */ function setFixedOracleFeePerSecondPerPfc(FixedPoint.Unsigned memory newFixedOracleFeePerSecondPerPfc) public onlyRoleHolder(uint256(Roles.Owner)) { // Oracle fees at or over 100% don't make sense. require(newFixedOracleFeePerSecondPerPfc.isLessThan(1), "Fee must be < 100% per second."); fixedOracleFeePerSecondPerPfc = newFixedOracleFeePerSecondPerPfc; emit NewFixedOracleFeePerSecondPerPfc(newFixedOracleFeePerSecondPerPfc); } /** * @notice Sets a new weekly delay fee. * @param newWeeklyDelayFeePerSecondPerPfc fee escalation per week of late fee payment. */ function setWeeklyDelayFeePerSecondPerPfc(FixedPoint.Unsigned memory newWeeklyDelayFeePerSecondPerPfc) public onlyRoleHolder(uint256(Roles.Owner)) { require(newWeeklyDelayFeePerSecondPerPfc.isLessThan(1), "weekly delay fee must be < 100%"); weeklyDelayFeePerSecondPerPfc = newWeeklyDelayFeePerSecondPerPfc; emit NewWeeklyDelayFeePerSecondPerPfc(newWeeklyDelayFeePerSecondPerPfc); } /** * @notice Sets a new final fee for a particular currency. * @param currency defines the token currency used to pay the final fee. * @param newFinalFee final fee amount. */ function setFinalFee(address currency, FixedPoint.Unsigned memory newFinalFee) public onlyRoleHolder(uint256(Roles.Owner)) { finalFees[currency] = newFinalFee; emit NewFinalFee(newFinalFee); } } /** * Withdrawable contract. */ // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.8.0; import "@openzeppelin/contracts/utils/Address.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; import "./MultiRole.sol"; /** * @title Base contract that allows a specific role to withdraw any ETH and/or ERC20 tokens that the contract holds. */ abstract contract Withdrawable is MultiRole { using SafeERC20 for IERC20; uint256 private roleId; /** * @notice Withdraws ETH from the contract. */ function withdraw(uint256 amount) external onlyRoleHolder(roleId) { Address.sendValue(payable(msg.sender), amount); } /** * @notice Withdraws ERC20 tokens from the contract. * @param erc20Address ERC20 token to withdraw. * @param amount amount of tokens to withdraw. */ function withdrawErc20(address erc20Address, uint256 amount) external onlyRoleHolder(roleId) { IERC20 erc20 = IERC20(erc20Address); erc20.safeTransfer(msg.sender, amount); } /** * @notice Internal method that allows derived contracts to create a role for withdrawal. * @dev Either this method or `_setWithdrawRole` must be called by the derived class for this contract to function * properly. * @param newRoleId ID corresponding to role whose members can withdraw. * @param managingRoleId ID corresponding to managing role who can modify the withdrawable role's membership. * @param withdrawerAddress new manager of withdrawable role. */ function _createWithdrawRole( uint256 newRoleId, uint256 managingRoleId, address withdrawerAddress ) internal { roleId = newRoleId; _createExclusiveRole(newRoleId, managingRoleId, withdrawerAddress); } /** * @notice Internal method that allows derived contracts to choose the role for withdrawal. * @dev The role `setRoleId` must exist. Either this method or `_createWithdrawRole` must be * called by the derived class for this contract to function properly. * @param setRoleId ID corresponding to role whose members can withdraw. */ function _setWithdrawRole(uint256 setRoleId) internal onlyValidRole(setRoleId) { roleId = setRoleId; } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.8.0; pragma abicoder v2; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; import "../../common/implementation/Lockable.sol"; import "../../common/implementation/FixedPoint.sol"; import "../../common/implementation/Testable.sol"; import "../../oracle/interfaces/StoreInterface.sol"; import "../../oracle/interfaces/FinderInterface.sol"; import "../../oracle/interfaces/AdministrateeInterface.sol"; import "../../oracle/implementation/Constants.sol"; /** * @title FeePayer contract. * @notice Provides fee payment functionality for the ExpiringMultiParty contract. * contract is abstract as each derived contract that inherits `FeePayer` must implement `pfc()`. */ abstract contract FeePayer is AdministrateeInterface, Testable, Lockable { using SafeMath for uint256; using FixedPoint for FixedPoint.Unsigned; using SafeERC20 for IERC20; /**************************************** * FEE PAYER DATA STRUCTURES * ****************************************/ // The collateral currency used to back the positions in this contract. IERC20 public collateralCurrency; // Finder contract used to look up addresses for UMA system contracts. FinderInterface public finder; // Tracks the last block time when the fees were paid. uint256 private lastPaymentTime; // Tracks the cumulative fees that have been paid by the contract for use by derived contracts. // The multiplier starts at 1, and is updated by computing cumulativeFeeMultiplier * (1 - effectiveFee). // Put another way, the cumulativeFeeMultiplier is (1 - effectiveFee1) * (1 - effectiveFee2) ... // For example: // The cumulativeFeeMultiplier should start at 1. // If a 1% fee is charged, the multiplier should update to .99. // If another 1% fee is charged, the multiplier should be 0.99^2 (0.9801). FixedPoint.Unsigned public cumulativeFeeMultiplier; /**************************************** * EVENTS * ****************************************/ event RegularFeesPaid(uint256 indexed regularFee, uint256 indexed lateFee); event FinalFeesPaid(uint256 indexed amount); /**************************************** * MODIFIERS * ****************************************/ // modifier that calls payRegularFees(). modifier fees virtual { // Note: the regular fee is applied on every fee-accruing transaction, where the total change is simply the // regular fee applied linearly since the last update. This implies that the compounding rate depends on the // frequency of update transactions that have this modifier, and it never reaches the ideal of continuous // compounding. This approximate-compounding pattern is common in the Ethereum ecosystem because of the // complexity of compounding data on-chain. payRegularFees(); _; } /** * @notice Constructs the FeePayer contract. Called by child contracts. * @param _collateralAddress ERC20 token that is used as the underlying collateral for the synthetic. * @param _finderAddress UMA protocol Finder used to discover other protocol contracts. * @param _timerAddress Contract that stores the current time in a testing environment. * Must be set to 0x0 for production environments that use live time. */ constructor( address _collateralAddress, address _finderAddress, address _timerAddress ) Testable(_timerAddress) { collateralCurrency = IERC20(_collateralAddress); finder = FinderInterface(_finderAddress); lastPaymentTime = getCurrentTime(); cumulativeFeeMultiplier = FixedPoint.fromUnscaledUint(1); } /**************************************** * FEE PAYMENT FUNCTIONS * ****************************************/ /** * @notice Pays UMA DVM regular fees (as a % of the collateral pool) to the Store contract. * @dev These must be paid periodically for the life of the contract. If the contract has not paid its regular fee * in a week or more then a late penalty is applied which is sent to the caller. If the amount of * fees owed are greater than the pfc, then this will pay as much as possible from the available collateral. * An event is only fired if the fees charged are greater than 0. * @return totalPaid Amount of collateral that the contract paid (sum of the amount paid to the Store and caller). * This returns 0 and exit early if there is no pfc, fees were already paid during the current block, or the fee rate is 0. */ function payRegularFees() public nonReentrant() returns (FixedPoint.Unsigned memory) { uint256 time = getCurrentTime(); FixedPoint.Unsigned memory collateralPool = _pfc(); // Fetch the regular fees, late penalty and the max possible to pay given the current collateral within the contract. ( FixedPoint.Unsigned memory regularFee, FixedPoint.Unsigned memory latePenalty, FixedPoint.Unsigned memory totalPaid ) = getOutstandingRegularFees(time); lastPaymentTime = time; // If there are no fees to pay then exit early. if (totalPaid.isEqual(0)) { return totalPaid; } emit RegularFeesPaid(regularFee.rawValue, latePenalty.rawValue); _adjustCumulativeFeeMultiplier(totalPaid, collateralPool); if (regularFee.isGreaterThan(0)) { StoreInterface store = _getStore(); collateralCurrency.safeIncreaseAllowance(address(store), regularFee.rawValue); store.payOracleFeesErc20(address(collateralCurrency), regularFee); } if (latePenalty.isGreaterThan(0)) { collateralCurrency.safeTransfer(msg.sender, latePenalty.rawValue); } return totalPaid; } /** * @notice Fetch any regular fees that the contract has pending but has not yet paid. If the fees to be paid are more * than the total collateral within the contract then the totalPaid returned is full contract collateral amount. * @dev This returns 0 and exit early if there is no pfc, fees were already paid during the current block, or the fee rate is 0. * @return regularFee outstanding unpaid regular fee. * @return latePenalty outstanding unpaid late fee for being late in previous fee payments. * @return totalPaid Amount of collateral that the contract paid (sum of the amount paid to the Store and caller). */ function getOutstandingRegularFees(uint256 time) public view returns ( FixedPoint.Unsigned memory regularFee, FixedPoint.Unsigned memory latePenalty, FixedPoint.Unsigned memory totalPaid ) { StoreInterface store = _getStore(); FixedPoint.Unsigned memory collateralPool = _pfc(); // Exit early if there is no collateral or if fees were already paid during this block. if (collateralPool.isEqual(0) || lastPaymentTime == time) { return (regularFee, latePenalty, totalPaid); } (regularFee, latePenalty) = store.computeRegularFee(lastPaymentTime, time, collateralPool); totalPaid = regularFee.add(latePenalty); if (totalPaid.isEqual(0)) { return (regularFee, latePenalty, totalPaid); } // If the effective fees paid as a % of the pfc is > 100%, then we need to reduce it and make the contract pay // as much of the fee that it can (up to 100% of its pfc). We'll reduce the late penalty first and then the // regular fee, which has the effect of paying the store first, followed by the caller if there is any fee remaining. if (totalPaid.isGreaterThan(collateralPool)) { FixedPoint.Unsigned memory deficit = totalPaid.sub(collateralPool); FixedPoint.Unsigned memory latePenaltyReduction = FixedPoint.min(latePenalty, deficit); latePenalty = latePenalty.sub(latePenaltyReduction); deficit = deficit.sub(latePenaltyReduction); regularFee = regularFee.sub(FixedPoint.min(regularFee, deficit)); totalPaid = collateralPool; } } /** * @notice Gets the current profit from corruption for this contract in terms of the collateral currency. * @dev This is equivalent to the collateral pool available from which to pay fees. Therefore, derived contracts are * expected to implement this so that pay-fee methods can correctly compute the owed fees as a % of PfC. * @return pfc value for equal to the current profit from corruption denominated in collateral currency. */ function pfc() external view override nonReentrantView() returns (FixedPoint.Unsigned memory) { return _pfc(); } /** * @notice Removes excess collateral balance not counted in the PfC by distributing it out pro-rata to all sponsors. * @dev Multiplying the `cumulativeFeeMultiplier` by the ratio of non-PfC-collateral :: PfC-collateral effectively * pays all sponsors a pro-rata portion of the excess collateral. * @dev This will revert if PfC is 0 and this contract's collateral balance > 0. */ function gulp() external nonReentrant() { _gulp(); } /**************************************** * INTERNAL FUNCTIONS * ****************************************/ // Pays UMA Oracle final fees of `amount` in `collateralCurrency` to the Store contract. Final fee is a flat fee // charged for each price request. If payer is the contract, adjusts internal bookkeeping variables. If payer is not // the contract, pulls in `amount` of collateral currency. function _payFinalFees(address payer, FixedPoint.Unsigned memory amount) internal { if (amount.isEqual(0)) { return; } if (payer != address(this)) { // If the payer is not the contract pull the collateral from the payer. collateralCurrency.safeTransferFrom(payer, address(this), amount.rawValue); } else { // If the payer is the contract, adjust the cumulativeFeeMultiplier to compensate. FixedPoint.Unsigned memory collateralPool = _pfc(); // The final fee must be < available collateral or the fee will be larger than 100%. // Note: revert reason removed to save bytecode. require(collateralPool.isGreaterThan(amount)); _adjustCumulativeFeeMultiplier(amount, collateralPool); } emit FinalFeesPaid(amount.rawValue); StoreInterface store = _getStore(); collateralCurrency.safeIncreaseAllowance(address(store), amount.rawValue); store.payOracleFeesErc20(address(collateralCurrency), amount); } function _gulp() internal { FixedPoint.Unsigned memory currentPfc = _pfc(); FixedPoint.Unsigned memory currentBalance = FixedPoint.Unsigned(collateralCurrency.balanceOf(address(this))); if (currentPfc.isLessThan(currentBalance)) { cumulativeFeeMultiplier = cumulativeFeeMultiplier.mul(currentBalance.div(currentPfc)); } } function _pfc() internal view virtual returns (FixedPoint.Unsigned memory); function _getStore() internal view returns (StoreInterface) { return StoreInterface(finder.getImplementationAddress(OracleInterfaces.Store)); } function _computeFinalFees() internal view returns (FixedPoint.Unsigned memory finalFees) { StoreInterface store = _getStore(); return store.computeFinalFee(address(collateralCurrency)); } // Returns the user's collateral minus any fees that have been subtracted since it was originally // deposited into the contract. Note: if the contract has paid fees since it was deployed, the raw // value should be larger than the returned value. function _getFeeAdjustedCollateral(FixedPoint.Unsigned memory rawCollateral) internal view returns (FixedPoint.Unsigned memory collateral) { return rawCollateral.mul(cumulativeFeeMultiplier); } // Returns the user's collateral minus any pending fees that have yet to be subtracted. function _getPendingRegularFeeAdjustedCollateral(FixedPoint.Unsigned memory rawCollateral) internal view returns (FixedPoint.Unsigned memory) { (, , FixedPoint.Unsigned memory currentTotalOutstandingRegularFees) = getOutstandingRegularFees(getCurrentTime()); if (currentTotalOutstandingRegularFees.isEqual(FixedPoint.fromUnscaledUint(0))) return rawCollateral; // Calculate the total outstanding regular fee as a fraction of the total contract PFC. FixedPoint.Unsigned memory effectiveOutstandingFee = currentTotalOutstandingRegularFees.divCeil(_pfc()); // Scale as rawCollateral* (1 - effectiveOutstandingFee) to apply the pro-rata amount to the regular fee. return rawCollateral.mul(FixedPoint.fromUnscaledUint(1).sub(effectiveOutstandingFee)); } // Converts a user-readable collateral value into a raw value that accounts for already-assessed fees. If any fees // have been taken from this contract in the past, then the raw value will be larger than the user-readable value. function _convertToRawCollateral(FixedPoint.Unsigned memory collateral) internal view returns (FixedPoint.Unsigned memory rawCollateral) { return collateral.div(cumulativeFeeMultiplier); } // Decrease rawCollateral by a fee-adjusted collateralToRemove amount. Fee adjustment scales up collateralToRemove // by dividing it by cumulativeFeeMultiplier. There is potential for this quotient to be floored, therefore // rawCollateral is decreased by less than expected. Because this method is usually called in conjunction with an // actual removal of collateral from this contract, return the fee-adjusted amount that the rawCollateral is // decreased by so that the caller can minimize error between collateral removed and rawCollateral debited. function _removeCollateral(FixedPoint.Unsigned storage rawCollateral, FixedPoint.Unsigned memory collateralToRemove) internal returns (FixedPoint.Unsigned memory removedCollateral) { FixedPoint.Unsigned memory initialBalance = _getFeeAdjustedCollateral(rawCollateral); FixedPoint.Unsigned memory adjustedCollateral = _convertToRawCollateral(collateralToRemove); rawCollateral.rawValue = rawCollateral.sub(adjustedCollateral).rawValue; removedCollateral = initialBalance.sub(_getFeeAdjustedCollateral(rawCollateral)); } // Increase rawCollateral by a fee-adjusted collateralToAdd amount. Fee adjustment scales up collateralToAdd // by dividing it by cumulativeFeeMultiplier. There is potential for this quotient to be floored, therefore // rawCollateral is increased by less than expected. Because this method is usually called in conjunction with an // actual addition of collateral to this contract, return the fee-adjusted amount that the rawCollateral is // increased by so that the caller can minimize error between collateral added and rawCollateral credited. // NOTE: This return value exists only for the sake of symmetry with _removeCollateral. We don't actually use it // because we are OK if more collateral is stored in the contract than is represented by rawTotalPositionCollateral. function _addCollateral(FixedPoint.Unsigned storage rawCollateral, FixedPoint.Unsigned memory collateralToAdd) internal returns (FixedPoint.Unsigned memory addedCollateral) { FixedPoint.Unsigned memory initialBalance = _getFeeAdjustedCollateral(rawCollateral); FixedPoint.Unsigned memory adjustedCollateral = _convertToRawCollateral(collateralToAdd); rawCollateral.rawValue = rawCollateral.add(adjustedCollateral).rawValue; addedCollateral = _getFeeAdjustedCollateral(rawCollateral).sub(initialBalance); } // Scale the cumulativeFeeMultiplier by the ratio of fees paid to the current available collateral. function _adjustCumulativeFeeMultiplier(FixedPoint.Unsigned memory amount, FixedPoint.Unsigned memory currentPfc) internal { FixedPoint.Unsigned memory effectiveFee = amount.divCeil(currentPfc); cumulativeFeeMultiplier = cumulativeFeeMultiplier.mul(FixedPoint.fromUnscaledUint(1).sub(effectiveFee)); } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.8.0; pragma abicoder v2; import "../../common/implementation/FixedPoint.sol"; /** * @title Interface that all financial contracts expose to the admin. */ interface AdministrateeInterface { /** * @notice Initiates the shutdown process, in case of an emergency. */ function emergencyShutdown() external; /** * @notice A core contract method called independently or as a part of other financial contract transactions. * @dev It pays fees and moves money between margin accounts to make sure they reflect the NAV of the contract. */ function remargin() external; /** * @notice Gets the current profit from corruption for this contract in terms of the collateral currency. * @dev This is equivalent to the collateral pool available from which to pay fees. Therefore, derived contracts are * expected to implement this so that pay-fee methods can correctly compute the owed fees as a % of PfC. * @return pfc value for equal to the current profit from corruption denominated in collateral currency. */ function pfc() external view returns (FixedPoint.Unsigned memory); } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.8.0; pragma abicoder v2; import "@openzeppelin/contracts/utils/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; import "@openzeppelin/contracts/utils/Address.sol"; import "../../common/implementation/FixedPoint.sol"; import "../../common/interfaces/ExpandedIERC20.sol"; import "../../common/interfaces/IERC20Standard.sol"; import "../../oracle/interfaces/OracleInterface.sol"; import "../../oracle/interfaces/OptimisticOracleInterface.sol"; import "../../oracle/interfaces/IdentifierWhitelistInterface.sol"; import "../../oracle/implementation/Constants.sol"; import "../common/FeePayer.sol"; import "../common/financial-product-libraries/FinancialProductLibrary.sol"; /** * @title Financial contract with priceless position management. * @notice Handles positions for multiple sponsors in an optimistic (i.e., priceless) way without relying * on a price feed. On construction, deploys a new ERC20, managed by this contract, that is the synthetic token. */ contract PricelessPositionManager is FeePayer { using SafeMath for uint256; using FixedPoint for FixedPoint.Unsigned; using SafeERC20 for IERC20; using SafeERC20 for ExpandedIERC20; using Address for address; /**************************************** * PRICELESS POSITION DATA STRUCTURES * ****************************************/ // Stores the state of the PricelessPositionManager. Set on expiration, emergency shutdown, or settlement. enum ContractState { Open, ExpiredPriceRequested, ExpiredPriceReceived } ContractState public contractState; // Represents a single sponsor's position. All collateral is held by this contract. // This struct acts as bookkeeping for how much of that collateral is allocated to each sponsor. struct PositionData { FixedPoint.Unsigned tokensOutstanding; // Tracks pending withdrawal requests. A withdrawal request is pending if `withdrawalRequestPassTimestamp != 0`. uint256 withdrawalRequestPassTimestamp; FixedPoint.Unsigned withdrawalRequestAmount; // Raw collateral value. This value should never be accessed directly -- always use _getFeeAdjustedCollateral(). // To add or remove collateral, use _addCollateral() and _removeCollateral(). FixedPoint.Unsigned rawCollateral; // Tracks pending transfer position requests. A transfer position request is pending if `transferPositionRequestPassTimestamp != 0`. uint256 transferPositionRequestPassTimestamp; } // Maps sponsor addresses to their positions. Each sponsor can have only one position. mapping(address => PositionData) public positions; // Keep track of the total collateral and tokens across all positions to enable calculating the // global collateralization ratio without iterating over all positions. FixedPoint.Unsigned public totalTokensOutstanding; // Similar to the rawCollateral in PositionData, this value should not be used directly. // _getFeeAdjustedCollateral(), _addCollateral() and _removeCollateral() must be used to access and adjust. FixedPoint.Unsigned public rawTotalPositionCollateral; // Synthetic token created by this contract. ExpandedIERC20 public tokenCurrency; // Unique identifier for DVM price feed ticker. bytes32 public priceIdentifier; // Time that this contract expires. Should not change post-construction unless an emergency shutdown occurs. uint256 public expirationTimestamp; // Time that has to elapse for a withdrawal request to be considered passed, if no liquidations occur. // !!Note: The lower the withdrawal liveness value, the more risk incurred by the contract. // Extremely low liveness values increase the chance that opportunistic invalid withdrawal requests // expire without liquidation, thereby increasing the insolvency risk for the contract as a whole. An insolvent // contract is extremely risky for any sponsor or synthetic token holder for the contract. uint256 public withdrawalLiveness; // Minimum number of tokens in a sponsor's position. FixedPoint.Unsigned public minSponsorTokens; // The expiry price pulled from the DVM. FixedPoint.Unsigned public expiryPrice; // Instance of FinancialProductLibrary to provide custom price and collateral requirement transformations to extend // the functionality of the EMP to support a wider range of financial products. FinancialProductLibrary public financialProductLibrary; /**************************************** * EVENTS * ****************************************/ event RequestTransferPosition(address indexed oldSponsor); event RequestTransferPositionExecuted(address indexed oldSponsor, address indexed newSponsor); event RequestTransferPositionCanceled(address indexed oldSponsor); event Deposit(address indexed sponsor, uint256 indexed collateralAmount); event Withdrawal(address indexed sponsor, uint256 indexed collateralAmount); event RequestWithdrawal(address indexed sponsor, uint256 indexed collateralAmount); event RequestWithdrawalExecuted(address indexed sponsor, uint256 indexed collateralAmount); event RequestWithdrawalCanceled(address indexed sponsor, uint256 indexed collateralAmount); event PositionCreated(address indexed sponsor, uint256 indexed collateralAmount, uint256 indexed tokenAmount); event NewSponsor(address indexed sponsor); event EndedSponsorPosition(address indexed sponsor); event Repay(address indexed sponsor, uint256 indexed numTokensRepaid, uint256 indexed newTokenCount); event Redeem(address indexed sponsor, uint256 indexed collateralAmount, uint256 indexed tokenAmount); event ContractExpired(address indexed caller); event SettleExpiredPosition( address indexed caller, uint256 indexed collateralReturned, uint256 indexed tokensBurned ); event EmergencyShutdown(address indexed caller, uint256 originalExpirationTimestamp, uint256 shutdownTimestamp); /**************************************** * MODIFIERS * ****************************************/ modifier onlyPreExpiration() { _onlyPreExpiration(); _; } modifier onlyPostExpiration() { _onlyPostExpiration(); _; } modifier onlyCollateralizedPosition(address sponsor) { _onlyCollateralizedPosition(sponsor); _; } // Check that the current state of the pricelessPositionManager is Open. // This prevents multiple calls to `expire` and `EmergencyShutdown` post expiration. modifier onlyOpenState() { _onlyOpenState(); _; } modifier noPendingWithdrawal(address sponsor) { _positionHasNoPendingWithdrawal(sponsor); _; } /** * @notice Construct the PricelessPositionManager * @dev Deployer of this contract should consider carefully which parties have ability to mint and burn * the synthetic tokens referenced by `_tokenAddress`. This contract's security assumes that no external accounts * can mint new tokens, which could be used to steal all of this contract's locked collateral. * We recommend to only use synthetic token contracts whose sole Owner role (the role capable of adding & removing roles) * is assigned to this contract, whose sole Minter role is assigned to this contract, and whose * total supply is 0 prior to construction of this contract. * @param _expirationTimestamp unix timestamp of when the contract will expire. * @param _withdrawalLiveness liveness delay, in seconds, for pending withdrawals. * @param _collateralAddress ERC20 token used as collateral for all positions. * @param _tokenAddress ERC20 token used as synthetic token. * @param _finderAddress UMA protocol Finder used to discover other protocol contracts. * @param _priceIdentifier registered in the DVM for the synthetic. * @param _minSponsorTokens minimum number of tokens that must exist at any time in a position. * @param _timerAddress Contract that stores the current time in a testing environment. * Must be set to 0x0 for production environments that use live time. * @param _financialProductLibraryAddress Contract providing contract state transformations. */ constructor( uint256 _expirationTimestamp, uint256 _withdrawalLiveness, address _collateralAddress, address _tokenAddress, address _finderAddress, bytes32 _priceIdentifier, FixedPoint.Unsigned memory _minSponsorTokens, address _timerAddress, address _financialProductLibraryAddress ) FeePayer(_collateralAddress, _finderAddress, _timerAddress) nonReentrant() { require(_expirationTimestamp > getCurrentTime()); require(_getIdentifierWhitelist().isIdentifierSupported(_priceIdentifier)); expirationTimestamp = _expirationTimestamp; withdrawalLiveness = _withdrawalLiveness; tokenCurrency = ExpandedIERC20(_tokenAddress); minSponsorTokens = _minSponsorTokens; priceIdentifier = _priceIdentifier; // Initialize the financialProductLibrary at the provided address. financialProductLibrary = FinancialProductLibrary(_financialProductLibraryAddress); } /**************************************** * POSITION FUNCTIONS * ****************************************/ /** * @notice Requests to transfer ownership of the caller's current position to a new sponsor address. * Once the request liveness is passed, the sponsor can execute the transfer and specify the new sponsor. * @dev The liveness length is the same as the withdrawal liveness. */ function requestTransferPosition() public onlyPreExpiration() nonReentrant() { PositionData storage positionData = _getPositionData(msg.sender); require(positionData.transferPositionRequestPassTimestamp == 0); // Make sure the proposed expiration of this request is not post-expiry. uint256 requestPassTime = getCurrentTime().add(withdrawalLiveness); require(requestPassTime < expirationTimestamp); // Update the position object for the user. positionData.transferPositionRequestPassTimestamp = requestPassTime; emit RequestTransferPosition(msg.sender); } /** * @notice After a passed transfer position request (i.e., by a call to `requestTransferPosition` and waiting * `withdrawalLiveness`), transfers ownership of the caller's current position to `newSponsorAddress`. * @dev Transferring positions can only occur if the recipient does not already have a position. * @param newSponsorAddress is the address to which the position will be transferred. */ function transferPositionPassedRequest(address newSponsorAddress) public onlyPreExpiration() noPendingWithdrawal(msg.sender) nonReentrant() { require( _getFeeAdjustedCollateral(positions[newSponsorAddress].rawCollateral).isEqual( FixedPoint.fromUnscaledUint(0) ) ); PositionData storage positionData = _getPositionData(msg.sender); require( positionData.transferPositionRequestPassTimestamp != 0 && positionData.transferPositionRequestPassTimestamp <= getCurrentTime() ); // Reset transfer request. positionData.transferPositionRequestPassTimestamp = 0; positions[newSponsorAddress] = positionData; delete positions[msg.sender]; emit RequestTransferPositionExecuted(msg.sender, newSponsorAddress); emit NewSponsor(newSponsorAddress); emit EndedSponsorPosition(msg.sender); } /** * @notice Cancels a pending transfer position request. */ function cancelTransferPosition() external onlyPreExpiration() nonReentrant() { PositionData storage positionData = _getPositionData(msg.sender); require(positionData.transferPositionRequestPassTimestamp != 0); emit RequestTransferPositionCanceled(msg.sender); // Reset withdrawal request. positionData.transferPositionRequestPassTimestamp = 0; } /** * @notice Transfers `collateralAmount` of `collateralCurrency` into the specified sponsor's position. * @dev Increases the collateralization level of a position after creation. This contract must be approved to spend * at least `collateralAmount` of `collateralCurrency`. * @param sponsor the sponsor to credit the deposit to. * @param collateralAmount total amount of collateral tokens to be sent to the sponsor's position. */ function depositTo(address sponsor, FixedPoint.Unsigned memory collateralAmount) public onlyPreExpiration() noPendingWithdrawal(sponsor) fees() nonReentrant() { require(collateralAmount.isGreaterThan(0)); PositionData storage positionData = _getPositionData(sponsor); // Increase the position and global collateral balance by collateral amount. _incrementCollateralBalances(positionData, collateralAmount); emit Deposit(sponsor, collateralAmount.rawValue); // Move collateral currency from sender to contract. collateralCurrency.safeTransferFrom(msg.sender, address(this), collateralAmount.rawValue); } /** * @notice Transfers `collateralAmount` of `collateralCurrency` into the caller's position. * @dev Increases the collateralization level of a position after creation. This contract must be approved to spend * at least `collateralAmount` of `collateralCurrency`. * @param collateralAmount total amount of collateral tokens to be sent to the sponsor's position. */ function deposit(FixedPoint.Unsigned memory collateralAmount) public { // This is just a thin wrapper over depositTo that specified the sender as the sponsor. depositTo(msg.sender, collateralAmount); } /** * @notice Transfers `collateralAmount` of `collateralCurrency` from the sponsor's position to the sponsor. * @dev Reverts if the withdrawal puts this position's collateralization ratio below the global collateralization * ratio. In that case, use `requestWithdrawal`. Might not withdraw the full requested amount to account for precision loss. * @param collateralAmount is the amount of collateral to withdraw. * @return amountWithdrawn The actual amount of collateral withdrawn. */ function withdraw(FixedPoint.Unsigned memory collateralAmount) public onlyPreExpiration() noPendingWithdrawal(msg.sender) fees() nonReentrant() returns (FixedPoint.Unsigned memory amountWithdrawn) { require(collateralAmount.isGreaterThan(0)); PositionData storage positionData = _getPositionData(msg.sender); // Decrement the sponsor's collateral and global collateral amounts. Check the GCR between decrement to ensure // position remains above the GCR within the withdrawal. If this is not the case the caller must submit a request. amountWithdrawn = _decrementCollateralBalancesCheckGCR(positionData, collateralAmount); emit Withdrawal(msg.sender, amountWithdrawn.rawValue); // Move collateral currency from contract to sender. // Note: that we move the amount of collateral that is decreased from rawCollateral (inclusive of fees) // instead of the user requested amount. This eliminates precision loss that could occur // where the user withdraws more collateral than rawCollateral is decremented by. collateralCurrency.safeTransfer(msg.sender, amountWithdrawn.rawValue); } /** * @notice Starts a withdrawal request that, if passed, allows the sponsor to withdraw` from their position. * @dev The request will be pending for `withdrawalLiveness`, during which the position can be liquidated. * @param collateralAmount the amount of collateral requested to withdraw */ function requestWithdrawal(FixedPoint.Unsigned memory collateralAmount) public onlyPreExpiration() noPendingWithdrawal(msg.sender) nonReentrant() { PositionData storage positionData = _getPositionData(msg.sender); require( collateralAmount.isGreaterThan(0) && collateralAmount.isLessThanOrEqual(_getFeeAdjustedCollateral(positionData.rawCollateral)) ); // Make sure the proposed expiration of this request is not post-expiry. uint256 requestPassTime = getCurrentTime().add(withdrawalLiveness); require(requestPassTime < expirationTimestamp); // Update the position object for the user. positionData.withdrawalRequestPassTimestamp = requestPassTime; positionData.withdrawalRequestAmount = collateralAmount; emit RequestWithdrawal(msg.sender, collateralAmount.rawValue); } /** * @notice After a passed withdrawal request (i.e., by a call to `requestWithdrawal` and waiting * `withdrawalLiveness`), withdraws `positionData.withdrawalRequestAmount` of collateral currency. * @dev Might not withdraw the full requested amount in order to account for precision loss or if the full requested * amount exceeds the collateral in the position (due to paying fees). * @return amountWithdrawn The actual amount of collateral withdrawn. */ function withdrawPassedRequest() external onlyPreExpiration() fees() nonReentrant() returns (FixedPoint.Unsigned memory amountWithdrawn) { PositionData storage positionData = _getPositionData(msg.sender); require( positionData.withdrawalRequestPassTimestamp != 0 && positionData.withdrawalRequestPassTimestamp <= getCurrentTime() ); // If withdrawal request amount is > position collateral, then withdraw the full collateral amount. // This situation is possible due to fees charged since the withdrawal was originally requested. FixedPoint.Unsigned memory amountToWithdraw = positionData.withdrawalRequestAmount; if (positionData.withdrawalRequestAmount.isGreaterThan(_getFeeAdjustedCollateral(positionData.rawCollateral))) { amountToWithdraw = _getFeeAdjustedCollateral(positionData.rawCollateral); } // Decrement the sponsor's collateral and global collateral amounts. amountWithdrawn = _decrementCollateralBalances(positionData, amountToWithdraw); // Reset withdrawal request by setting withdrawal amount and withdrawal timestamp to 0. _resetWithdrawalRequest(positionData); // Transfer approved withdrawal amount from the contract to the caller. collateralCurrency.safeTransfer(msg.sender, amountWithdrawn.rawValue); emit RequestWithdrawalExecuted(msg.sender, amountWithdrawn.rawValue); } /** * @notice Cancels a pending withdrawal request. */ function cancelWithdrawal() external nonReentrant() { PositionData storage positionData = _getPositionData(msg.sender); require(positionData.withdrawalRequestPassTimestamp != 0); emit RequestWithdrawalCanceled(msg.sender, positionData.withdrawalRequestAmount.rawValue); // Reset withdrawal request by setting withdrawal amount and withdrawal timestamp to 0. _resetWithdrawalRequest(positionData); } /** * @notice Creates tokens by creating a new position or by augmenting an existing position. Pulls `collateralAmount` into the sponsor's position and mints `numTokens` of `tokenCurrency`. * @dev Reverts if minting these tokens would put the position's collateralization ratio below the * global collateralization ratio. This contract must be approved to spend at least `collateralAmount` of * `collateralCurrency`. * @dev This contract must have the Minter role for the `tokenCurrency`. * @param collateralAmount is the number of collateral tokens to collateralize the position with * @param numTokens is the number of tokens to mint from the position. */ function create(FixedPoint.Unsigned memory collateralAmount, FixedPoint.Unsigned memory numTokens) public onlyPreExpiration() fees() nonReentrant() { PositionData storage positionData = positions[msg.sender]; // Either the new create ratio or the resultant position CR must be above the current GCR. require( (_checkCollateralization( _getFeeAdjustedCollateral(positionData.rawCollateral).add(collateralAmount), positionData.tokensOutstanding.add(numTokens) ) || _checkCollateralization(collateralAmount, numTokens)), "Insufficient collateral" ); require(positionData.withdrawalRequestPassTimestamp == 0, "Pending withdrawal"); if (positionData.tokensOutstanding.isEqual(0)) { require(numTokens.isGreaterThanOrEqual(minSponsorTokens), "Below minimum sponsor position"); emit NewSponsor(msg.sender); } // Increase the position and global collateral balance by collateral amount. _incrementCollateralBalances(positionData, collateralAmount); // Add the number of tokens created to the position's outstanding tokens. positionData.tokensOutstanding = positionData.tokensOutstanding.add(numTokens); totalTokensOutstanding = totalTokensOutstanding.add(numTokens); emit PositionCreated(msg.sender, collateralAmount.rawValue, numTokens.rawValue); // Transfer tokens into the contract from caller and mint corresponding synthetic tokens to the caller's address. collateralCurrency.safeTransferFrom(msg.sender, address(this), collateralAmount.rawValue); require(tokenCurrency.mint(msg.sender, numTokens.rawValue)); } /** * @notice Burns `numTokens` of `tokenCurrency` to decrease sponsors position size, without sending back `collateralCurrency`. * This is done by a sponsor to increase position CR. Resulting size is bounded by minSponsorTokens. * @dev Can only be called by token sponsor. This contract must be approved to spend `numTokens` of `tokenCurrency`. * @dev This contract must have the Burner role for the `tokenCurrency`. * @param numTokens is the number of tokens to be burnt from the sponsor's debt position. */ function repay(FixedPoint.Unsigned memory numTokens) public onlyPreExpiration() noPendingWithdrawal(msg.sender) fees() nonReentrant() { PositionData storage positionData = _getPositionData(msg.sender); require(numTokens.isLessThanOrEqual(positionData.tokensOutstanding)); // Decrease the sponsors position tokens size. Ensure it is above the min sponsor size. FixedPoint.Unsigned memory newTokenCount = positionData.tokensOutstanding.sub(numTokens); require(newTokenCount.isGreaterThanOrEqual(minSponsorTokens)); positionData.tokensOutstanding = newTokenCount; // Update the totalTokensOutstanding after redemption. totalTokensOutstanding = totalTokensOutstanding.sub(numTokens); emit Repay(msg.sender, numTokens.rawValue, newTokenCount.rawValue); // Transfer the tokens back from the sponsor and burn them. tokenCurrency.safeTransferFrom(msg.sender, address(this), numTokens.rawValue); tokenCurrency.burn(numTokens.rawValue); } /** * @notice Burns `numTokens` of `tokenCurrency` and sends back the proportional amount of `collateralCurrency`. * @dev Can only be called by a token sponsor. Might not redeem the full proportional amount of collateral * in order to account for precision loss. This contract must be approved to spend at least `numTokens` of * `tokenCurrency`. * @dev This contract must have the Burner role for the `tokenCurrency`. * @param numTokens is the number of tokens to be burnt for a commensurate amount of collateral. * @return amountWithdrawn The actual amount of collateral withdrawn. */ function redeem(FixedPoint.Unsigned memory numTokens) public noPendingWithdrawal(msg.sender) fees() nonReentrant() returns (FixedPoint.Unsigned memory amountWithdrawn) { PositionData storage positionData = _getPositionData(msg.sender); require(!numTokens.isGreaterThan(positionData.tokensOutstanding)); FixedPoint.Unsigned memory fractionRedeemed = numTokens.div(positionData.tokensOutstanding); FixedPoint.Unsigned memory collateralRedeemed = fractionRedeemed.mul(_getFeeAdjustedCollateral(positionData.rawCollateral)); // If redemption returns all tokens the sponsor has then we can delete their position. Else, downsize. if (positionData.tokensOutstanding.isEqual(numTokens)) { amountWithdrawn = _deleteSponsorPosition(msg.sender); } else { // Decrement the sponsor's collateral and global collateral amounts. amountWithdrawn = _decrementCollateralBalances(positionData, collateralRedeemed); // Decrease the sponsors position tokens size. Ensure it is above the min sponsor size. FixedPoint.Unsigned memory newTokenCount = positionData.tokensOutstanding.sub(numTokens); require(newTokenCount.isGreaterThanOrEqual(minSponsorTokens), "Below minimum sponsor position"); positionData.tokensOutstanding = newTokenCount; // Update the totalTokensOutstanding after redemption. totalTokensOutstanding = totalTokensOutstanding.sub(numTokens); } emit Redeem(msg.sender, amountWithdrawn.rawValue, numTokens.rawValue); // Transfer collateral from contract to caller and burn callers synthetic tokens. collateralCurrency.safeTransfer(msg.sender, amountWithdrawn.rawValue); tokenCurrency.safeTransferFrom(msg.sender, address(this), numTokens.rawValue); tokenCurrency.burn(numTokens.rawValue); } /** * @notice After a contract has passed expiry all token holders can redeem their tokens for underlying at the * prevailing price defined by the DVM from the `expire` function. * @dev This burns all tokens from the caller of `tokenCurrency` and sends back the proportional amount of * `collateralCurrency`. Might not redeem the full proportional amount of collateral in order to account for * precision loss. This contract must be approved to spend `tokenCurrency` at least up to the caller's full balance. * @dev This contract must have the Burner role for the `tokenCurrency`. * @return amountWithdrawn The actual amount of collateral withdrawn. */ function settleExpired() external onlyPostExpiration() fees() nonReentrant() returns (FixedPoint.Unsigned memory amountWithdrawn) { // If the contract state is open and onlyPostExpiration passed then `expire()` has not yet been called. require(contractState != ContractState.Open, "Unexpired position"); // Get the current settlement price and store it. If it is not resolved will revert. if (contractState != ContractState.ExpiredPriceReceived) { expiryPrice = _getOraclePriceExpiration(expirationTimestamp); contractState = ContractState.ExpiredPriceReceived; } // Get caller's tokens balance and calculate amount of underlying entitled to them. FixedPoint.Unsigned memory tokensToRedeem = FixedPoint.Unsigned(tokenCurrency.balanceOf(msg.sender)); FixedPoint.Unsigned memory totalRedeemableCollateral = tokensToRedeem.mul(expiryPrice); // If the caller is a sponsor with outstanding collateral they are also entitled to their excess collateral after their debt. PositionData storage positionData = positions[msg.sender]; if (_getFeeAdjustedCollateral(positionData.rawCollateral).isGreaterThan(0)) { // Calculate the underlying entitled to a token sponsor. This is collateral - debt in underlying. FixedPoint.Unsigned memory tokenDebtValueInCollateral = positionData.tokensOutstanding.mul(expiryPrice); FixedPoint.Unsigned memory positionCollateral = _getFeeAdjustedCollateral(positionData.rawCollateral); // If the debt is greater than the remaining collateral, they cannot redeem anything. FixedPoint.Unsigned memory positionRedeemableCollateral = tokenDebtValueInCollateral.isLessThan(positionCollateral) ? positionCollateral.sub(tokenDebtValueInCollateral) : FixedPoint.Unsigned(0); // Add the number of redeemable tokens for the sponsor to their total redeemable collateral. totalRedeemableCollateral = totalRedeemableCollateral.add(positionRedeemableCollateral); // Reset the position state as all the value has been removed after settlement. delete positions[msg.sender]; emit EndedSponsorPosition(msg.sender); } // Take the min of the remaining collateral and the collateral "owed". If the contract is undercapitalized, // the caller will get as much collateral as the contract can pay out. FixedPoint.Unsigned memory payout = FixedPoint.min(_getFeeAdjustedCollateral(rawTotalPositionCollateral), totalRedeemableCollateral); // Decrement total contract collateral and outstanding debt. amountWithdrawn = _removeCollateral(rawTotalPositionCollateral, payout); totalTokensOutstanding = totalTokensOutstanding.sub(tokensToRedeem); emit SettleExpiredPosition(msg.sender, amountWithdrawn.rawValue, tokensToRedeem.rawValue); // Transfer tokens & collateral and burn the redeemed tokens. collateralCurrency.safeTransfer(msg.sender, amountWithdrawn.rawValue); tokenCurrency.safeTransferFrom(msg.sender, address(this), tokensToRedeem.rawValue); tokenCurrency.burn(tokensToRedeem.rawValue); } /**************************************** * GLOBAL STATE FUNCTIONS * ****************************************/ /** * @notice Locks contract state in expired and requests oracle price. * @dev this function can only be called once the contract is expired and can't be re-called. */ function expire() external onlyPostExpiration() onlyOpenState() fees() nonReentrant() { contractState = ContractState.ExpiredPriceRequested; // Final fees do not need to be paid when sending a request to the optimistic oracle. _requestOraclePriceExpiration(expirationTimestamp); emit ContractExpired(msg.sender); } /** * @notice Premature contract settlement under emergency circumstances. * @dev Only the governor can call this function as they are permissioned within the `FinancialContractAdmin`. * Upon emergency shutdown, the contract settlement time is set to the shutdown time. This enables withdrawal * to occur via the standard `settleExpired` function. Contract state is set to `ExpiredPriceRequested` * which prevents re-entry into this function or the `expire` function. No fees are paid when calling * `emergencyShutdown` as the governor who would call the function would also receive the fees. */ function emergencyShutdown() external override onlyPreExpiration() onlyOpenState() nonReentrant() { require(msg.sender == _getFinancialContractsAdminAddress()); contractState = ContractState.ExpiredPriceRequested; // Expiratory time now becomes the current time (emergency shutdown time). // Price requested at this time stamp. `settleExpired` can now withdraw at this timestamp. uint256 oldExpirationTimestamp = expirationTimestamp; expirationTimestamp = getCurrentTime(); _requestOraclePriceExpiration(expirationTimestamp); emit EmergencyShutdown(msg.sender, oldExpirationTimestamp, expirationTimestamp); } /** * @notice Theoretically supposed to pay fees and move money between margin accounts to make sure they * reflect the NAV of the contract. However, this functionality doesn't apply to this contract. * @dev This is supposed to be implemented by any contract that inherits `AdministrateeInterface` and callable * only by the Governor contract. This method is therefore minimally implemented in this contract and does nothing. */ function remargin() external override onlyPreExpiration() nonReentrant() { return; } /** * @notice Accessor method for a sponsor's collateral. * @dev This is necessary because the struct returned by the positions() method shows * rawCollateral, which isn't a user-readable value. * @dev This method accounts for pending regular fees that have not yet been withdrawn from this contract, for * example if the `lastPaymentTime != currentTime`. * @param sponsor address whose collateral amount is retrieved. * @return collateralAmount amount of collateral within a sponsors position. */ function getCollateral(address sponsor) external view nonReentrantView() returns (FixedPoint.Unsigned memory) { // Note: do a direct access to avoid the validity check. return _getPendingRegularFeeAdjustedCollateral(_getFeeAdjustedCollateral(positions[sponsor].rawCollateral)); } /** * @notice Accessor method for the total collateral stored within the PricelessPositionManager. * @return totalCollateral amount of all collateral within the Expiring Multi Party Contract. * @dev This method accounts for pending regular fees that have not yet been withdrawn from this contract, for * example if the `lastPaymentTime != currentTime`. */ function totalPositionCollateral() external view nonReentrantView() returns (FixedPoint.Unsigned memory) { return _getPendingRegularFeeAdjustedCollateral(_getFeeAdjustedCollateral(rawTotalPositionCollateral)); } /** * @notice Accessor method to compute a transformed price using the finanicalProductLibrary specified at contract * deployment. If no library was provided then no modification to the price is done. * @param price input price to be transformed. * @param requestTime timestamp the oraclePrice was requested at. * @return transformedPrice price with the transformation function applied to it. * @dev This method should never revert. */ function transformPrice(FixedPoint.Unsigned memory price, uint256 requestTime) public view nonReentrantView() returns (FixedPoint.Unsigned memory) { return _transformPrice(price, requestTime); } /** * @notice Accessor method to compute a transformed price identifier using the finanicalProductLibrary specified * at contract deployment. If no library was provided then no modification to the identifier is done. * @param requestTime timestamp the identifier is to be used at. * @return transformedPrice price with the transformation function applied to it. * @dev This method should never revert. */ function transformPriceIdentifier(uint256 requestTime) public view nonReentrantView() returns (bytes32) { return _transformPriceIdentifier(requestTime); } /**************************************** * INTERNAL FUNCTIONS * ****************************************/ // Reduces a sponsor's position and global counters by the specified parameters. Handles deleting the entire // position if the entire position is being removed. Does not make any external transfers. function _reduceSponsorPosition( address sponsor, FixedPoint.Unsigned memory tokensToRemove, FixedPoint.Unsigned memory collateralToRemove, FixedPoint.Unsigned memory withdrawalAmountToRemove ) internal { PositionData storage positionData = _getPositionData(sponsor); // If the entire position is being removed, delete it instead. if ( tokensToRemove.isEqual(positionData.tokensOutstanding) && _getFeeAdjustedCollateral(positionData.rawCollateral).isEqual(collateralToRemove) ) { _deleteSponsorPosition(sponsor); return; } // Decrement the sponsor's collateral and global collateral amounts. _decrementCollateralBalances(positionData, collateralToRemove); // Ensure that the sponsor will meet the min position size after the reduction. FixedPoint.Unsigned memory newTokenCount = positionData.tokensOutstanding.sub(tokensToRemove); require(newTokenCount.isGreaterThanOrEqual(minSponsorTokens), "Below minimum sponsor position"); positionData.tokensOutstanding = newTokenCount; // Decrement the position's withdrawal amount. positionData.withdrawalRequestAmount = positionData.withdrawalRequestAmount.sub(withdrawalAmountToRemove); // Decrement the total outstanding tokens in the overall contract. totalTokensOutstanding = totalTokensOutstanding.sub(tokensToRemove); } // Deletes a sponsor's position and updates global counters. Does not make any external transfers. function _deleteSponsorPosition(address sponsor) internal returns (FixedPoint.Unsigned memory) { PositionData storage positionToLiquidate = _getPositionData(sponsor); FixedPoint.Unsigned memory startingGlobalCollateral = _getFeeAdjustedCollateral(rawTotalPositionCollateral); // Remove the collateral and outstanding from the overall total position. FixedPoint.Unsigned memory remainingRawCollateral = positionToLiquidate.rawCollateral; rawTotalPositionCollateral = rawTotalPositionCollateral.sub(remainingRawCollateral); totalTokensOutstanding = totalTokensOutstanding.sub(positionToLiquidate.tokensOutstanding); // Reset the sponsors position to have zero outstanding and collateral. delete positions[sponsor]; emit EndedSponsorPosition(sponsor); // Return fee-adjusted amount of collateral deleted from position. return startingGlobalCollateral.sub(_getFeeAdjustedCollateral(rawTotalPositionCollateral)); } function _pfc() internal view virtual override returns (FixedPoint.Unsigned memory) { return _getFeeAdjustedCollateral(rawTotalPositionCollateral); } function _getPositionData(address sponsor) internal view onlyCollateralizedPosition(sponsor) returns (PositionData storage) { return positions[sponsor]; } function _getIdentifierWhitelist() internal view returns (IdentifierWhitelistInterface) { return IdentifierWhitelistInterface(finder.getImplementationAddress(OracleInterfaces.IdentifierWhitelist)); } function _getOracle() internal view returns (OracleInterface) { return OracleInterface(finder.getImplementationAddress(OracleInterfaces.Oracle)); } function _getOptimisticOracle() internal view returns (OptimisticOracleInterface) { return OptimisticOracleInterface(finder.getImplementationAddress(OracleInterfaces.OptimisticOracle)); } function _getFinancialContractsAdminAddress() internal view returns (address) { return finder.getImplementationAddress(OracleInterfaces.FinancialContractsAdmin); } // Requests a price for transformed `priceIdentifier` at `requestedTime` from the Oracle. function _requestOraclePriceExpiration(uint256 requestedTime) internal { OptimisticOracleInterface optimisticOracle = _getOptimisticOracle(); // Increase token allowance to enable the optimistic oracle reward transfer. FixedPoint.Unsigned memory reward = _computeFinalFees(); collateralCurrency.safeIncreaseAllowance(address(optimisticOracle), reward.rawValue); optimisticOracle.requestPrice( _transformPriceIdentifier(requestedTime), requestedTime, _getAncillaryData(), collateralCurrency, reward.rawValue // Reward is equal to the final fee ); // Apply haircut to all sponsors by decrementing the cumlativeFeeMultiplier by the amount lost from the final fee. _adjustCumulativeFeeMultiplier(reward, _pfc()); } // Fetches a resolved Oracle price from the Oracle. Reverts if the Oracle hasn't resolved for this request. function _getOraclePriceExpiration(uint256 requestedTime) internal returns (FixedPoint.Unsigned memory) { // Create an instance of the oracle and get the price. If the price is not resolved revert. OptimisticOracleInterface optimisticOracle = _getOptimisticOracle(); require( optimisticOracle.hasPrice( address(this), _transformPriceIdentifier(requestedTime), requestedTime, _getAncillaryData() ) ); int256 optimisticOraclePrice = optimisticOracle.settleAndGetPrice( _transformPriceIdentifier(requestedTime), requestedTime, _getAncillaryData() ); // For now we don't want to deal with negative prices in positions. if (optimisticOraclePrice < 0) { optimisticOraclePrice = 0; } return _transformPrice(FixedPoint.Unsigned(uint256(optimisticOraclePrice)), requestedTime); } // Requests a price for transformed `priceIdentifier` at `requestedTime` from the Oracle. function _requestOraclePriceLiquidation(uint256 requestedTime) internal { OracleInterface oracle = _getOracle(); oracle.requestPrice(_transformPriceIdentifier(requestedTime), requestedTime); } // Fetches a resolved Oracle price from the Oracle. Reverts if the Oracle hasn't resolved for this request. function _getOraclePriceLiquidation(uint256 requestedTime) internal view returns (FixedPoint.Unsigned memory) { // Create an instance of the oracle and get the price. If the price is not resolved revert. OracleInterface oracle = _getOracle(); require(oracle.hasPrice(_transformPriceIdentifier(requestedTime), requestedTime), "Unresolved oracle price"); int256 oraclePrice = oracle.getPrice(_transformPriceIdentifier(requestedTime), requestedTime); // For now we don't want to deal with negative prices in positions. if (oraclePrice < 0) { oraclePrice = 0; } return _transformPrice(FixedPoint.Unsigned(uint256(oraclePrice)), requestedTime); } // Reset withdrawal request by setting the withdrawal request and withdrawal timestamp to 0. function _resetWithdrawalRequest(PositionData storage positionData) internal { positionData.withdrawalRequestAmount = FixedPoint.fromUnscaledUint(0); positionData.withdrawalRequestPassTimestamp = 0; } // Ensure individual and global consistency when increasing collateral balances. Returns the change to the position. function _incrementCollateralBalances( PositionData storage positionData, FixedPoint.Unsigned memory collateralAmount ) internal returns (FixedPoint.Unsigned memory) { _addCollateral(positionData.rawCollateral, collateralAmount); return _addCollateral(rawTotalPositionCollateral, collateralAmount); } // Ensure individual and global consistency when decrementing collateral balances. Returns the change to the // position. We elect to return the amount that the global collateral is decreased by, rather than the individual // position's collateral, because we need to maintain the invariant that the global collateral is always // <= the collateral owned by the contract to avoid reverts on withdrawals. The amount returned = amount withdrawn. function _decrementCollateralBalances( PositionData storage positionData, FixedPoint.Unsigned memory collateralAmount ) internal returns (FixedPoint.Unsigned memory) { _removeCollateral(positionData.rawCollateral, collateralAmount); return _removeCollateral(rawTotalPositionCollateral, collateralAmount); } // Ensure individual and global consistency when decrementing collateral balances. Returns the change to the position. // This function is similar to the _decrementCollateralBalances function except this function checks position GCR // between the decrements. This ensures that collateral removal will not leave the position undercollateralized. function _decrementCollateralBalancesCheckGCR( PositionData storage positionData, FixedPoint.Unsigned memory collateralAmount ) internal returns (FixedPoint.Unsigned memory) { _removeCollateral(positionData.rawCollateral, collateralAmount); require(_checkPositionCollateralization(positionData), "CR below GCR"); return _removeCollateral(rawTotalPositionCollateral, collateralAmount); } // These internal functions are supposed to act identically to modifiers, but re-used modifiers // unnecessarily increase contract bytecode size. // source: https://blog.polymath.network/solidity-tips-and-tricks-to-save-gas-and-reduce-bytecode-size-c44580b218e6 function _onlyOpenState() internal view { require(contractState == ContractState.Open, "Contract state is not OPEN"); } function _onlyPreExpiration() internal view { require(getCurrentTime() < expirationTimestamp, "Only callable pre-expiry"); } function _onlyPostExpiration() internal view { require(getCurrentTime() >= expirationTimestamp, "Only callable post-expiry"); } function _onlyCollateralizedPosition(address sponsor) internal view { require( _getFeeAdjustedCollateral(positions[sponsor].rawCollateral).isGreaterThan(0), "Position has no collateral" ); } // Note: This checks whether an already existing position has a pending withdrawal. This cannot be used on the // `create` method because it is possible that `create` is called on a new position (i.e. one without any collateral // or tokens outstanding) which would fail the `onlyCollateralizedPosition` modifier on `_getPositionData`. function _positionHasNoPendingWithdrawal(address sponsor) internal view { require(_getPositionData(sponsor).withdrawalRequestPassTimestamp == 0, "Pending withdrawal"); } /**************************************** * PRIVATE FUNCTIONS * ****************************************/ function _checkPositionCollateralization(PositionData storage positionData) private view returns (bool) { return _checkCollateralization( _getFeeAdjustedCollateral(positionData.rawCollateral), positionData.tokensOutstanding ); } // Checks whether the provided `collateral` and `numTokens` have a collateralization ratio above the global // collateralization ratio. function _checkCollateralization(FixedPoint.Unsigned memory collateral, FixedPoint.Unsigned memory numTokens) private view returns (bool) { FixedPoint.Unsigned memory global = _getCollateralizationRatio(_getFeeAdjustedCollateral(rawTotalPositionCollateral), totalTokensOutstanding); FixedPoint.Unsigned memory thisChange = _getCollateralizationRatio(collateral, numTokens); return !global.isGreaterThan(thisChange); } function _getCollateralizationRatio(FixedPoint.Unsigned memory collateral, FixedPoint.Unsigned memory numTokens) private pure returns (FixedPoint.Unsigned memory ratio) { if (!numTokens.isGreaterThan(0)) { return FixedPoint.fromUnscaledUint(0); } else { return collateral.div(numTokens); } } // IERC20Standard.decimals() will revert if the collateral contract has not implemented the decimals() method, // which is possible since the method is only an OPTIONAL method in the ERC20 standard: // https://eips.ethereum.org/EIPS/eip-20#methods. function _getSyntheticDecimals(address _collateralAddress) public view returns (uint8 decimals) { try IERC20Standard(_collateralAddress).decimals() returns (uint8 _decimals) { return _decimals; } catch { return 18; } } function _transformPrice(FixedPoint.Unsigned memory price, uint256 requestTime) internal view returns (FixedPoint.Unsigned memory) { if (!address(financialProductLibrary).isContract()) return price; try financialProductLibrary.transformPrice(price, requestTime) returns ( FixedPoint.Unsigned memory transformedPrice ) { return transformedPrice; } catch { return price; } } function _transformPriceIdentifier(uint256 requestTime) internal view returns (bytes32) { if (!address(financialProductLibrary).isContract()) return priceIdentifier; try financialProductLibrary.transformPriceIdentifier(priceIdentifier, requestTime) returns ( bytes32 transformedIdentifier ) { return transformedIdentifier; } catch { return priceIdentifier; } } function _getAncillaryData() internal view returns (bytes memory) { // Note: when ancillary data is passed to the optimistic oracle, it should be tagged with the token address // whose funding rate it's trying to get. return abi.encodePacked(address(tokenCurrency)); } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.8.0; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; /** * @title ERC20 interface that includes the decimals read only method. */ interface IERC20Standard is IERC20 { /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should be displayed to a user as `5,05` * (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between Ether and Wei. This is the value * {ERC20} uses, unless {_setupDecimals} is called. * * NOTE: This information is only used for _display_ purposes: it in no way affects any of the arithmetic * of the contract, including {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() external view returns (uint8); } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.8.0; pragma abicoder v2; import "../../../common/implementation/FixedPoint.sol"; interface ExpiringContractInterface { function expirationTimestamp() external view returns (uint256); } /** * @title Financial product library contract * @notice Provides price and collateral requirement transformation interfaces that can be overridden by custom * Financial product library implementations. */ abstract contract FinancialProductLibrary { using FixedPoint for FixedPoint.Unsigned; /** * @notice Transforms a given oracle price using the financial product libraries transformation logic. * @param oraclePrice input price returned by the DVM to be transformed. * @param requestTime timestamp the oraclePrice was requested at. * @return transformedOraclePrice input oraclePrice with the transformation function applied. */ function transformPrice(FixedPoint.Unsigned memory oraclePrice, uint256 requestTime) public view virtual returns (FixedPoint.Unsigned memory) { return oraclePrice; } /** * @notice Transforms a given collateral requirement using the financial product libraries transformation logic. * @param oraclePrice input price returned by DVM used to transform the collateral requirement. * @param collateralRequirement input collateral requirement to be transformed. * @return transformedCollateralRequirement input collateral requirement with the transformation function applied. */ function transformCollateralRequirement( FixedPoint.Unsigned memory oraclePrice, FixedPoint.Unsigned memory collateralRequirement ) public view virtual returns (FixedPoint.Unsigned memory) { return collateralRequirement; } /** * @notice Transforms a given price identifier using the financial product libraries transformation logic. * @param priceIdentifier input price identifier defined for the financial contract. * @param requestTime timestamp the identifier is to be used at. EG the time that a price request would be sent using this identifier. * @return transformedPriceIdentifier input price identifier with the transformation function applied. */ function transformPriceIdentifier(bytes32 priceIdentifier, uint256 requestTime) public view virtual returns (bytes32) { return priceIdentifier; } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.8.0; pragma abicoder v2; import "../common/financial-product-libraries/FinancialProductLibrary.sol"; // Implements a simple FinancialProductLibrary to test price and collateral requirement transoformations. contract FinancialProductLibraryTest is FinancialProductLibrary { using FixedPoint for FixedPoint.Unsigned; FixedPoint.Unsigned public priceTransformationScalar; FixedPoint.Unsigned public collateralRequirementTransformationScalar; bytes32 public transformedPriceIdentifier; bool public shouldRevert; constructor( FixedPoint.Unsigned memory _priceTransformationScalar, FixedPoint.Unsigned memory _collateralRequirementTransformationScalar, bytes32 _transformedPriceIdentifier ) { priceTransformationScalar = _priceTransformationScalar; collateralRequirementTransformationScalar = _collateralRequirementTransformationScalar; transformedPriceIdentifier = _transformedPriceIdentifier; } // Set the mocked methods to revert to test failed library computation. function setShouldRevert(bool _shouldRevert) public { shouldRevert = _shouldRevert; } // Create a simple price transformation function that scales the input price by the scalar for testing. function transformPrice(FixedPoint.Unsigned memory oraclePrice, uint256 requestTime) public view override returns (FixedPoint.Unsigned memory) { require(!shouldRevert, "set to always reverts"); return oraclePrice.mul(priceTransformationScalar); } // Create a simple collateral requirement transformation that doubles the input collateralRequirement. function transformCollateralRequirement( FixedPoint.Unsigned memory price, FixedPoint.Unsigned memory collateralRequirement ) public view override returns (FixedPoint.Unsigned memory) { require(!shouldRevert, "set to always reverts"); return collateralRequirement.mul(collateralRequirementTransformationScalar); } // Create a simple transformPriceIdentifier function that returns the transformed price identifier. function transformPriceIdentifier(bytes32 priceIdentifier, uint256 requestTime) public view override returns (bytes32) { require(!shouldRevert, "set to always reverts"); return transformedPriceIdentifier; } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.8.0; pragma abicoder v2; import "../../common/implementation/Testable.sol"; import "../../common/implementation/FixedPoint.sol"; import "../common/financial-product-libraries/FinancialProductLibrary.sol"; contract ExpiringMultiPartyMock is Testable { using FixedPoint for FixedPoint.Unsigned; FinancialProductLibrary public financialProductLibrary; uint256 public expirationTimestamp; FixedPoint.Unsigned public collateralRequirement; bytes32 public priceIdentifier; constructor( address _financialProductLibraryAddress, uint256 _expirationTimestamp, FixedPoint.Unsigned memory _collateralRequirement, bytes32 _priceIdentifier, address _timerAddress ) Testable(_timerAddress) { expirationTimestamp = _expirationTimestamp; collateralRequirement = _collateralRequirement; financialProductLibrary = FinancialProductLibrary(_financialProductLibraryAddress); priceIdentifier = _priceIdentifier; } function transformPrice(FixedPoint.Unsigned memory price, uint256 requestTime) public view returns (FixedPoint.Unsigned memory) { if (address(financialProductLibrary) == address(0)) return price; try financialProductLibrary.transformPrice(price, requestTime) returns ( FixedPoint.Unsigned memory transformedPrice ) { return transformedPrice; } catch { return price; } } function transformCollateralRequirement(FixedPoint.Unsigned memory price) public view returns (FixedPoint.Unsigned memory) { if (address(financialProductLibrary) == address(0)) return collateralRequirement; try financialProductLibrary.transformCollateralRequirement(price, collateralRequirement) returns ( FixedPoint.Unsigned memory transformedCollateralRequirement ) { return transformedCollateralRequirement; } catch { return collateralRequirement; } } function transformPriceIdentifier(uint256 requestTime) public view returns (bytes32) { if (address(financialProductLibrary) == address(0)) return priceIdentifier; try financialProductLibrary.transformPriceIdentifier(priceIdentifier, requestTime) returns ( bytes32 transformedIdentifier ) { return transformedIdentifier; } catch { return priceIdentifier; } } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.8.0; pragma abicoder v2; import "../../common/implementation/FixedPoint.sol"; import "../../common/implementation/Testable.sol"; import "../interfaces/OracleAncillaryInterface.sol"; import "../interfaces/VotingAncillaryInterface.sol"; // A mock oracle used for testing. Exports the voting & oracle interfaces and events that contain ancillary data. abstract contract VotingAncillaryInterfaceTesting is OracleAncillaryInterface, VotingAncillaryInterface, Testable { using FixedPoint for FixedPoint.Unsigned; // Events, data structures and functions not exported in the base interfaces, used for testing. event VoteCommitted( address indexed voter, uint256 indexed roundId, bytes32 indexed identifier, uint256 time, bytes ancillaryData ); event EncryptedVote( address indexed voter, uint256 indexed roundId, bytes32 indexed identifier, uint256 time, bytes ancillaryData, bytes encryptedVote ); event VoteRevealed( address indexed voter, uint256 indexed roundId, bytes32 indexed identifier, uint256 time, int256 price, bytes ancillaryData, uint256 numTokens ); event RewardsRetrieved( address indexed voter, uint256 indexed roundId, bytes32 indexed identifier, uint256 time, bytes ancillaryData, uint256 numTokens ); event PriceRequestAdded(uint256 indexed roundId, bytes32 indexed identifier, uint256 time); event PriceResolved( uint256 indexed roundId, bytes32 indexed identifier, uint256 time, int256 price, bytes ancillaryData ); struct Round { uint256 snapshotId; // Voting token snapshot ID for this round. 0 if no snapshot has been taken. FixedPoint.Unsigned inflationRate; // Inflation rate set for this round. FixedPoint.Unsigned gatPercentage; // Gat rate set for this round. uint256 rewardsExpirationTime; // Time that rewards for this round can be claimed until. } // Represents the status a price request has. enum RequestStatus { NotRequested, // Was never requested. Active, // Is being voted on in the current round. Resolved, // Was resolved in a previous round. Future // Is scheduled to be voted on in a future round. } // Only used as a return value in view methods -- never stored in the contract. struct RequestState { RequestStatus status; uint256 lastVotingRound; } function rounds(uint256 roundId) public view virtual returns (Round memory); function getPriceRequestStatuses(VotingAncillaryInterface.PendingRequestAncillary[] memory requests) public view virtual returns (RequestState[] memory); function getPendingPriceRequestsArray() external view virtual returns (bytes32[] memory); } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.8.0; pragma abicoder v2; import "../../common/implementation/MultiRole.sol"; import "../../common/implementation/Withdrawable.sol"; import "../interfaces/VotingAncillaryInterface.sol"; import "../interfaces/FinderInterface.sol"; import "./Constants.sol"; /** * @title Proxy to allow voting from another address. * @dev Allows a UMA token holder to designate another address to vote on their behalf. * Each voter must deploy their own instance of this contract. */ contract DesignatedVoting is Withdrawable { /**************************************** * INTERNAL VARIABLES AND STORAGE * ****************************************/ enum Roles { Owner, // Can set the Voter role. Is also permanently permissioned as the minter role. Voter // Can vote through this contract. } // Reference to the UMA Finder contract, allowing Voting upgrades to be performed // without requiring any calls to this contract. FinderInterface private finder; /** * @notice Construct the DesignatedVoting contract. * @param finderAddress keeps track of all contracts within the system based on their interfaceName. * @param ownerAddress address of the owner of the DesignatedVoting contract. * @param voterAddress address to which the owner has delegated their voting power. */ constructor( address finderAddress, address ownerAddress, address voterAddress ) { _createExclusiveRole(uint256(Roles.Owner), uint256(Roles.Owner), ownerAddress); _createExclusiveRole(uint256(Roles.Voter), uint256(Roles.Owner), voterAddress); _setWithdrawRole(uint256(Roles.Owner)); finder = FinderInterface(finderAddress); } /**************************************** * VOTING AND REWARD FUNCTIONALITY * ****************************************/ /** * @notice Forwards a commit to Voting. * @param identifier uniquely identifies the feed for this vote. EG BTC/USD price pair. * @param time specifies the unix timestamp of the price being voted on. * @param hash the keccak256 hash of the price you want to vote for and a random integer salt value. */ function commitVote( bytes32 identifier, uint256 time, bytes memory ancillaryData, bytes32 hash ) external onlyRoleHolder(uint256(Roles.Voter)) { _getVotingAddress().commitVote(identifier, time, ancillaryData, hash); } /** * @notice Forwards a batch commit to Voting. * @param commits struct to encapsulate an `identifier`, `time`, `hash` and optional `encryptedVote`. */ function batchCommit(VotingAncillaryInterface.CommitmentAncillary[] calldata commits) external onlyRoleHolder(uint256(Roles.Voter)) { _getVotingAddress().batchCommit(commits); } /** * @notice Forwards a reveal to Voting. * @param identifier voted on in the commit phase. EG BTC/USD price pair. * @param time specifies the unix timestamp of the price being voted on. * @param price used along with the `salt` to produce the `hash` during the commit phase. * @param salt used along with the `price` to produce the `hash` during the commit phase. */ function revealVote( bytes32 identifier, uint256 time, int256 price, bytes memory ancillaryData, int256 salt ) external onlyRoleHolder(uint256(Roles.Voter)) { _getVotingAddress().revealVote(identifier, time, price, ancillaryData, salt); } /** * @notice Forwards a batch reveal to Voting. * @param reveals is an array of the Reveal struct which contains an identifier, time, price and salt. */ function batchReveal(VotingAncillaryInterface.RevealAncillary[] calldata reveals) external onlyRoleHolder(uint256(Roles.Voter)) { _getVotingAddress().batchReveal(reveals); } /** * @notice Forwards a reward retrieval to Voting. * @dev Rewards are added to the tokens already held by this contract. * @param roundId defines the round from which voting rewards will be retrieved from. * @param toRetrieve an array of PendingRequests which rewards are retrieved from. * @return amount of rewards that the user should receive. */ function retrieveRewards(uint256 roundId, VotingAncillaryInterface.PendingRequestAncillary[] memory toRetrieve) public onlyRoleHolder(uint256(Roles.Voter)) returns (FixedPoint.Unsigned memory) { return _getVotingAddress().retrieveRewards(address(this), roundId, toRetrieve); } function _getVotingAddress() private view returns (VotingAncillaryInterface) { return VotingAncillaryInterface(finder.getImplementationAddress(OracleInterfaces.Oracle)); } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.8.0; pragma abicoder v2; import "../../common/implementation/Withdrawable.sol"; import "./DesignatedVoting.sol"; /** * @title Factory to deploy new instances of DesignatedVoting and look up previously deployed instances. * @dev Allows off-chain infrastructure to look up a hot wallet's deployed DesignatedVoting contract. */ contract DesignatedVotingFactory is Withdrawable { /**************************************** * INTERNAL VARIABLES AND STORAGE * ****************************************/ enum Roles { Withdrawer // Can withdraw any ETH or ERC20 sent accidentally to this contract. } address private finder; mapping(address => DesignatedVoting) public designatedVotingContracts; /** * @notice Construct the DesignatedVotingFactory contract. * @param finderAddress keeps track of all contracts within the system based on their interfaceName. */ constructor(address finderAddress) { finder = finderAddress; _createWithdrawRole(uint256(Roles.Withdrawer), uint256(Roles.Withdrawer), msg.sender); } /** * @notice Deploys a new `DesignatedVoting` contract. * @param ownerAddress defines who will own the deployed instance of the designatedVoting contract. * @return designatedVoting a new DesignatedVoting contract. */ function newDesignatedVoting(address ownerAddress) external returns (DesignatedVoting) { DesignatedVoting designatedVoting = new DesignatedVoting(finder, ownerAddress, msg.sender); designatedVotingContracts[msg.sender] = designatedVoting; return designatedVoting; } /** * @notice Associates a `DesignatedVoting` instance with `msg.sender`. * @param designatedVotingAddress address to designate voting to. * @dev This is generally only used if the owner of a `DesignatedVoting` contract changes their `voter` * address and wants that reflected here. */ function setDesignatedVoting(address designatedVotingAddress) external { designatedVotingContracts[msg.sender] = DesignatedVoting(designatedVotingAddress); } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.8.0; import "../implementation/Withdrawable.sol"; // WithdrawableTest is derived from the abstract contract Withdrawable for testing purposes. contract WithdrawableTest is Withdrawable { enum Roles { Governance, Withdraw } // solhint-disable-next-line no-empty-blocks constructor() { _createExclusiveRole(uint256(Roles.Governance), uint256(Roles.Governance), msg.sender); _createWithdrawRole(uint256(Roles.Withdraw), uint256(Roles.Governance), msg.sender); } function pay() external payable { require(msg.value > 0); } function setInternalWithdrawRole(uint256 setRoleId) public { _setWithdrawRole(setRoleId); } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.8.0; import "../../interfaces/VotingInterface.sol"; import "../VoteTiming.sol"; // Wraps the library VoteTiming for testing purposes. contract VoteTimingTest { using VoteTiming for VoteTiming.Data; VoteTiming.Data public voteTiming; constructor(uint256 phaseLength) { wrapInit(phaseLength); } function wrapComputeCurrentRoundId(uint256 currentTime) external view returns (uint256) { return voteTiming.computeCurrentRoundId(currentTime); } function wrapComputeCurrentPhase(uint256 currentTime) external view returns (VotingAncillaryInterface.Phase) { return voteTiming.computeCurrentPhase(currentTime); } function wrapInit(uint256 phaseLength) public { voteTiming.init(phaseLength); } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.8.0; pragma abicoder v2; import "@openzeppelin/contracts/utils/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; import "@openzeppelin/contracts/utils/cryptography/MerkleProof.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; /** * Inspired by: * - https://github.com/pie-dao/vested-token-migration-app * - https://github.com/Uniswap/merkle-distributor * - https://github.com/balancer-labs/erc20-redeemable * * @title MerkleDistributor contract. * @notice Allows an owner to distribute any reward ERC20 to claimants according to Merkle roots. The owner can specify * multiple Merkle roots distributions with customized reward currencies. * @dev The Merkle trees are not validated in any way, so the system assumes the contract owner behaves honestly. */ contract MerkleDistributor is Ownable { using SafeMath for uint256; using SafeERC20 for IERC20; // A Window maps a Merkle root to a reward token address. struct Window { // Merkle root describing the distribution. bytes32 merkleRoot; // Currency in which reward is processed. IERC20 rewardToken; // IPFS hash of the merkle tree. Can be used to independently fetch recipient proofs and tree. Note that the canonical // data type for storing an IPFS hash is a multihash which is the concatenation of <varint hash function code> // <varint digest size in bytes><hash function output>. We opted to store this in a string type to make it easier // for users to query the ipfs data without needing to reconstruct the multihash. to view the IPFS data simply // go to https://cloudflare-ipfs.com/ipfs/<IPFS-HASH>. string ipfsHash; } // Represents an account's claim for `amount` within the Merkle root located at the `windowIndex`. struct Claim { uint256 windowIndex; uint256 amount; uint256 accountIndex; // Used only for bitmap. Assumed to be unique for each claim. address account; bytes32[] merkleProof; } // Windows are mapped to arbitrary indices. mapping(uint256 => Window) public merkleWindows; // Index of next created Merkle root. uint256 public nextCreatedIndex; // Track which accounts have claimed for each window index. // Note: uses a packed array of bools for gas optimization on tracking certain claims. Copied from Uniswap's contract. mapping(uint256 => mapping(uint256 => uint256)) private claimedBitMap; /**************************************** * EVENTS ****************************************/ event Claimed( address indexed caller, uint256 windowIndex, address indexed account, uint256 accountIndex, uint256 amount, address indexed rewardToken ); event CreatedWindow( uint256 indexed windowIndex, uint256 rewardsDeposited, address indexed rewardToken, address owner ); event WithdrawRewards(address indexed owner, uint256 amount, address indexed currency); event DeleteWindow(uint256 indexed windowIndex, address owner); /**************************** * ADMIN FUNCTIONS ****************************/ /** * @notice Set merkle root for the next available window index and seed allocations. * @notice Callable only by owner of this contract. Caller must have approved this contract to transfer * `rewardsToDeposit` amount of `rewardToken` or this call will fail. Importantly, we assume that the * owner of this contract correctly chooses an amount `rewardsToDeposit` that is sufficient to cover all * claims within the `merkleRoot`. Otherwise, a race condition can be created. This situation can occur * because we do not segregate reward balances by window, for code simplicity purposes. * (If `rewardsToDeposit` is purposefully insufficient to payout all claims, then the admin must * subsequently transfer in rewards or the following situation can occur). * Example race situation: * - Window 1 Tree: Owner sets `rewardsToDeposit=100` and insert proofs that give claimant A 50 tokens and * claimant B 51 tokens. The owner has made an error by not setting the `rewardsToDeposit` correctly to 101. * - Window 2 Tree: Owner sets `rewardsToDeposit=1` and insert proofs that give claimant A 1 token. The owner * correctly set `rewardsToDeposit` this time. * - At this point contract owns 100 + 1 = 101 tokens. Now, imagine the following sequence: * (1) Claimant A claims 50 tokens for Window 1, contract now has 101 - 50 = 51 tokens. * (2) Claimant B claims 51 tokens for Window 1, contract now has 51 - 51 = 0 tokens. * (3) Claimant A tries to claim 1 token for Window 2 but fails because contract has 0 tokens. * - In summary, the contract owner created a race for step(2) and step(3) in which the first claim would * succeed and the second claim would fail, even though both claimants would expect their claims to succeed. * @param rewardsToDeposit amount of rewards to deposit to seed this allocation. * @param rewardToken ERC20 reward token. * @param merkleRoot merkle root describing allocation. * @param ipfsHash hash of IPFS object, conveniently stored for clients */ function setWindow( uint256 rewardsToDeposit, address rewardToken, bytes32 merkleRoot, string memory ipfsHash ) external onlyOwner { uint256 indexToSet = nextCreatedIndex; nextCreatedIndex = indexToSet.add(1); _setWindow(indexToSet, rewardsToDeposit, rewardToken, merkleRoot, ipfsHash); } /** * @notice Delete merkle root at window index. * @dev Callable only by owner. Likely to be followed by a withdrawRewards call to clear contract state. * @param windowIndex merkle root index to delete. */ function deleteWindow(uint256 windowIndex) external onlyOwner { delete merkleWindows[windowIndex]; emit DeleteWindow(windowIndex, msg.sender); } /** * @notice Emergency method that transfers rewards out of the contract if the contract was configured improperly. * @dev Callable only by owner. * @param rewardCurrency rewards to withdraw from contract. * @param amount amount of rewards to withdraw. */ function withdrawRewards(address rewardCurrency, uint256 amount) external onlyOwner { IERC20(rewardCurrency).safeTransfer(msg.sender, amount); emit WithdrawRewards(msg.sender, amount, rewardCurrency); } /**************************** * NON-ADMIN FUNCTIONS ****************************/ /** * @notice Batch claims to reduce gas versus individual submitting all claims. Method will fail * if any individual claims within the batch would fail. * @dev Optimistically tries to batch together consecutive claims for the same account and same * reward token to reduce gas. Therefore, the most gas-cost-optimal way to use this method * is to pass in an array of claims sorted by account and reward currency. * @param claims array of claims to claim. */ function claimMulti(Claim[] memory claims) external { uint256 batchedAmount = 0; uint256 claimCount = claims.length; for (uint256 i = 0; i < claimCount; i++) { Claim memory _claim = claims[i]; _verifyAndMarkClaimed(_claim); batchedAmount = batchedAmount.add(_claim.amount); // If the next claim is NOT the same account or the same token (or this claim is the last one), // then disburse the `batchedAmount` to the current claim's account for the current claim's reward token. uint256 nextI = i + 1; address currentRewardToken = address(merkleWindows[_claim.windowIndex].rewardToken); if ( nextI == claimCount || // This claim is last claim. claims[nextI].account != _claim.account || // Next claim account is different than current one. address(merkleWindows[claims[nextI].windowIndex].rewardToken) != currentRewardToken // Next claim reward token is different than current one. ) { IERC20(currentRewardToken).safeTransfer(_claim.account, batchedAmount); batchedAmount = 0; } } } /** * @notice Claim amount of reward tokens for account, as described by Claim input object. * @dev If the `_claim`'s `amount`, `accountIndex`, and `account` do not exactly match the * values stored in the merkle root for the `_claim`'s `windowIndex` this method * will revert. * @param _claim claim object describing amount, accountIndex, account, window index, and merkle proof. */ function claim(Claim memory _claim) public { _verifyAndMarkClaimed(_claim); merkleWindows[_claim.windowIndex].rewardToken.safeTransfer(_claim.account, _claim.amount); } /** * @notice Returns True if the claim for `accountIndex` has already been completed for the Merkle root at * `windowIndex`. * @dev This method will only work as intended if all `accountIndex`'s are unique for a given `windowIndex`. * The onus is on the Owner of this contract to submit only valid Merkle roots. * @param windowIndex merkle root to check. * @param accountIndex account index to check within window index. * @return True if claim has been executed already, False otherwise. */ function isClaimed(uint256 windowIndex, uint256 accountIndex) public view returns (bool) { uint256 claimedWordIndex = accountIndex / 256; uint256 claimedBitIndex = accountIndex % 256; uint256 claimedWord = claimedBitMap[windowIndex][claimedWordIndex]; uint256 mask = (1 << claimedBitIndex); return claimedWord & mask == mask; } /** * @notice Returns True if leaf described by {account, amount, accountIndex} is stored in Merkle root at given * window index. * @param _claim claim object describing amount, accountIndex, account, window index, and merkle proof. * @return valid True if leaf exists. */ function verifyClaim(Claim memory _claim) public view returns (bool valid) { bytes32 leaf = keccak256(abi.encodePacked(_claim.account, _claim.amount, _claim.accountIndex)); return MerkleProof.verify(_claim.merkleProof, merkleWindows[_claim.windowIndex].merkleRoot, leaf); } /**************************** * PRIVATE FUNCTIONS ****************************/ // Mark claim as completed for `accountIndex` for Merkle root at `windowIndex`. function _setClaimed(uint256 windowIndex, uint256 accountIndex) private { uint256 claimedWordIndex = accountIndex / 256; uint256 claimedBitIndex = accountIndex % 256; claimedBitMap[windowIndex][claimedWordIndex] = claimedBitMap[windowIndex][claimedWordIndex] | (1 << claimedBitIndex); } // Store new Merkle root at `windowindex`. Pull `rewardsDeposited` from caller to seed distribution for this root. function _setWindow( uint256 windowIndex, uint256 rewardsDeposited, address rewardToken, bytes32 merkleRoot, string memory ipfsHash ) private { Window storage window = merkleWindows[windowIndex]; window.merkleRoot = merkleRoot; window.rewardToken = IERC20(rewardToken); window.ipfsHash = ipfsHash; emit CreatedWindow(windowIndex, rewardsDeposited, rewardToken, msg.sender); window.rewardToken.safeTransferFrom(msg.sender, address(this), rewardsDeposited); } // Verify claim is valid and mark it as completed in this contract. function _verifyAndMarkClaimed(Claim memory _claim) private { // Check claimed proof against merkle window at given index. require(verifyClaim(_claim), "Incorrect merkle proof"); // Check the account has not yet claimed for this window. require(!isClaimed(_claim.windowIndex, _claim.accountIndex), "Account has already claimed for this window"); // Proof is correct and claim has not occurred yet, mark claimed complete. _setClaimed(_claim.windowIndex, _claim.accountIndex); emit Claimed( msg.sender, _claim.windowIndex, _claim.account, _claim.accountIndex, _claim.amount, address(merkleWindows[_claim.windowIndex].rewardToken) ); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev These functions deal with verification of Merkle Trees proofs. * * The proofs can be generated using the JavaScript library * https://github.com/miguelmota/merkletreejs[merkletreejs]. * Note: the hashing algorithm should be keccak256 and pair sorting should be enabled. * * See `test/utils/cryptography/MerkleProof.test.js` for some examples. */ library MerkleProof { /** * @dev Returns true if a `leaf` can be proved to be a part of a Merkle tree * defined by `root`. For this, a `proof` must be provided, containing * sibling hashes on the branch from the leaf to the root of the tree. Each * pair of leaves and each pair of pre-images are assumed to be sorted. */ function verify(bytes32[] memory proof, bytes32 root, bytes32 leaf) internal pure returns (bool) { bytes32 computedHash = leaf; for (uint256 i = 0; i < proof.length; i++) { bytes32 proofElement = proof[i]; if (computedHash <= proofElement) { // Hash(current computed hash + current element of the proof) computedHash = keccak256(abi.encodePacked(computedHash, proofElement)); } else { // Hash(current element of the proof + current computed hash) computedHash = keccak256(abi.encodePacked(proofElement, computedHash)); } } // Check if the computed hash (root) is equal to the provided root return computedHash == root; } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.8.0; import "../interfaces/IdentifierWhitelistInterface.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; /** * @title Stores a whitelist of supported identifiers that the oracle can provide prices for. */ contract IdentifierWhitelist is IdentifierWhitelistInterface, Ownable { /**************************************** * INTERNAL VARIABLES AND STORAGE * ****************************************/ mapping(bytes32 => bool) private supportedIdentifiers; /**************************************** * EVENTS * ****************************************/ event SupportedIdentifierAdded(bytes32 indexed identifier); event SupportedIdentifierRemoved(bytes32 indexed identifier); /**************************************** * ADMIN STATE MODIFYING FUNCTIONS * ****************************************/ /** * @notice Adds the provided identifier as a supported identifier. * @dev Price requests using this identifier will succeed after this call. * @param identifier unique UTF-8 representation for the feed being added. Eg: BTC/USD. */ function addSupportedIdentifier(bytes32 identifier) external override onlyOwner { if (!supportedIdentifiers[identifier]) { supportedIdentifiers[identifier] = true; emit SupportedIdentifierAdded(identifier); } } /** * @notice Removes the identifier from the whitelist. * @dev Price requests using this identifier will no longer succeed after this call. * @param identifier unique UTF-8 representation for the feed being removed. Eg: BTC/USD. */ function removeSupportedIdentifier(bytes32 identifier) external override onlyOwner { if (supportedIdentifiers[identifier]) { supportedIdentifiers[identifier] = false; emit SupportedIdentifierRemoved(identifier); } } /**************************************** * WHITELIST GETTERS FUNCTIONS * ****************************************/ /** * @notice Checks whether an identifier is on the whitelist. * @param identifier unique UTF-8 representation for the feed being queried. Eg: BTC/USD. * @return bool if the identifier is supported (or not). */ function isIdentifierSupported(bytes32 identifier) external view override returns (bool) { return supportedIdentifiers[identifier]; } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.8.0; import "../interfaces/AdministrateeInterface.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; /** * @title Admin for financial contracts in the UMA system. * @dev Allows appropriately permissioned admin roles to interact with financial contracts. */ contract FinancialContractsAdmin is Ownable { /** * @notice Calls emergency shutdown on the provided financial contract. * @param financialContract address of the FinancialContract to be shut down. */ function callEmergencyShutdown(address financialContract) external onlyOwner { AdministrateeInterface administratee = AdministrateeInterface(financialContract); administratee.emergencyShutdown(); } /** * @notice Calls remargin on the provided financial contract. * @param financialContract address of the FinancialContract to be remargined. */ function callRemargin(address financialContract) external onlyOwner { AdministrateeInterface administratee = AdministrateeInterface(financialContract); administratee.remargin(); } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.8.0; pragma abicoder v2; import "../../interfaces/AdministrateeInterface.sol"; // A mock implementation of AdministrateeInterface, taking the place of a financial contract. contract MockAdministratee is AdministrateeInterface { uint256 public timesRemargined; uint256 public timesEmergencyShutdown; function remargin() external override { timesRemargined++; } function emergencyShutdown() external override { timesEmergencyShutdown++; } function pfc() external view override returns (FixedPoint.Unsigned memory) { return FixedPoint.fromUnscaledUint(0); } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.8.0; pragma abicoder v2; import "@openzeppelin/contracts/utils/math/SafeMath.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; import "./ConfigStoreInterface.sol"; import "../../common/implementation/Testable.sol"; import "../../common/implementation/Lockable.sol"; import "../../common/implementation/FixedPoint.sol"; /** * @notice ConfigStore stores configuration settings for a perpetual contract and provides an interface for it * to query settings such as reward rates, proposal bond sizes, etc. The configuration settings can be upgraded * by a privileged account and the upgraded changes are timelocked. */ contract ConfigStore is ConfigStoreInterface, Testable, Lockable, Ownable { using SafeMath for uint256; using FixedPoint for FixedPoint.Unsigned; /**************************************** * STORE DATA STRUCTURES * ****************************************/ // Make currentConfig private to force user to call getCurrentConfig, which returns the pendingConfig // if its liveness has expired. ConfigStoreInterface.ConfigSettings private currentConfig; // Beginning on `pendingPassedTimestamp`, the `pendingConfig` can be published as the current config. ConfigStoreInterface.ConfigSettings public pendingConfig; uint256 public pendingPassedTimestamp; /**************************************** * EVENTS * ****************************************/ event ProposedNewConfigSettings( address indexed proposer, uint256 rewardRatePerSecond, uint256 proposerBondPercentage, uint256 timelockLiveness, int256 maxFundingRate, int256 minFundingRate, uint256 proposalTimePastLimit, uint256 proposalPassedTimestamp ); event ChangedConfigSettings( uint256 rewardRatePerSecond, uint256 proposerBondPercentage, uint256 timelockLiveness, int256 maxFundingRate, int256 minFundingRate, uint256 proposalTimePastLimit ); /**************************************** * MODIFIERS * ****************************************/ // Update config settings if possible. modifier updateConfig() { _updateConfig(); _; } /** * @notice Construct the Config Store. An initial configuration is provided and set on construction. * @param _initialConfig Configuration settings to initialize `currentConfig` with. * @param _timerAddress Address of testable Timer contract. */ constructor(ConfigSettings memory _initialConfig, address _timerAddress) Testable(_timerAddress) { _validateConfig(_initialConfig); currentConfig = _initialConfig; } /** * @notice Returns current config or pending config if pending liveness has expired. * @return ConfigSettings config settings that calling financial contract should view as "live". */ function updateAndGetCurrentConfig() external override updateConfig() nonReentrant() returns (ConfigStoreInterface.ConfigSettings memory) { return currentConfig; } /** * @notice Propose new configuration settings. New settings go into effect after a liveness period passes. * @param newConfig Configuration settings to publish after `currentConfig.timelockLiveness` passes from block.timestamp. * @dev Callable only by owner. Calling this while there is already a pending proposal will overwrite the pending proposal. */ function proposeNewConfig(ConfigSettings memory newConfig) external onlyOwner() nonReentrant() updateConfig() { _validateConfig(newConfig); // Warning: This overwrites a pending proposal! pendingConfig = newConfig; // Use current config's liveness period to timelock this proposal. pendingPassedTimestamp = getCurrentTime().add(currentConfig.timelockLiveness); emit ProposedNewConfigSettings( msg.sender, newConfig.rewardRatePerSecond.rawValue, newConfig.proposerBondPercentage.rawValue, newConfig.timelockLiveness, newConfig.maxFundingRate.rawValue, newConfig.minFundingRate.rawValue, newConfig.proposalTimePastLimit, pendingPassedTimestamp ); } /** * @notice Publish any pending configuration settings if there is a pending proposal that has passed liveness. */ function publishPendingConfig() external nonReentrant() updateConfig() {} /**************************************** * INTERNAL FUNCTIONS * ****************************************/ // Check if pending proposal can overwrite the current config. function _updateConfig() internal { // If liveness has passed, publish proposed configuration settings. if (_pendingProposalPassed()) { currentConfig = pendingConfig; _deletePendingConfig(); emit ChangedConfigSettings( currentConfig.rewardRatePerSecond.rawValue, currentConfig.proposerBondPercentage.rawValue, currentConfig.timelockLiveness, currentConfig.maxFundingRate.rawValue, currentConfig.minFundingRate.rawValue, currentConfig.proposalTimePastLimit ); } } function _deletePendingConfig() internal { delete pendingConfig; pendingPassedTimestamp = 0; } function _pendingProposalPassed() internal view returns (bool) { return (pendingPassedTimestamp != 0 && pendingPassedTimestamp <= getCurrentTime()); } // Use this method to constrain values with which you can set ConfigSettings. function _validateConfig(ConfigStoreInterface.ConfigSettings memory config) internal pure { // We don't set limits on proposal timestamps because there are already natural limits: // - Future: price requests to the OptimisticOracle must be in the past---we can't add further constraints. // - Past: proposal times must always be after the last update time, and a reasonable past limit would be 30 // mins, meaning that no proposal timestamp can be more than 30 minutes behind the current time. // Make sure timelockLiveness is not too long, otherwise contract might not be able to fix itself // before a vulnerability drains its collateral. require(config.timelockLiveness <= 7 days && config.timelockLiveness >= 1 days, "Invalid timelockLiveness"); // The reward rate should be modified as needed to incentivize honest proposers appropriately. // Additionally, the rate should be less than 100% a year => 100% / 360 days / 24 hours / 60 mins / 60 secs // = 0.0000033 FixedPoint.Unsigned memory maxRewardRatePerSecond = FixedPoint.fromUnscaledUint(33).div(1e7); require(config.rewardRatePerSecond.isLessThan(maxRewardRatePerSecond), "Invalid rewardRatePerSecond"); // We don't set a limit on the proposer bond because it is a defense against dishonest proposers. If a proposer // were to successfully propose a very high or low funding rate, then their PfC would be very high. The proposer // could theoretically keep their "evil" funding rate alive indefinitely by continuously disputing honest // proposers, so we would want to be able to set the proposal bond (equal to the dispute bond) higher than their // PfC for each proposal liveness window. The downside of not limiting this is that the config store owner // can set it arbitrarily high and preclude a new funding rate from ever coming in. We suggest setting the // proposal bond based on the configuration's funding rate range like in this discussion: // https://github.com/UMAprotocol/protocol/issues/2039#issuecomment-719734383 // We also don't set a limit on the funding rate max/min because we might need to allow very high magnitude // funding rates in extraordinarily volatile market situations. Note, that even though we do not bound // the max/min, we still recommend that the deployer of this contract set the funding rate max/min values // to bound the PfC of a dishonest proposer. A reasonable range might be the equivalent of [+200%/year, -200%/year]. } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.8.0; pragma abicoder v2; import "../../common/implementation/FixedPoint.sol"; interface ConfigStoreInterface { // All of the configuration settings available for querying by a perpetual. struct ConfigSettings { // Liveness period (in seconds) for an update to currentConfig to become official. uint256 timelockLiveness; // Reward rate paid to successful proposers. Percentage of 1 E.g., .1 is 10%. FixedPoint.Unsigned rewardRatePerSecond; // Bond % (of given contract's PfC) that must be staked by proposers. Percentage of 1, e.g. 0.0005 is 0.05%. FixedPoint.Unsigned proposerBondPercentage; // Maximum funding rate % per second that can be proposed. FixedPoint.Signed maxFundingRate; // Minimum funding rate % per second that can be proposed. FixedPoint.Signed minFundingRate; // Funding rate proposal timestamp cannot be more than this amount of seconds in the past from the latest // update time. uint256 proposalTimePastLimit; } function updateAndGetCurrentConfig() external returns (ConfigSettings memory); } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.8.0; pragma abicoder v2; import "../../common/interfaces/ExpandedIERC20.sol"; import "../../common/interfaces/IERC20Standard.sol"; import "../../oracle/implementation/ContractCreator.sol"; import "../../common/implementation/Testable.sol"; import "../../common/implementation/AddressWhitelist.sol"; import "../../common/implementation/Lockable.sol"; import "../common/TokenFactory.sol"; import "../common/SyntheticToken.sol"; import "./PerpetualLib.sol"; import "./ConfigStore.sol"; /** * @title Perpetual Contract creator. * @notice Factory contract to create and register new instances of perpetual contracts. * Responsible for constraining the parameters used to construct a new perpetual. This creator contains a number of constraints * that are applied to newly created contract. These constraints can evolve over time and are * initially constrained to conservative values in this first iteration. Technically there is nothing in the * Perpetual contract requiring these constraints. However, because `createPerpetual()` is intended * to be the only way to create valid financial contracts that are registered with the DVM (via _registerContract), we can enforce deployment configurations here. */ contract PerpetualCreator is ContractCreator, Testable, Lockable { using FixedPoint for FixedPoint.Unsigned; /**************************************** * PERP CREATOR DATA STRUCTURES * ****************************************/ // Immutable params for perpetual contract. struct Params { address collateralAddress; bytes32 priceFeedIdentifier; bytes32 fundingRateIdentifier; string syntheticName; string syntheticSymbol; FixedPoint.Unsigned collateralRequirement; FixedPoint.Unsigned disputeBondPercentage; FixedPoint.Unsigned sponsorDisputeRewardPercentage; FixedPoint.Unsigned disputerDisputeRewardPercentage; FixedPoint.Unsigned minSponsorTokens; FixedPoint.Unsigned tokenScaling; uint256 withdrawalLiveness; uint256 liquidationLiveness; } // Address of TokenFactory used to create a new synthetic token. address public tokenFactoryAddress; event CreatedPerpetual(address indexed perpetualAddress, address indexed deployerAddress); event CreatedConfigStore(address indexed configStoreAddress, address indexed ownerAddress); /** * @notice Constructs the Perpetual contract. * @param _finderAddress UMA protocol Finder used to discover other protocol contracts. * @param _tokenFactoryAddress ERC20 token factory used to deploy synthetic token instances. * @param _timerAddress Contract that stores the current time in a testing environment. */ constructor( address _finderAddress, address _tokenFactoryAddress, address _timerAddress ) ContractCreator(_finderAddress) Testable(_timerAddress) nonReentrant() { tokenFactoryAddress = _tokenFactoryAddress; } /** * @notice Creates an instance of perpetual and registers it within the registry. * @param params is a `ConstructorParams` object from Perpetual. * @return address of the deployed contract. */ function createPerpetual(Params memory params, ConfigStore.ConfigSettings memory configSettings) public nonReentrant() returns (address) { require(bytes(params.syntheticName).length != 0, "Missing synthetic name"); require(bytes(params.syntheticSymbol).length != 0, "Missing synthetic symbol"); // Create new config settings store for this contract and reset ownership to the deployer. ConfigStore configStore = new ConfigStore(configSettings, timerAddress); configStore.transferOwnership(msg.sender); emit CreatedConfigStore(address(configStore), configStore.owner()); // Create a new synthetic token using the params. TokenFactory tf = TokenFactory(tokenFactoryAddress); // If the collateral token does not have a `decimals()` method, // then a default precision of 18 will be applied to the newly created synthetic token. uint8 syntheticDecimals = _getSyntheticDecimals(params.collateralAddress); ExpandedIERC20 tokenCurrency = tf.createToken(params.syntheticName, params.syntheticSymbol, syntheticDecimals); address derivative = PerpetualLib.deploy(_convertParams(params, tokenCurrency, address(configStore))); // Give permissions to new derivative contract and then hand over ownership. tokenCurrency.addMinter(derivative); tokenCurrency.addBurner(derivative); tokenCurrency.resetOwner(derivative); _registerContract(new address[](0), derivative); emit CreatedPerpetual(derivative, msg.sender); return derivative; } /**************************************** * PRIVATE FUNCTIONS * ****************************************/ // Converts createPerpetual params to Perpetual constructor params. function _convertParams( Params memory params, ExpandedIERC20 newTokenCurrency, address configStore ) private view returns (Perpetual.ConstructorParams memory constructorParams) { // Known from creator deployment. constructorParams.finderAddress = finderAddress; constructorParams.timerAddress = timerAddress; // Enforce configuration constraints. require(params.withdrawalLiveness != 0, "Withdrawal liveness cannot be 0"); require(params.liquidationLiveness != 0, "Liquidation liveness cannot be 0"); _requireWhitelistedCollateral(params.collateralAddress); // We don't want perpetual deployers to be able to intentionally or unintentionally set // liveness periods that could induce arithmetic overflow, but we also don't want // to be opinionated about what livenesses are "correct", so we will somewhat // arbitrarily set the liveness upper bound to 100 years (5200 weeks). In practice, liveness // periods even greater than a few days would make the perpetual unusable for most users. require(params.withdrawalLiveness < 5200 weeks, "Withdrawal liveness too large"); require(params.liquidationLiveness < 5200 weeks, "Liquidation liveness too large"); // To avoid precision loss or overflows, prevent the token scaling from being too large or too small. FixedPoint.Unsigned memory minScaling = FixedPoint.Unsigned(1e8); // 1e-10 FixedPoint.Unsigned memory maxScaling = FixedPoint.Unsigned(1e28); // 1e10 require( params.tokenScaling.isGreaterThan(minScaling) && params.tokenScaling.isLessThan(maxScaling), "Invalid tokenScaling" ); // Input from function call. constructorParams.configStoreAddress = configStore; constructorParams.tokenAddress = address(newTokenCurrency); constructorParams.collateralAddress = params.collateralAddress; constructorParams.priceFeedIdentifier = params.priceFeedIdentifier; constructorParams.fundingRateIdentifier = params.fundingRateIdentifier; constructorParams.collateralRequirement = params.collateralRequirement; constructorParams.disputeBondPercentage = params.disputeBondPercentage; constructorParams.sponsorDisputeRewardPercentage = params.sponsorDisputeRewardPercentage; constructorParams.disputerDisputeRewardPercentage = params.disputerDisputeRewardPercentage; constructorParams.minSponsorTokens = params.minSponsorTokens; constructorParams.withdrawalLiveness = params.withdrawalLiveness; constructorParams.liquidationLiveness = params.liquidationLiveness; constructorParams.tokenScaling = params.tokenScaling; } // IERC20Standard.decimals() will revert if the collateral contract has not implemented the decimals() method, // which is possible since the method is only an OPTIONAL method in the ERC20 standard: // https://eips.ethereum.org/EIPS/eip-20#methods. function _getSyntheticDecimals(address _collateralAddress) public view returns (uint8 decimals) { try IERC20Standard(_collateralAddress).decimals() returns (uint8 _decimals) { return _decimals; } catch { return 18; } } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.8.0; import "../interfaces/FinderInterface.sol"; import "../../common/implementation/AddressWhitelist.sol"; import "./Registry.sol"; import "./Constants.sol"; /** * @title Base contract for all financial contract creators */ abstract contract ContractCreator { address internal finderAddress; constructor(address _finderAddress) { finderAddress = _finderAddress; } function _requireWhitelistedCollateral(address collateralAddress) internal view { FinderInterface finder = FinderInterface(finderAddress); AddressWhitelist collateralWhitelist = AddressWhitelist(finder.getImplementationAddress(OracleInterfaces.CollateralWhitelist)); require(collateralWhitelist.isOnWhitelist(collateralAddress), "Collateral not whitelisted"); } function _registerContract(address[] memory parties, address contractToRegister) internal { FinderInterface finder = FinderInterface(finderAddress); Registry registry = Registry(finder.getImplementationAddress(OracleInterfaces.Registry)); registry.registerContract(parties, contractToRegister); } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.8.0; import "./SyntheticToken.sol"; import "../../common/interfaces/ExpandedIERC20.sol"; import "../../common/implementation/Lockable.sol"; /** * @title Factory for creating new mintable and burnable tokens. */ contract TokenFactory is Lockable { /** * @notice Create a new token and return it to the caller. * @dev The caller will become the only minter and burner and the new owner capable of assigning the roles. * @param tokenName used to describe the new token. * @param tokenSymbol short ticker abbreviation of the name. Ideally < 5 chars. * @param tokenDecimals used to define the precision used in the token's numerical representation. * @return newToken an instance of the newly created token interface. */ function createToken( string calldata tokenName, string calldata tokenSymbol, uint8 tokenDecimals ) external nonReentrant() returns (ExpandedIERC20 newToken) { SyntheticToken mintableToken = new SyntheticToken(tokenName, tokenSymbol, tokenDecimals); mintableToken.addMinter(msg.sender); mintableToken.addBurner(msg.sender); mintableToken.resetOwner(msg.sender); newToken = ExpandedIERC20(address(mintableToken)); } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.8.0; import "../../common/implementation/ExpandedERC20.sol"; import "../../common/implementation/Lockable.sol"; /** * @title Burnable and mintable ERC20. * @dev The contract deployer will initially be the only minter, burner and owner capable of adding new roles. */ contract SyntheticToken is ExpandedERC20, Lockable { /** * @notice Constructs the SyntheticToken. * @param tokenName The name which describes the new token. * @param tokenSymbol The ticker abbreviation of the name. Ideally < 5 chars. * @param tokenDecimals The number of decimals to define token precision. */ constructor( string memory tokenName, string memory tokenSymbol, uint8 tokenDecimals ) ExpandedERC20(tokenName, tokenSymbol, tokenDecimals) nonReentrant() {} /** * @notice Add Minter role to account. * @dev The caller must have the Owner role. * @param account The address to which the Minter role is added. */ function addMinter(address account) external override nonReentrant() { addMember(uint256(Roles.Minter), account); } /** * @notice Remove Minter role from account. * @dev The caller must have the Owner role. * @param account The address from which the Minter role is removed. */ function removeMinter(address account) external nonReentrant() { removeMember(uint256(Roles.Minter), account); } /** * @notice Add Burner role to account. * @dev The caller must have the Owner role. * @param account The address to which the Burner role is added. */ function addBurner(address account) external override nonReentrant() { addMember(uint256(Roles.Burner), account); } /** * @notice Removes Burner role from account. * @dev The caller must have the Owner role. * @param account The address from which the Burner role is removed. */ function removeBurner(address account) external nonReentrant() { removeMember(uint256(Roles.Burner), account); } /** * @notice Reset Owner role to account. * @dev The caller must have the Owner role. * @param account The new holder of the Owner role. */ function resetOwner(address account) external override nonReentrant() { resetMember(uint256(Roles.Owner), account); } /** * @notice Checks if a given account holds the Minter role. * @param account The address which is checked for the Minter role. * @return bool True if the provided account is a Minter. */ function isMinter(address account) public view nonReentrantView() returns (bool) { return holdsRole(uint256(Roles.Minter), account); } /** * @notice Checks if a given account holds the Burner role. * @param account The address which is checked for the Burner role. * @return bool True if the provided account is a Burner. */ function isBurner(address account) public view nonReentrantView() returns (bool) { return holdsRole(uint256(Roles.Burner), account); } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.8.0; pragma abicoder v2; import "./Perpetual.sol"; /** * @title Provides convenient Perpetual Multi Party contract utilities. * @dev Using this library to deploy Perpetuals allows calling contracts to avoid importing the full bytecode. */ library PerpetualLib { /** * @notice Returns address of new Perpetual deployed with given `params` configuration. * @dev Caller will need to register new Perpetual with the Registry to begin requesting prices. Caller is also * responsible for enforcing constraints on `params`. * @param params is a `ConstructorParams` object from Perpetual. * @return address of the deployed Perpetual contract */ function deploy(Perpetual.ConstructorParams memory params) public returns (address) { Perpetual derivative = new Perpetual(params); return address(derivative); } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.8.0; pragma abicoder v2; import "./PerpetualLiquidatable.sol"; /** * @title Perpetual Multiparty Contract. * @notice Convenient wrapper for Liquidatable. */ contract Perpetual is PerpetualLiquidatable { /** * @notice Constructs the Perpetual contract. * @param params struct to define input parameters for construction of Liquidatable. Some params * are fed directly into the PositionManager's constructor within the inheritance tree. */ constructor(ConstructorParams memory params) PerpetualLiquidatable(params) // Note: since there is no logic here, there is no need to add a re-entrancy guard. { } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.8.0; pragma abicoder v2; import "@openzeppelin/contracts/utils/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; import "./PerpetualPositionManager.sol"; import "../../common/implementation/FixedPoint.sol"; /** * @title PerpetualLiquidatable * @notice Adds logic to a position-managing contract that enables callers to liquidate an undercollateralized position. * @dev The liquidation has a liveness period before expiring successfully, during which someone can "dispute" the * liquidation, which sends a price request to the relevant Oracle to settle the final collateralization ratio based on * a DVM price. The contract enforces dispute rewards in order to incentivize disputers to correctly dispute false * liquidations and compensate position sponsors who had their position incorrectly liquidated. Importantly, a * prospective disputer must deposit a dispute bond that they can lose in the case of an unsuccessful dispute. * NOTE: this contract does _not_ work with ERC777 collateral currencies or any others that call into the receiver on * transfer(). Using an ERC777 token would allow a user to maliciously grief other participants (while also losing * money themselves). */ contract PerpetualLiquidatable is PerpetualPositionManager { using FixedPoint for FixedPoint.Unsigned; using SafeMath for uint256; using SafeERC20 for IERC20; using SafeERC20 for ExpandedIERC20; /**************************************** * LIQUIDATION DATA STRUCTURES * ****************************************/ // Because of the check in withdrawable(), the order of these enum values should not change. enum Status { Uninitialized, NotDisputed, Disputed, DisputeSucceeded, DisputeFailed } struct LiquidationData { // Following variables set upon creation of liquidation: address sponsor; // Address of the liquidated position's sponsor address liquidator; // Address who created this liquidation Status state; // Liquidated (and expired or not), Pending a Dispute, or Dispute has resolved uint256 liquidationTime; // Time when liquidation is initiated, needed to get price from Oracle // Following variables determined by the position that is being liquidated: FixedPoint.Unsigned tokensOutstanding; // Synthetic tokens required to be burned by liquidator to initiate dispute FixedPoint.Unsigned lockedCollateral; // Collateral locked by contract and released upon expiry or post-dispute // Amount of collateral being liquidated, which could be different from // lockedCollateral if there were pending withdrawals at the time of liquidation FixedPoint.Unsigned liquidatedCollateral; // Unit value (starts at 1) that is used to track the fees per unit of collateral over the course of the liquidation. FixedPoint.Unsigned rawUnitCollateral; // Following variable set upon initiation of a dispute: address disputer; // Person who is disputing a liquidation // Following variable set upon a resolution of a dispute: FixedPoint.Unsigned settlementPrice; // Final price as determined by an Oracle following a dispute FixedPoint.Unsigned finalFee; } // Define the contract's constructor parameters as a struct to enable more variables to be specified. // This is required to enable more params, over and above Solidity's limits. struct ConstructorParams { // Params for PerpetualPositionManager only. uint256 withdrawalLiveness; address configStoreAddress; address collateralAddress; address tokenAddress; address finderAddress; address timerAddress; bytes32 priceFeedIdentifier; bytes32 fundingRateIdentifier; FixedPoint.Unsigned minSponsorTokens; FixedPoint.Unsigned tokenScaling; // Params specifically for PerpetualLiquidatable. uint256 liquidationLiveness; FixedPoint.Unsigned collateralRequirement; FixedPoint.Unsigned disputeBondPercentage; FixedPoint.Unsigned sponsorDisputeRewardPercentage; FixedPoint.Unsigned disputerDisputeRewardPercentage; } // This struct is used in the `withdrawLiquidation` method that disperses liquidation and dispute rewards. // `payToX` stores the total collateral to withdraw from the contract to pay X. This value might differ // from `paidToX` due to precision loss between accounting for the `rawCollateral` versus the // fee-adjusted collateral. These variables are stored within a struct to avoid the stack too deep error. struct RewardsData { FixedPoint.Unsigned payToSponsor; FixedPoint.Unsigned payToLiquidator; FixedPoint.Unsigned payToDisputer; FixedPoint.Unsigned paidToSponsor; FixedPoint.Unsigned paidToLiquidator; FixedPoint.Unsigned paidToDisputer; } // Liquidations are unique by ID per sponsor mapping(address => LiquidationData[]) public liquidations; // Total collateral in liquidation. FixedPoint.Unsigned public rawLiquidationCollateral; // Immutable contract parameters: // Amount of time for pending liquidation before expiry. // !!Note: The lower the liquidation liveness value, the more risk incurred by sponsors. // Extremely low liveness values increase the chance that opportunistic invalid liquidations // expire without dispute, thereby decreasing the usability for sponsors and increasing the risk // for the contract as a whole. An insolvent contract is extremely risky for any sponsor or synthetic // token holder for the contract. uint256 public liquidationLiveness; // Required collateral:TRV ratio for a position to be considered sufficiently collateralized. FixedPoint.Unsigned public collateralRequirement; // Percent of a Liquidation/Position's lockedCollateral to be deposited by a potential disputer // Represented as a multiplier, for example 1.5e18 = "150%" and 0.05e18 = "5%" FixedPoint.Unsigned public disputeBondPercentage; // Percent of oraclePrice paid to sponsor in the Disputed state (i.e. following a successful dispute) // Represented as a multiplier, see above. FixedPoint.Unsigned public sponsorDisputeRewardPercentage; // Percent of oraclePrice paid to disputer in the Disputed state (i.e. following a successful dispute) // Represented as a multiplier, see above. FixedPoint.Unsigned public disputerDisputeRewardPercentage; /**************************************** * EVENTS * ****************************************/ event LiquidationCreated( address indexed sponsor, address indexed liquidator, uint256 indexed liquidationId, uint256 tokensOutstanding, uint256 lockedCollateral, uint256 liquidatedCollateral, uint256 liquidationTime ); event LiquidationDisputed( address indexed sponsor, address indexed liquidator, address indexed disputer, uint256 liquidationId, uint256 disputeBondAmount ); event DisputeSettled( address indexed caller, address indexed sponsor, address indexed liquidator, address disputer, uint256 liquidationId, bool disputeSucceeded ); event LiquidationWithdrawn( address indexed caller, uint256 paidToLiquidator, uint256 paidToDisputer, uint256 paidToSponsor, Status indexed liquidationStatus, uint256 settlementPrice ); /**************************************** * MODIFIERS * ****************************************/ modifier disputable(uint256 liquidationId, address sponsor) { _disputable(liquidationId, sponsor); _; } modifier withdrawable(uint256 liquidationId, address sponsor) { _withdrawable(liquidationId, sponsor); _; } /** * @notice Constructs the liquidatable contract. * @param params struct to define input parameters for construction of Liquidatable. Some params * are fed directly into the PositionManager's constructor within the inheritance tree. */ constructor(ConstructorParams memory params) PerpetualPositionManager( params.withdrawalLiveness, params.collateralAddress, params.tokenAddress, params.finderAddress, params.priceFeedIdentifier, params.fundingRateIdentifier, params.minSponsorTokens, params.configStoreAddress, params.tokenScaling, params.timerAddress ) { require(params.collateralRequirement.isGreaterThan(1)); require(params.sponsorDisputeRewardPercentage.add(params.disputerDisputeRewardPercentage).isLessThan(1)); // Set liquidatable specific variables. liquidationLiveness = params.liquidationLiveness; collateralRequirement = params.collateralRequirement; disputeBondPercentage = params.disputeBondPercentage; sponsorDisputeRewardPercentage = params.sponsorDisputeRewardPercentage; disputerDisputeRewardPercentage = params.disputerDisputeRewardPercentage; } /**************************************** * LIQUIDATION FUNCTIONS * ****************************************/ /** * @notice Liquidates the sponsor's position if the caller has enough * synthetic tokens to retire the position's outstanding tokens. Liquidations above * a minimum size also reset an ongoing "slow withdrawal"'s liveness. * @dev This method generates an ID that will uniquely identify liquidation for the sponsor. This contract must be * approved to spend at least `tokensLiquidated` of `tokenCurrency` and at least `finalFeeBond` of `collateralCurrency`. * @dev This contract must have the Burner role for the `tokenCurrency`. * @param sponsor address of the sponsor to liquidate. * @param minCollateralPerToken abort the liquidation if the position's collateral per token is below this value. * @param maxCollateralPerToken abort the liquidation if the position's collateral per token exceeds this value. * @param maxTokensToLiquidate max number of tokens to liquidate. * @param deadline abort the liquidation if the transaction is mined after this timestamp. * @return liquidationId ID of the newly created liquidation. * @return tokensLiquidated amount of synthetic tokens removed and liquidated from the `sponsor`'s position. * @return finalFeeBond amount of collateral to be posted by liquidator and returned if not disputed successfully. */ function createLiquidation( address sponsor, FixedPoint.Unsigned calldata minCollateralPerToken, FixedPoint.Unsigned calldata maxCollateralPerToken, FixedPoint.Unsigned calldata maxTokensToLiquidate, uint256 deadline ) external notEmergencyShutdown() fees() nonReentrant() returns ( uint256 liquidationId, FixedPoint.Unsigned memory tokensLiquidated, FixedPoint.Unsigned memory finalFeeBond ) { // Check that this transaction was mined pre-deadline. require(getCurrentTime() <= deadline, "Mined after deadline"); // Retrieve Position data for sponsor PositionData storage positionToLiquidate = _getPositionData(sponsor); tokensLiquidated = FixedPoint.min(maxTokensToLiquidate, positionToLiquidate.tokensOutstanding); require(tokensLiquidated.isGreaterThan(0)); // Starting values for the Position being liquidated. If withdrawal request amount is > position's collateral, // then set this to 0, otherwise set it to (startCollateral - withdrawal request amount). FixedPoint.Unsigned memory startCollateral = _getFeeAdjustedCollateral(positionToLiquidate.rawCollateral); FixedPoint.Unsigned memory startCollateralNetOfWithdrawal = FixedPoint.fromUnscaledUint(0); if (positionToLiquidate.withdrawalRequestAmount.isLessThanOrEqual(startCollateral)) { startCollateralNetOfWithdrawal = startCollateral.sub(positionToLiquidate.withdrawalRequestAmount); } // Scoping to get rid of a stack too deep error. { FixedPoint.Unsigned memory startTokens = positionToLiquidate.tokensOutstanding; // The Position's collateralization ratio must be between [minCollateralPerToken, maxCollateralPerToken]. require( maxCollateralPerToken.mul(startTokens).isGreaterThanOrEqual(startCollateralNetOfWithdrawal), "CR is more than max liq. price" ); // minCollateralPerToken >= startCollateralNetOfWithdrawal / startTokens. require( minCollateralPerToken.mul(startTokens).isLessThanOrEqual(startCollateralNetOfWithdrawal), "CR is less than min liq. price" ); } // Compute final fee at time of liquidation. finalFeeBond = _computeFinalFees(); // These will be populated within the scope below. FixedPoint.Unsigned memory lockedCollateral; FixedPoint.Unsigned memory liquidatedCollateral; // Scoping to get rid of a stack too deep error. The amount of tokens to remove from the position // are not funding-rate adjusted because the multiplier only affects their redemption value, not their // notional. { FixedPoint.Unsigned memory ratio = tokensLiquidated.div(positionToLiquidate.tokensOutstanding); // The actual amount of collateral that gets moved to the liquidation. lockedCollateral = startCollateral.mul(ratio); // For purposes of disputes, it's actually this liquidatedCollateral value that's used. This value is net of // withdrawal requests. liquidatedCollateral = startCollateralNetOfWithdrawal.mul(ratio); // Part of the withdrawal request is also removed. Ideally: // liquidatedCollateral + withdrawalAmountToRemove = lockedCollateral. FixedPoint.Unsigned memory withdrawalAmountToRemove = positionToLiquidate.withdrawalRequestAmount.mul(ratio); _reduceSponsorPosition(sponsor, tokensLiquidated, lockedCollateral, withdrawalAmountToRemove); } // Add to the global liquidation collateral count. _addCollateral(rawLiquidationCollateral, lockedCollateral.add(finalFeeBond)); // Construct liquidation object. // Note: All dispute-related values are zeroed out until a dispute occurs. liquidationId is the index of the new // LiquidationData that is pushed into the array, which is equal to the current length of the array pre-push. liquidationId = liquidations[sponsor].length; liquidations[sponsor].push( LiquidationData({ sponsor: sponsor, liquidator: msg.sender, state: Status.NotDisputed, liquidationTime: getCurrentTime(), tokensOutstanding: _getFundingRateAppliedTokenDebt(tokensLiquidated), lockedCollateral: lockedCollateral, liquidatedCollateral: liquidatedCollateral, rawUnitCollateral: _convertToRawCollateral(FixedPoint.fromUnscaledUint(1)), disputer: address(0), settlementPrice: FixedPoint.fromUnscaledUint(0), finalFee: finalFeeBond }) ); // If this liquidation is a subsequent liquidation on the position, and the liquidation size is larger than // some "griefing threshold", then re-set the liveness. This enables a liquidation against a withdraw request to be // "dragged out" if the position is very large and liquidators need time to gather funds. The griefing threshold // is enforced so that liquidations for trivially small # of tokens cannot drag out an honest sponsor's slow withdrawal. // We arbitrarily set the "griefing threshold" to `minSponsorTokens` because it is the only parameter // denominated in token currency units and we can avoid adding another parameter. FixedPoint.Unsigned memory griefingThreshold = minSponsorTokens; if ( positionToLiquidate.withdrawalRequestPassTimestamp > 0 && // The position is undergoing a slow withdrawal. positionToLiquidate.withdrawalRequestPassTimestamp > getCurrentTime() && // The slow withdrawal has not yet expired. tokensLiquidated.isGreaterThanOrEqual(griefingThreshold) // The liquidated token count is above a "griefing threshold". ) { positionToLiquidate.withdrawalRequestPassTimestamp = getCurrentTime().add(withdrawalLiveness); } emit LiquidationCreated( sponsor, msg.sender, liquidationId, _getFundingRateAppliedTokenDebt(tokensLiquidated).rawValue, lockedCollateral.rawValue, liquidatedCollateral.rawValue, getCurrentTime() ); // Destroy tokens tokenCurrency.safeTransferFrom(msg.sender, address(this), tokensLiquidated.rawValue); tokenCurrency.burn(tokensLiquidated.rawValue); // Pull final fee from liquidator. collateralCurrency.safeTransferFrom(msg.sender, address(this), finalFeeBond.rawValue); } /** * @notice Disputes a liquidation, if the caller has enough collateral to post a dispute bond and pay a fixed final * fee charged on each price request. * @dev Can only dispute a liquidation before the liquidation expires and if there are no other pending disputes. * This contract must be approved to spend at least the dispute bond amount of `collateralCurrency`. This dispute * bond amount is calculated from `disputeBondPercentage` times the collateral in the liquidation. * @param liquidationId of the disputed liquidation. * @param sponsor the address of the sponsor whose liquidation is being disputed. * @return totalPaid amount of collateral charged to disputer (i.e. final fee bond + dispute bond). */ function dispute(uint256 liquidationId, address sponsor) external disputable(liquidationId, sponsor) fees() nonReentrant() returns (FixedPoint.Unsigned memory totalPaid) { LiquidationData storage disputedLiquidation = _getLiquidationData(sponsor, liquidationId); // Multiply by the unit collateral so the dispute bond is a percentage of the locked collateral after fees. FixedPoint.Unsigned memory disputeBondAmount = disputedLiquidation.lockedCollateral.mul(disputeBondPercentage).mul( _getFeeAdjustedCollateral(disputedLiquidation.rawUnitCollateral) ); _addCollateral(rawLiquidationCollateral, disputeBondAmount); // Request a price from DVM. Liquidation is pending dispute until DVM returns a price. disputedLiquidation.state = Status.Disputed; disputedLiquidation.disputer = msg.sender; // Enqueue a request with the DVM. _requestOraclePrice(disputedLiquidation.liquidationTime); emit LiquidationDisputed( sponsor, disputedLiquidation.liquidator, msg.sender, liquidationId, disputeBondAmount.rawValue ); totalPaid = disputeBondAmount.add(disputedLiquidation.finalFee); // Pay the final fee for requesting price from the DVM. _payFinalFees(msg.sender, disputedLiquidation.finalFee); // Transfer the dispute bond amount from the caller to this contract. collateralCurrency.safeTransferFrom(msg.sender, address(this), disputeBondAmount.rawValue); } /** * @notice After a dispute has settled or after a non-disputed liquidation has expired, * anyone can call this method to disperse payments to the sponsor, liquidator, and disputer. * @dev If the dispute SUCCEEDED: the sponsor, liquidator, and disputer are eligible for payment. * If the dispute FAILED: only the liquidator receives payment. This method deletes the liquidation data. * This method will revert if rewards have already been dispersed. * @param liquidationId uniquely identifies the sponsor's liquidation. * @param sponsor address of the sponsor associated with the liquidation. * @return data about rewards paid out. */ function withdrawLiquidation(uint256 liquidationId, address sponsor) public withdrawable(liquidationId, sponsor) fees() nonReentrant() returns (RewardsData memory) { LiquidationData storage liquidation = _getLiquidationData(sponsor, liquidationId); // Settles the liquidation if necessary. This call will revert if the price has not resolved yet. _settle(liquidationId, sponsor); // Calculate rewards as a function of the TRV. // Note1: all payouts are scaled by the unit collateral value so all payouts are charged the fees pro rata. // Note2: the tokenRedemptionValue uses the tokensOutstanding which was calculated using the funding rate at // liquidation time from _getFundingRateAppliedTokenDebt. Therefore the TRV considers the full debt value at that time. FixedPoint.Unsigned memory feeAttenuation = _getFeeAdjustedCollateral(liquidation.rawUnitCollateral); FixedPoint.Unsigned memory settlementPrice = liquidation.settlementPrice; FixedPoint.Unsigned memory tokenRedemptionValue = liquidation.tokensOutstanding.mul(settlementPrice).mul(feeAttenuation); FixedPoint.Unsigned memory collateral = liquidation.lockedCollateral.mul(feeAttenuation); FixedPoint.Unsigned memory disputerDisputeReward = disputerDisputeRewardPercentage.mul(tokenRedemptionValue); FixedPoint.Unsigned memory sponsorDisputeReward = sponsorDisputeRewardPercentage.mul(tokenRedemptionValue); FixedPoint.Unsigned memory disputeBondAmount = collateral.mul(disputeBondPercentage); FixedPoint.Unsigned memory finalFee = liquidation.finalFee.mul(feeAttenuation); // There are three main outcome states: either the dispute succeeded, failed or was not updated. // Based on the state, different parties of a liquidation receive different amounts. // After assigning rewards based on the liquidation status, decrease the total collateral held in this contract // by the amount to pay each party. The actual amounts withdrawn might differ if _removeCollateral causes // precision loss. RewardsData memory rewards; if (liquidation.state == Status.DisputeSucceeded) { // If the dispute is successful then all three users should receive rewards: // Pay DISPUTER: disputer reward + dispute bond + returned final fee rewards.payToDisputer = disputerDisputeReward.add(disputeBondAmount).add(finalFee); // Pay SPONSOR: remaining collateral (collateral - TRV) + sponsor reward rewards.payToSponsor = sponsorDisputeReward.add(collateral.sub(tokenRedemptionValue)); // Pay LIQUIDATOR: TRV - dispute reward - sponsor reward // If TRV > Collateral, then subtract rewards from collateral // NOTE: This should never be below zero since we prevent (sponsorDisputePercentage+disputerDisputePercentage) >= 0 in // the constructor when these params are set. rewards.payToLiquidator = tokenRedemptionValue.sub(sponsorDisputeReward).sub(disputerDisputeReward); // Transfer rewards and debit collateral rewards.paidToLiquidator = _removeCollateral(rawLiquidationCollateral, rewards.payToLiquidator); rewards.paidToSponsor = _removeCollateral(rawLiquidationCollateral, rewards.payToSponsor); rewards.paidToDisputer = _removeCollateral(rawLiquidationCollateral, rewards.payToDisputer); collateralCurrency.safeTransfer(liquidation.disputer, rewards.paidToDisputer.rawValue); collateralCurrency.safeTransfer(liquidation.liquidator, rewards.paidToLiquidator.rawValue); collateralCurrency.safeTransfer(liquidation.sponsor, rewards.paidToSponsor.rawValue); // In the case of a failed dispute only the liquidator can withdraw. } else if (liquidation.state == Status.DisputeFailed) { // Pay LIQUIDATOR: collateral + dispute bond + returned final fee rewards.payToLiquidator = collateral.add(disputeBondAmount).add(finalFee); // Transfer rewards and debit collateral rewards.paidToLiquidator = _removeCollateral(rawLiquidationCollateral, rewards.payToLiquidator); collateralCurrency.safeTransfer(liquidation.liquidator, rewards.paidToLiquidator.rawValue); // If the state is pre-dispute but time has passed liveness then there was no dispute. We represent this // state as a dispute failed and the liquidator can withdraw. } else if (liquidation.state == Status.NotDisputed) { // Pay LIQUIDATOR: collateral + returned final fee rewards.payToLiquidator = collateral.add(finalFee); // Transfer rewards and debit collateral rewards.paidToLiquidator = _removeCollateral(rawLiquidationCollateral, rewards.payToLiquidator); collateralCurrency.safeTransfer(liquidation.liquidator, rewards.paidToLiquidator.rawValue); } emit LiquidationWithdrawn( msg.sender, rewards.paidToLiquidator.rawValue, rewards.paidToDisputer.rawValue, rewards.paidToSponsor.rawValue, liquidation.state, settlementPrice.rawValue ); // Free up space after collateral is withdrawn by removing the liquidation object from the array. delete liquidations[sponsor][liquidationId]; return rewards; } /** * @notice Gets all liquidation information for a given sponsor address. * @param sponsor address of the position sponsor. * @return liquidationData array of all liquidation information for the given sponsor address. */ function getLiquidations(address sponsor) external view nonReentrantView() returns (LiquidationData[] memory liquidationData) { return liquidations[sponsor]; } /**************************************** * INTERNAL FUNCTIONS * ****************************************/ // This settles a liquidation if it is in the Disputed state. If not, it will immediately return. // If the liquidation is in the Disputed state, but a price is not available, this will revert. function _settle(uint256 liquidationId, address sponsor) internal { LiquidationData storage liquidation = _getLiquidationData(sponsor, liquidationId); // Settlement only happens when state == Disputed and will only happen once per liquidation. // If this liquidation is not ready to be settled, this method should return immediately. if (liquidation.state != Status.Disputed) { return; } // Get the returned price from the oracle. If this has not yet resolved will revert. liquidation.settlementPrice = _getOraclePrice(liquidation.liquidationTime); // Find the value of the tokens in the underlying collateral. FixedPoint.Unsigned memory tokenRedemptionValue = liquidation.tokensOutstanding.mul(liquidation.settlementPrice); // The required collateral is the value of the tokens in underlying * required collateral ratio. FixedPoint.Unsigned memory requiredCollateral = tokenRedemptionValue.mul(collateralRequirement); // If the position has more than the required collateral it is solvent and the dispute is valid (liquidation is invalid) // Note that this check uses the liquidatedCollateral not the lockedCollateral as this considers withdrawals. bool disputeSucceeded = liquidation.liquidatedCollateral.isGreaterThanOrEqual(requiredCollateral); liquidation.state = disputeSucceeded ? Status.DisputeSucceeded : Status.DisputeFailed; emit DisputeSettled( msg.sender, sponsor, liquidation.liquidator, liquidation.disputer, liquidationId, disputeSucceeded ); } function _pfc() internal view override returns (FixedPoint.Unsigned memory) { return super._pfc().add(_getFeeAdjustedCollateral(rawLiquidationCollateral)); } function _getLiquidationData(address sponsor, uint256 liquidationId) internal view returns (LiquidationData storage liquidation) { LiquidationData[] storage liquidationArray = liquidations[sponsor]; // Revert if the caller is attempting to access an invalid liquidation // (one that has never been created or one has never been initialized). require( liquidationId < liquidationArray.length && liquidationArray[liquidationId].state != Status.Uninitialized ); return liquidationArray[liquidationId]; } function _getLiquidationExpiry(LiquidationData storage liquidation) internal view returns (uint256) { return liquidation.liquidationTime.add(liquidationLiveness); } // These internal functions are supposed to act identically to modifiers, but re-used modifiers // unnecessarily increase contract bytecode size. // source: https://blog.polymath.network/solidity-tips-and-tricks-to-save-gas-and-reduce-bytecode-size-c44580b218e6 function _disputable(uint256 liquidationId, address sponsor) internal view { LiquidationData storage liquidation = _getLiquidationData(sponsor, liquidationId); require( (getCurrentTime() < _getLiquidationExpiry(liquidation)) && (liquidation.state == Status.NotDisputed), "Liquidation not disputable" ); } function _withdrawable(uint256 liquidationId, address sponsor) internal view { LiquidationData storage liquidation = _getLiquidationData(sponsor, liquidationId); Status state = liquidation.state; // Must be disputed or the liquidation has passed expiry. require( (state > Status.NotDisputed) || ((_getLiquidationExpiry(liquidation) <= getCurrentTime()) && (state == Status.NotDisputed)) ); } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.8.0; pragma abicoder v2; import "@openzeppelin/contracts/utils/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; import "../../common/implementation/FixedPoint.sol"; import "../../common/interfaces/ExpandedIERC20.sol"; import "../../oracle/interfaces/OracleInterface.sol"; import "../../oracle/interfaces/IdentifierWhitelistInterface.sol"; import "../../oracle/implementation/Constants.sol"; import "../common/FundingRateApplier.sol"; /** * @title Financial contract with priceless position management. * @notice Handles positions for multiple sponsors in an optimistic (i.e., priceless) way without relying * on a price feed. On construction, deploys a new ERC20, managed by this contract, that is the synthetic token. */ contract PerpetualPositionManager is FundingRateApplier { using SafeMath for uint256; using FixedPoint for FixedPoint.Unsigned; using SafeERC20 for IERC20; using SafeERC20 for ExpandedIERC20; /**************************************** * PRICELESS POSITION DATA STRUCTURES * ****************************************/ // Represents a single sponsor's position. All collateral is held by this contract. // This struct acts as bookkeeping for how much of that collateral is allocated to each sponsor. struct PositionData { FixedPoint.Unsigned tokensOutstanding; // Tracks pending withdrawal requests. A withdrawal request is pending if `withdrawalRequestPassTimestamp != 0`. uint256 withdrawalRequestPassTimestamp; FixedPoint.Unsigned withdrawalRequestAmount; // Raw collateral value. This value should never be accessed directly -- always use _getFeeAdjustedCollateral(). // To add or remove collateral, use _addCollateral() and _removeCollateral(). FixedPoint.Unsigned rawCollateral; } // Maps sponsor addresses to their positions. Each sponsor can have only one position. mapping(address => PositionData) public positions; // Keep track of the total collateral and tokens across all positions to enable calculating the // global collateralization ratio without iterating over all positions. FixedPoint.Unsigned public totalTokensOutstanding; // Similar to the rawCollateral in PositionData, this value should not be used directly. // _getFeeAdjustedCollateral(), _addCollateral() and _removeCollateral() must be used to access and adjust. FixedPoint.Unsigned public rawTotalPositionCollateral; // Synthetic token created by this contract. ExpandedIERC20 public tokenCurrency; // Unique identifier for DVM price feed ticker. bytes32 public priceIdentifier; // Time that has to elapse for a withdrawal request to be considered passed, if no liquidations occur. // !!Note: The lower the withdrawal liveness value, the more risk incurred by the contract. // Extremely low liveness values increase the chance that opportunistic invalid withdrawal requests // expire without liquidation, thereby increasing the insolvency risk for the contract as a whole. An insolvent // contract is extremely risky for any sponsor or synthetic token holder for the contract. uint256 public withdrawalLiveness; // Minimum number of tokens in a sponsor's position. FixedPoint.Unsigned public minSponsorTokens; // Expiry price pulled from the DVM in the case of an emergency shutdown. FixedPoint.Unsigned public emergencyShutdownPrice; /**************************************** * EVENTS * ****************************************/ event Deposit(address indexed sponsor, uint256 indexed collateralAmount); event Withdrawal(address indexed sponsor, uint256 indexed collateralAmount); event RequestWithdrawal(address indexed sponsor, uint256 indexed collateralAmount); event RequestWithdrawalExecuted(address indexed sponsor, uint256 indexed collateralAmount); event RequestWithdrawalCanceled(address indexed sponsor, uint256 indexed collateralAmount); event PositionCreated(address indexed sponsor, uint256 indexed collateralAmount, uint256 indexed tokenAmount); event NewSponsor(address indexed sponsor); event EndedSponsorPosition(address indexed sponsor); event Redeem(address indexed sponsor, uint256 indexed collateralAmount, uint256 indexed tokenAmount); event Repay(address indexed sponsor, uint256 indexed numTokensRepaid, uint256 indexed newTokenCount); event EmergencyShutdown(address indexed caller, uint256 shutdownTimestamp); event SettleEmergencyShutdown( address indexed caller, uint256 indexed collateralReturned, uint256 indexed tokensBurned ); /**************************************** * MODIFIERS * ****************************************/ modifier onlyCollateralizedPosition(address sponsor) { _onlyCollateralizedPosition(sponsor); _; } modifier noPendingWithdrawal(address sponsor) { _positionHasNoPendingWithdrawal(sponsor); _; } /** * @notice Construct the PerpetualPositionManager. * @dev Deployer of this contract should consider carefully which parties have ability to mint and burn * the synthetic tokens referenced by `_tokenAddress`. This contract's security assumes that no external accounts * can mint new tokens, which could be used to steal all of this contract's locked collateral. * We recommend to only use synthetic token contracts whose sole Owner role (the role capable of adding & removing roles) * is assigned to this contract, whose sole Minter role is assigned to this contract, and whose * total supply is 0 prior to construction of this contract. * @param _withdrawalLiveness liveness delay, in seconds, for pending withdrawals. * @param _collateralAddress ERC20 token used as collateral for all positions. * @param _tokenAddress ERC20 token used as synthetic token. * @param _finderAddress UMA protocol Finder used to discover other protocol contracts. * @param _priceIdentifier registered in the DVM for the synthetic. * @param _fundingRateIdentifier Unique identifier for DVM price feed ticker for child financial contract. * @param _minSponsorTokens minimum number of tokens that must exist at any time in a position. * @param _tokenScaling initial scaling to apply to the token value (i.e. scales the tracking index). * @param _timerAddress Contract that stores the current time in a testing environment. Set to 0x0 for production. */ constructor( uint256 _withdrawalLiveness, address _collateralAddress, address _tokenAddress, address _finderAddress, bytes32 _priceIdentifier, bytes32 _fundingRateIdentifier, FixedPoint.Unsigned memory _minSponsorTokens, address _configStoreAddress, FixedPoint.Unsigned memory _tokenScaling, address _timerAddress ) FundingRateApplier( _fundingRateIdentifier, _collateralAddress, _finderAddress, _configStoreAddress, _tokenScaling, _timerAddress ) { require(_getIdentifierWhitelist().isIdentifierSupported(_priceIdentifier)); withdrawalLiveness = _withdrawalLiveness; tokenCurrency = ExpandedIERC20(_tokenAddress); minSponsorTokens = _minSponsorTokens; priceIdentifier = _priceIdentifier; } /**************************************** * POSITION FUNCTIONS * ****************************************/ /** * @notice Transfers `collateralAmount` of `collateralCurrency` into the specified sponsor's position. * @dev Increases the collateralization level of a position after creation. This contract must be approved to spend * at least `collateralAmount` of `collateralCurrency`. * @param sponsor the sponsor to credit the deposit to. * @param collateralAmount total amount of collateral tokens to be sent to the sponsor's position. */ function depositTo(address sponsor, FixedPoint.Unsigned memory collateralAmount) public notEmergencyShutdown() noPendingWithdrawal(sponsor) fees() nonReentrant() { require(collateralAmount.isGreaterThan(0)); PositionData storage positionData = _getPositionData(sponsor); // Increase the position and global collateral balance by collateral amount. _incrementCollateralBalances(positionData, collateralAmount); emit Deposit(sponsor, collateralAmount.rawValue); // Move collateral currency from sender to contract. collateralCurrency.safeTransferFrom(msg.sender, address(this), collateralAmount.rawValue); } /** * @notice Transfers `collateralAmount` of `collateralCurrency` into the caller's position. * @dev Increases the collateralization level of a position after creation. This contract must be approved to spend * at least `collateralAmount` of `collateralCurrency`. * @param collateralAmount total amount of collateral tokens to be sent to the sponsor's position. */ function deposit(FixedPoint.Unsigned memory collateralAmount) public { // This is just a thin wrapper over depositTo that specified the sender as the sponsor. depositTo(msg.sender, collateralAmount); } /** * @notice Transfers `collateralAmount` of `collateralCurrency` from the sponsor's position to the sponsor. * @dev Reverts if the withdrawal puts this position's collateralization ratio below the global collateralization * ratio. In that case, use `requestWithdrawal`. Might not withdraw the full requested amount to account for precision loss. * @param collateralAmount is the amount of collateral to withdraw. * @return amountWithdrawn The actual amount of collateral withdrawn. */ function withdraw(FixedPoint.Unsigned memory collateralAmount) public notEmergencyShutdown() noPendingWithdrawal(msg.sender) fees() nonReentrant() returns (FixedPoint.Unsigned memory amountWithdrawn) { require(collateralAmount.isGreaterThan(0)); PositionData storage positionData = _getPositionData(msg.sender); // Decrement the sponsor's collateral and global collateral amounts. Check the GCR between decrement to ensure // position remains above the GCR within the withdrawal. If this is not the case the caller must submit a request. amountWithdrawn = _decrementCollateralBalancesCheckGCR(positionData, collateralAmount); emit Withdrawal(msg.sender, amountWithdrawn.rawValue); // Move collateral currency from contract to sender. // Note: that we move the amount of collateral that is decreased from rawCollateral (inclusive of fees) // instead of the user requested amount. This eliminates precision loss that could occur // where the user withdraws more collateral than rawCollateral is decremented by. collateralCurrency.safeTransfer(msg.sender, amountWithdrawn.rawValue); } /** * @notice Starts a withdrawal request that, if passed, allows the sponsor to withdraw from their position. * @dev The request will be pending for `withdrawalLiveness`, during which the position can be liquidated. * @param collateralAmount the amount of collateral requested to withdraw */ function requestWithdrawal(FixedPoint.Unsigned memory collateralAmount) public notEmergencyShutdown() noPendingWithdrawal(msg.sender) nonReentrant() { PositionData storage positionData = _getPositionData(msg.sender); require( collateralAmount.isGreaterThan(0) && collateralAmount.isLessThanOrEqual(_getFeeAdjustedCollateral(positionData.rawCollateral)) ); // Update the position object for the user. positionData.withdrawalRequestPassTimestamp = getCurrentTime().add(withdrawalLiveness); positionData.withdrawalRequestAmount = collateralAmount; emit RequestWithdrawal(msg.sender, collateralAmount.rawValue); } /** * @notice After a passed withdrawal request (i.e., by a call to `requestWithdrawal` and waiting * `withdrawalLiveness`), withdraws `positionData.withdrawalRequestAmount` of collateral currency. * @dev Might not withdraw the full requested amount in order to account for precision loss or if the full requested * amount exceeds the collateral in the position (due to paying fees). * @return amountWithdrawn The actual amount of collateral withdrawn. */ function withdrawPassedRequest() external notEmergencyShutdown() fees() nonReentrant() returns (FixedPoint.Unsigned memory amountWithdrawn) { PositionData storage positionData = _getPositionData(msg.sender); require( positionData.withdrawalRequestPassTimestamp != 0 && positionData.withdrawalRequestPassTimestamp <= getCurrentTime() ); // If withdrawal request amount is > position collateral, then withdraw the full collateral amount. // This situation is possible due to fees charged since the withdrawal was originally requested. FixedPoint.Unsigned memory amountToWithdraw = positionData.withdrawalRequestAmount; if (positionData.withdrawalRequestAmount.isGreaterThan(_getFeeAdjustedCollateral(positionData.rawCollateral))) { amountToWithdraw = _getFeeAdjustedCollateral(positionData.rawCollateral); } // Decrement the sponsor's collateral and global collateral amounts. amountWithdrawn = _decrementCollateralBalances(positionData, amountToWithdraw); // Reset withdrawal request by setting withdrawal amount and withdrawal timestamp to 0. _resetWithdrawalRequest(positionData); // Transfer approved withdrawal amount from the contract to the caller. collateralCurrency.safeTransfer(msg.sender, amountWithdrawn.rawValue); emit RequestWithdrawalExecuted(msg.sender, amountWithdrawn.rawValue); } /** * @notice Cancels a pending withdrawal request. */ function cancelWithdrawal() external notEmergencyShutdown() nonReentrant() { PositionData storage positionData = _getPositionData(msg.sender); // No pending withdrawal require message removed to save bytecode. require(positionData.withdrawalRequestPassTimestamp != 0); emit RequestWithdrawalCanceled(msg.sender, positionData.withdrawalRequestAmount.rawValue); // Reset withdrawal request by setting withdrawal amount and withdrawal timestamp to 0. _resetWithdrawalRequest(positionData); } /** * @notice Creates tokens by creating a new position or by augmenting an existing position. Pulls `collateralAmount * ` into the sponsor's position and mints `numTokens` of `tokenCurrency`. * @dev This contract must have the Minter role for the `tokenCurrency`. * @dev Reverts if minting these tokens would put the position's collateralization ratio below the * global collateralization ratio. This contract must be approved to spend at least `collateralAmount` of * `collateralCurrency`. * @param collateralAmount is the number of collateral tokens to collateralize the position with * @param numTokens is the number of tokens to mint from the position. */ function create(FixedPoint.Unsigned memory collateralAmount, FixedPoint.Unsigned memory numTokens) public notEmergencyShutdown() fees() nonReentrant() { PositionData storage positionData = positions[msg.sender]; // Either the new create ratio or the resultant position CR must be above the current GCR. require( (_checkCollateralization( _getFeeAdjustedCollateral(positionData.rawCollateral).add(collateralAmount), positionData.tokensOutstanding.add(numTokens) ) || _checkCollateralization(collateralAmount, numTokens)), "Insufficient collateral" ); require(positionData.withdrawalRequestPassTimestamp == 0); if (positionData.tokensOutstanding.isEqual(0)) { require(numTokens.isGreaterThanOrEqual(minSponsorTokens)); emit NewSponsor(msg.sender); } // Increase the position and global collateral balance by collateral amount. _incrementCollateralBalances(positionData, collateralAmount); // Add the number of tokens created to the position's outstanding tokens. positionData.tokensOutstanding = positionData.tokensOutstanding.add(numTokens); totalTokensOutstanding = totalTokensOutstanding.add(numTokens); emit PositionCreated(msg.sender, collateralAmount.rawValue, numTokens.rawValue); // Transfer tokens into the contract from caller and mint corresponding synthetic tokens to the caller's address. collateralCurrency.safeTransferFrom(msg.sender, address(this), collateralAmount.rawValue); // Note: revert reason removed to save bytecode. require(tokenCurrency.mint(msg.sender, numTokens.rawValue)); } /** * @notice Burns `numTokens` of `tokenCurrency` and sends back the proportional amount of `collateralCurrency`. * @dev Can only be called by a token sponsor. Might not redeem the full proportional amount of collateral * in order to account for precision loss. This contract must be approved to spend at least `numTokens` of * `tokenCurrency`. * @dev This contract must have the Burner role for the `tokenCurrency`. * @param numTokens is the number of tokens to be burnt for a commensurate amount of collateral. * @return amountWithdrawn The actual amount of collateral withdrawn. */ function redeem(FixedPoint.Unsigned memory numTokens) public notEmergencyShutdown() noPendingWithdrawal(msg.sender) fees() nonReentrant() returns (FixedPoint.Unsigned memory amountWithdrawn) { PositionData storage positionData = _getPositionData(msg.sender); require(numTokens.isLessThanOrEqual(positionData.tokensOutstanding)); FixedPoint.Unsigned memory fractionRedeemed = numTokens.div(positionData.tokensOutstanding); FixedPoint.Unsigned memory collateralRedeemed = fractionRedeemed.mul(_getFeeAdjustedCollateral(positionData.rawCollateral)); // If redemption returns all tokens the sponsor has then we can delete their position. Else, downsize. if (positionData.tokensOutstanding.isEqual(numTokens)) { amountWithdrawn = _deleteSponsorPosition(msg.sender); } else { // Decrement the sponsor's collateral and global collateral amounts. amountWithdrawn = _decrementCollateralBalances(positionData, collateralRedeemed); // Decrease the sponsors position tokens size. Ensure it is above the min sponsor size. FixedPoint.Unsigned memory newTokenCount = positionData.tokensOutstanding.sub(numTokens); require(newTokenCount.isGreaterThanOrEqual(minSponsorTokens)); positionData.tokensOutstanding = newTokenCount; // Update the totalTokensOutstanding after redemption. totalTokensOutstanding = totalTokensOutstanding.sub(numTokens); } emit Redeem(msg.sender, amountWithdrawn.rawValue, numTokens.rawValue); // Transfer collateral from contract to caller and burn callers synthetic tokens. collateralCurrency.safeTransfer(msg.sender, amountWithdrawn.rawValue); tokenCurrency.safeTransferFrom(msg.sender, address(this), numTokens.rawValue); tokenCurrency.burn(numTokens.rawValue); } /** * @notice Burns `numTokens` of `tokenCurrency` to decrease sponsors position size, without sending back `collateralCurrency`. * This is done by a sponsor to increase position CR. Resulting size is bounded by minSponsorTokens. * @dev Can only be called by token sponsor. This contract must be approved to spend `numTokens` of `tokenCurrency`. * @dev This contract must have the Burner role for the `tokenCurrency`. * @param numTokens is the number of tokens to be burnt from the sponsor's debt position. */ function repay(FixedPoint.Unsigned memory numTokens) public notEmergencyShutdown() noPendingWithdrawal(msg.sender) fees() nonReentrant() { PositionData storage positionData = _getPositionData(msg.sender); require(numTokens.isLessThanOrEqual(positionData.tokensOutstanding)); // Decrease the sponsors position tokens size. Ensure it is above the min sponsor size. FixedPoint.Unsigned memory newTokenCount = positionData.tokensOutstanding.sub(numTokens); require(newTokenCount.isGreaterThanOrEqual(minSponsorTokens)); positionData.tokensOutstanding = newTokenCount; // Update the totalTokensOutstanding after redemption. totalTokensOutstanding = totalTokensOutstanding.sub(numTokens); emit Repay(msg.sender, numTokens.rawValue, newTokenCount.rawValue); // Transfer the tokens back from the sponsor and burn them. tokenCurrency.safeTransferFrom(msg.sender, address(this), numTokens.rawValue); tokenCurrency.burn(numTokens.rawValue); } /** * @notice If the contract is emergency shutdown then all token holders and sponsors can redeem their tokens or * remaining collateral for underlying at the prevailing price defined by a DVM vote. * @dev This burns all tokens from the caller of `tokenCurrency` and sends back the resolved settlement value of * `collateralCurrency`. Might not redeem the full proportional amount of collateral in order to account for * precision loss. This contract must be approved to spend `tokenCurrency` at least up to the caller's full balance. * @dev This contract must have the Burner role for the `tokenCurrency`. * @dev Note that this function does not call the updateFundingRate modifier to update the funding rate as this * function is only called after an emergency shutdown & there should be no funding rate updates after the shutdown. * @return amountWithdrawn The actual amount of collateral withdrawn. */ function settleEmergencyShutdown() external isEmergencyShutdown() fees() nonReentrant() returns (FixedPoint.Unsigned memory amountWithdrawn) { // Set the emergency shutdown price as resolved from the DVM. If DVM has not resolved will revert. if (emergencyShutdownPrice.isEqual(FixedPoint.fromUnscaledUint(0))) { emergencyShutdownPrice = _getOracleEmergencyShutdownPrice(); } // Get caller's tokens balance and calculate amount of underlying entitled to them. FixedPoint.Unsigned memory tokensToRedeem = FixedPoint.Unsigned(tokenCurrency.balanceOf(msg.sender)); FixedPoint.Unsigned memory totalRedeemableCollateral = _getFundingRateAppliedTokenDebt(tokensToRedeem).mul(emergencyShutdownPrice); // If the caller is a sponsor with outstanding collateral they are also entitled to their excess collateral after their debt. PositionData storage positionData = positions[msg.sender]; if (_getFeeAdjustedCollateral(positionData.rawCollateral).isGreaterThan(0)) { // Calculate the underlying entitled to a token sponsor. This is collateral - debt in underlying with // the funding rate applied to the outstanding token debt. FixedPoint.Unsigned memory tokenDebtValueInCollateral = _getFundingRateAppliedTokenDebt(positionData.tokensOutstanding).mul(emergencyShutdownPrice); FixedPoint.Unsigned memory positionCollateral = _getFeeAdjustedCollateral(positionData.rawCollateral); // If the debt is greater than the remaining collateral, they cannot redeem anything. FixedPoint.Unsigned memory positionRedeemableCollateral = tokenDebtValueInCollateral.isLessThan(positionCollateral) ? positionCollateral.sub(tokenDebtValueInCollateral) : FixedPoint.Unsigned(0); // Add the number of redeemable tokens for the sponsor to their total redeemable collateral. totalRedeemableCollateral = totalRedeemableCollateral.add(positionRedeemableCollateral); // Reset the position state as all the value has been removed after settlement. delete positions[msg.sender]; emit EndedSponsorPosition(msg.sender); } // Take the min of the remaining collateral and the collateral "owed". If the contract is undercapitalized, // the caller will get as much collateral as the contract can pay out. FixedPoint.Unsigned memory payout = FixedPoint.min(_getFeeAdjustedCollateral(rawTotalPositionCollateral), totalRedeemableCollateral); // Decrement total contract collateral and outstanding debt. amountWithdrawn = _removeCollateral(rawTotalPositionCollateral, payout); totalTokensOutstanding = totalTokensOutstanding.sub(tokensToRedeem); emit SettleEmergencyShutdown(msg.sender, amountWithdrawn.rawValue, tokensToRedeem.rawValue); // Transfer tokens & collateral and burn the redeemed tokens. collateralCurrency.safeTransfer(msg.sender, amountWithdrawn.rawValue); tokenCurrency.safeTransferFrom(msg.sender, address(this), tokensToRedeem.rawValue); tokenCurrency.burn(tokensToRedeem.rawValue); } /**************************************** * GLOBAL STATE FUNCTIONS * ****************************************/ /** * @notice Premature contract settlement under emergency circumstances. * @dev Only the governor can call this function as they are permissioned within the `FinancialContractAdmin`. * Upon emergency shutdown, the contract settlement time is set to the shutdown time. This enables withdrawal * to occur via the `settleEmergencyShutdown` function. */ function emergencyShutdown() external override notEmergencyShutdown() fees() nonReentrant() { // Note: revert reason removed to save bytecode. require(msg.sender == _getFinancialContractsAdminAddress()); emergencyShutdownTimestamp = getCurrentTime(); _requestOraclePrice(emergencyShutdownTimestamp); emit EmergencyShutdown(msg.sender, emergencyShutdownTimestamp); } /** * @notice Theoretically supposed to pay fees and move money between margin accounts to make sure they * reflect the NAV of the contract. However, this functionality doesn't apply to this contract. * @dev This is supposed to be implemented by any contract that inherits `AdministrateeInterface` and callable * only by the Governor contract. This method is therefore minimally implemented in this contract and does nothing. */ function remargin() external override { return; } /** * @notice Accessor method for a sponsor's collateral. * @dev This is necessary because the struct returned by the positions() method shows * rawCollateral, which isn't a user-readable value. * @dev This method accounts for pending regular fees that have not yet been withdrawn from this contract, for * example if the `lastPaymentTime != currentTime`. * @param sponsor address whose collateral amount is retrieved. * @return collateralAmount amount of collateral within a sponsors position. */ function getCollateral(address sponsor) external view nonReentrantView() returns (FixedPoint.Unsigned memory collateralAmount) { // Note: do a direct access to avoid the validity check. return _getPendingRegularFeeAdjustedCollateral(_getFeeAdjustedCollateral(positions[sponsor].rawCollateral)); } /** * @notice Accessor method for the total collateral stored within the PerpetualPositionManager. * @return totalCollateral amount of all collateral within the position manager. */ function totalPositionCollateral() external view nonReentrantView() returns (FixedPoint.Unsigned memory totalCollateral) { return _getPendingRegularFeeAdjustedCollateral(_getFeeAdjustedCollateral(rawTotalPositionCollateral)); } function getFundingRateAppliedTokenDebt(FixedPoint.Unsigned memory rawTokenDebt) external view nonReentrantView() returns (FixedPoint.Unsigned memory totalCollateral) { return _getFundingRateAppliedTokenDebt(rawTokenDebt); } /**************************************** * INTERNAL FUNCTIONS * ****************************************/ // Reduces a sponsor's position and global counters by the specified parameters. Handles deleting the entire // position if the entire position is being removed. Does not make any external transfers. function _reduceSponsorPosition( address sponsor, FixedPoint.Unsigned memory tokensToRemove, FixedPoint.Unsigned memory collateralToRemove, FixedPoint.Unsigned memory withdrawalAmountToRemove ) internal { PositionData storage positionData = _getPositionData(sponsor); // If the entire position is being removed, delete it instead. if ( tokensToRemove.isEqual(positionData.tokensOutstanding) && _getFeeAdjustedCollateral(positionData.rawCollateral).isEqual(collateralToRemove) ) { _deleteSponsorPosition(sponsor); return; } // Decrement the sponsor's collateral and global collateral amounts. _decrementCollateralBalances(positionData, collateralToRemove); // Ensure that the sponsor will meet the min position size after the reduction. positionData.tokensOutstanding = positionData.tokensOutstanding.sub(tokensToRemove); require(positionData.tokensOutstanding.isGreaterThanOrEqual(minSponsorTokens)); // Decrement the position's withdrawal amount. positionData.withdrawalRequestAmount = positionData.withdrawalRequestAmount.sub(withdrawalAmountToRemove); // Decrement the total outstanding tokens in the overall contract. totalTokensOutstanding = totalTokensOutstanding.sub(tokensToRemove); } // Deletes a sponsor's position and updates global counters. Does not make any external transfers. function _deleteSponsorPosition(address sponsor) internal returns (FixedPoint.Unsigned memory) { PositionData storage positionToLiquidate = _getPositionData(sponsor); FixedPoint.Unsigned memory startingGlobalCollateral = _getFeeAdjustedCollateral(rawTotalPositionCollateral); // Remove the collateral and outstanding from the overall total position. rawTotalPositionCollateral = rawTotalPositionCollateral.sub(positionToLiquidate.rawCollateral); totalTokensOutstanding = totalTokensOutstanding.sub(positionToLiquidate.tokensOutstanding); // Reset the sponsors position to have zero outstanding and collateral. delete positions[sponsor]; emit EndedSponsorPosition(sponsor); // Return fee-adjusted amount of collateral deleted from position. return startingGlobalCollateral.sub(_getFeeAdjustedCollateral(rawTotalPositionCollateral)); } function _pfc() internal view virtual override returns (FixedPoint.Unsigned memory) { return _getFeeAdjustedCollateral(rawTotalPositionCollateral); } function _getPositionData(address sponsor) internal view onlyCollateralizedPosition(sponsor) returns (PositionData storage) { return positions[sponsor]; } function _getIdentifierWhitelist() internal view returns (IdentifierWhitelistInterface) { return IdentifierWhitelistInterface(finder.getImplementationAddress(OracleInterfaces.IdentifierWhitelist)); } function _getOracle() internal view returns (OracleInterface) { return OracleInterface(finder.getImplementationAddress(OracleInterfaces.Oracle)); } function _getFinancialContractsAdminAddress() internal view returns (address) { return finder.getImplementationAddress(OracleInterfaces.FinancialContractsAdmin); } // Requests a price for `priceIdentifier` at `requestedTime` from the Oracle. function _requestOraclePrice(uint256 requestedTime) internal { _getOracle().requestPrice(priceIdentifier, requestedTime); } // Fetches a resolved Oracle price from the Oracle. Reverts if the Oracle hasn't resolved for this request. function _getOraclePrice(uint256 requestedTime) internal view returns (FixedPoint.Unsigned memory price) { // Create an instance of the oracle and get the price. If the price is not resolved revert. int256 oraclePrice = _getOracle().getPrice(priceIdentifier, requestedTime); // For now we don't want to deal with negative prices in positions. if (oraclePrice < 0) { oraclePrice = 0; } return FixedPoint.Unsigned(uint256(oraclePrice)); } // Fetches a resolved Oracle price from the Oracle. Reverts if the Oracle hasn't resolved for this request. function _getOracleEmergencyShutdownPrice() internal view returns (FixedPoint.Unsigned memory) { return _getOraclePrice(emergencyShutdownTimestamp); } // Reset withdrawal request by setting the withdrawal request and withdrawal timestamp to 0. function _resetWithdrawalRequest(PositionData storage positionData) internal { positionData.withdrawalRequestAmount = FixedPoint.fromUnscaledUint(0); positionData.withdrawalRequestPassTimestamp = 0; } // Ensure individual and global consistency when increasing collateral balances. Returns the change to the position. function _incrementCollateralBalances( PositionData storage positionData, FixedPoint.Unsigned memory collateralAmount ) internal returns (FixedPoint.Unsigned memory) { _addCollateral(positionData.rawCollateral, collateralAmount); return _addCollateral(rawTotalPositionCollateral, collateralAmount); } // Ensure individual and global consistency when decrementing collateral balances. Returns the change to the // position. We elect to return the amount that the global collateral is decreased by, rather than the individual // position's collateral, because we need to maintain the invariant that the global collateral is always // <= the collateral owned by the contract to avoid reverts on withdrawals. The amount returned = amount withdrawn. function _decrementCollateralBalances( PositionData storage positionData, FixedPoint.Unsigned memory collateralAmount ) internal returns (FixedPoint.Unsigned memory) { _removeCollateral(positionData.rawCollateral, collateralAmount); return _removeCollateral(rawTotalPositionCollateral, collateralAmount); } // Ensure individual and global consistency when decrementing collateral balances. Returns the change to the position. // This function is similar to the _decrementCollateralBalances function except this function checks position GCR // between the decrements. This ensures that collateral removal will not leave the position undercollateralized. function _decrementCollateralBalancesCheckGCR( PositionData storage positionData, FixedPoint.Unsigned memory collateralAmount ) internal returns (FixedPoint.Unsigned memory) { _removeCollateral(positionData.rawCollateral, collateralAmount); require(_checkPositionCollateralization(positionData), "CR below GCR"); return _removeCollateral(rawTotalPositionCollateral, collateralAmount); } // These internal functions are supposed to act identically to modifiers, but re-used modifiers // unnecessarily increase contract bytecode size. // source: https://blog.polymath.network/solidity-tips-and-tricks-to-save-gas-and-reduce-bytecode-size-c44580b218e6 function _onlyCollateralizedPosition(address sponsor) internal view { require(_getFeeAdjustedCollateral(positions[sponsor].rawCollateral).isGreaterThan(0)); } // Note: This checks whether an already existing position has a pending withdrawal. This cannot be used on the // `create` method because it is possible that `create` is called on a new position (i.e. one without any collateral // or tokens outstanding) which would fail the `onlyCollateralizedPosition` modifier on `_getPositionData`. function _positionHasNoPendingWithdrawal(address sponsor) internal view { require(_getPositionData(sponsor).withdrawalRequestPassTimestamp == 0); } /**************************************** * PRIVATE FUNCTIONS * ****************************************/ function _checkPositionCollateralization(PositionData storage positionData) private view returns (bool) { return _checkCollateralization( _getFeeAdjustedCollateral(positionData.rawCollateral), positionData.tokensOutstanding ); } // Checks whether the provided `collateral` and `numTokens` have a collateralization ratio above the global // collateralization ratio. function _checkCollateralization(FixedPoint.Unsigned memory collateral, FixedPoint.Unsigned memory numTokens) private view returns (bool) { FixedPoint.Unsigned memory global = _getCollateralizationRatio(_getFeeAdjustedCollateral(rawTotalPositionCollateral), totalTokensOutstanding); FixedPoint.Unsigned memory thisChange = _getCollateralizationRatio(collateral, numTokens); return !global.isGreaterThan(thisChange); } function _getCollateralizationRatio(FixedPoint.Unsigned memory collateral, FixedPoint.Unsigned memory numTokens) private pure returns (FixedPoint.Unsigned memory ratio) { return numTokens.isLessThanOrEqual(0) ? FixedPoint.fromUnscaledUint(0) : collateral.div(numTokens); } function _getTokenAddress() internal view override returns (address) { return address(tokenCurrency); } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.8.0; pragma abicoder v2; import "@openzeppelin/contracts/utils/math/SafeCast.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; import "../../common/implementation/Lockable.sol"; import "../../common/implementation/FixedPoint.sol"; import "../../common/implementation/Testable.sol"; import "../../oracle/implementation/Constants.sol"; import "../../oracle/interfaces/OptimisticOracleInterface.sol"; import "../perpetual-multiparty/ConfigStoreInterface.sol"; import "./EmergencyShutdownable.sol"; import "./FeePayer.sol"; /** * @title FundingRateApplier contract. * @notice Provides funding rate payment functionality for the Perpetual contract. */ abstract contract FundingRateApplier is EmergencyShutdownable, FeePayer { using FixedPoint for FixedPoint.Unsigned; using FixedPoint for FixedPoint.Signed; using SafeERC20 for IERC20; using SafeMath for uint256; /**************************************** * FUNDING RATE APPLIER DATA STRUCTURES * ****************************************/ struct FundingRate { // Current funding rate value. FixedPoint.Signed rate; // Identifier to retrieve the funding rate. bytes32 identifier; // Tracks the cumulative funding payments that have been paid to the sponsors. // The multiplier starts at 1, and is updated by computing cumulativeFundingRateMultiplier * (1 + effectivePayment). // Put another way, the cumulativeFeeMultiplier is (1 + effectivePayment1) * (1 + effectivePayment2) ... // For example: // The cumulativeFundingRateMultiplier should start at 1. // If a 1% funding payment is paid to sponsors, the multiplier should update to 1.01. // If another 1% fee is charged, the multiplier should be 1.01^2 (1.0201). FixedPoint.Unsigned cumulativeMultiplier; // Most recent time that the funding rate was updated. uint256 updateTime; // Most recent time that the funding rate was applied and changed the cumulative multiplier. uint256 applicationTime; // The time for the active (if it exists) funding rate proposal. 0 otherwise. uint256 proposalTime; } FundingRate public fundingRate; // Remote config store managed an owner. ConfigStoreInterface public configStore; /**************************************** * EVENTS * ****************************************/ event FundingRateUpdated(int256 newFundingRate, uint256 indexed updateTime, uint256 reward); /**************************************** * MODIFIERS * ****************************************/ // This is overridden to both pay fees (which is done by applyFundingRate()) and apply the funding rate. modifier fees override { // Note: the funding rate is applied on every fee-accruing transaction, where the total change is simply the // rate applied linearly since the last update. This implies that the compounding rate depends on the frequency // of update transactions that have this modifier, and it never reaches the ideal of continuous compounding. // This approximate-compounding pattern is common in the Ethereum ecosystem because of the complexity of // compounding data on-chain. applyFundingRate(); _; } // Note: this modifier is intended to be used if the caller intends to _only_ pay regular fees. modifier paysRegularFees { payRegularFees(); _; } /** * @notice Constructs the FundingRateApplier contract. Called by child contracts. * @param _fundingRateIdentifier identifier that tracks the funding rate of this contract. * @param _collateralAddress address of the collateral token. * @param _finderAddress Finder used to discover financial-product-related contracts. * @param _configStoreAddress address of the remote configuration store managed by an external owner. * @param _tokenScaling initial scaling to apply to the token value (i.e. scales the tracking index). * @param _timerAddress address of the timer contract in test envs, otherwise 0x0. */ constructor( bytes32 _fundingRateIdentifier, address _collateralAddress, address _finderAddress, address _configStoreAddress, FixedPoint.Unsigned memory _tokenScaling, address _timerAddress ) FeePayer(_collateralAddress, _finderAddress, _timerAddress) EmergencyShutdownable() { uint256 currentTime = getCurrentTime(); fundingRate.updateTime = currentTime; fundingRate.applicationTime = currentTime; // Seed the cumulative multiplier with the token scaling, from which it will be scaled as funding rates are // applied over time. fundingRate.cumulativeMultiplier = _tokenScaling; fundingRate.identifier = _fundingRateIdentifier; configStore = ConfigStoreInterface(_configStoreAddress); } /** * @notice This method takes 3 distinct actions: * 1. Pays out regular fees. * 2. If possible, resolves the outstanding funding rate proposal, pulling the result in and paying out the rewards. * 3. Applies the prevailing funding rate over the most recent period. */ function applyFundingRate() public paysRegularFees() nonReentrant() { _applyEffectiveFundingRate(); } /** * @notice Proposes a new funding rate. Proposer receives a reward if correct. * @param rate funding rate being proposed. * @param timestamp time at which the funding rate was computed. */ function proposeFundingRate(FixedPoint.Signed memory rate, uint256 timestamp) external fees() nonReentrant() returns (FixedPoint.Unsigned memory totalBond) { require(fundingRate.proposalTime == 0, "Proposal in progress"); _validateFundingRate(rate); // Timestamp must be after the last funding rate update time, within the last 30 minutes. uint256 currentTime = getCurrentTime(); uint256 updateTime = fundingRate.updateTime; require( timestamp > updateTime && timestamp >= currentTime.sub(_getConfig().proposalTimePastLimit), "Invalid proposal time" ); // Set the proposal time in order to allow this contract to track this request. fundingRate.proposalTime = timestamp; OptimisticOracleInterface optimisticOracle = _getOptimisticOracle(); // Set up optimistic oracle. bytes32 identifier = fundingRate.identifier; bytes memory ancillaryData = _getAncillaryData(); // Note: requestPrice will revert if `timestamp` is less than the current block timestamp. optimisticOracle.requestPrice(identifier, timestamp, ancillaryData, collateralCurrency, 0); totalBond = FixedPoint.Unsigned( optimisticOracle.setBond( identifier, timestamp, ancillaryData, _pfc().mul(_getConfig().proposerBondPercentage).rawValue ) ); // Pull bond from caller and send to optimistic oracle. if (totalBond.isGreaterThan(0)) { collateralCurrency.safeTransferFrom(msg.sender, address(this), totalBond.rawValue); collateralCurrency.safeIncreaseAllowance(address(optimisticOracle), totalBond.rawValue); } optimisticOracle.proposePriceFor( msg.sender, address(this), identifier, timestamp, ancillaryData, rate.rawValue ); } // Returns a token amount scaled by the current funding rate multiplier. // Note: if the contract has paid fees since it was deployed, the raw value should be larger than the returned value. function _getFundingRateAppliedTokenDebt(FixedPoint.Unsigned memory rawTokenDebt) internal view returns (FixedPoint.Unsigned memory tokenDebt) { return rawTokenDebt.mul(fundingRate.cumulativeMultiplier); } function _getOptimisticOracle() internal view returns (OptimisticOracleInterface) { return OptimisticOracleInterface(finder.getImplementationAddress(OracleInterfaces.OptimisticOracle)); } function _getConfig() internal returns (ConfigStoreInterface.ConfigSettings memory) { return configStore.updateAndGetCurrentConfig(); } function _updateFundingRate() internal { uint256 proposalTime = fundingRate.proposalTime; // If there is no pending proposal then do nothing. Otherwise check to see if we can update the funding rate. if (proposalTime != 0) { // Attempt to update the funding rate. OptimisticOracleInterface optimisticOracle = _getOptimisticOracle(); bytes32 identifier = fundingRate.identifier; bytes memory ancillaryData = _getAncillaryData(); // Try to get the price from the optimistic oracle. This call will revert if the request has not resolved // yet. If the request has not resolved yet, then we need to do additional checks to see if we should // "forget" the pending proposal and allow new proposals to update the funding rate. try optimisticOracle.settleAndGetPrice(identifier, proposalTime, ancillaryData) returns (int256 price) { // If successful, determine if the funding rate state needs to be updated. // If the request is more recent than the last update then we should update it. uint256 lastUpdateTime = fundingRate.updateTime; if (proposalTime >= lastUpdateTime) { // Update funding rates fundingRate.rate = FixedPoint.Signed(price); fundingRate.updateTime = proposalTime; // If there was no dispute, send a reward. FixedPoint.Unsigned memory reward = FixedPoint.fromUnscaledUint(0); OptimisticOracleInterface.Request memory request = optimisticOracle.getRequest(address(this), identifier, proposalTime, ancillaryData); if (request.disputer == address(0)) { reward = _pfc().mul(_getConfig().rewardRatePerSecond).mul(proposalTime.sub(lastUpdateTime)); if (reward.isGreaterThan(0)) { _adjustCumulativeFeeMultiplier(reward, _pfc()); collateralCurrency.safeTransfer(request.proposer, reward.rawValue); } } // This event will only be emitted after the fundingRate struct's "updateTime" has been set // to the latest proposal's proposalTime, indicating that the proposal has been published. // So, it suffices to just emit fundingRate.updateTime here. emit FundingRateUpdated(fundingRate.rate.rawValue, fundingRate.updateTime, reward.rawValue); } // Set proposal time to 0 since this proposal has now been resolved. fundingRate.proposalTime = 0; } catch { // Stop tracking and allow other proposals to come in if: // - The requester address is empty, indicating that the Oracle does not know about this funding rate // request. This is possible if the Oracle is replaced while the price request is still pending. // - The request has been disputed. OptimisticOracleInterface.Request memory request = optimisticOracle.getRequest(address(this), identifier, proposalTime, ancillaryData); if (request.disputer != address(0) || request.proposer == address(0)) { fundingRate.proposalTime = 0; } } } } // Constraining the range of funding rates limits the PfC for any dishonest proposer and enhances the // perpetual's security. For example, let's examine the case where the max and min funding rates // are equivalent to +/- 500%/year. This 1000% funding rate range allows a 8.6% profit from corruption for a // proposer who can deter honest proposers for 74 hours: // 1000%/year / 360 days / 24 hours * 74 hours max attack time = ~ 8.6%. // How would attack work? Imagine that the market is very volatile currently and that the "true" funding // rate for the next 74 hours is -500%, but a dishonest proposer successfully proposes a rate of +500% // (after a two hour liveness) and disputes honest proposers for the next 72 hours. This results in a funding // rate error of 1000% for 74 hours, until the DVM can set the funding rate back to its correct value. function _validateFundingRate(FixedPoint.Signed memory rate) internal { require( rate.isLessThanOrEqual(_getConfig().maxFundingRate) && rate.isGreaterThanOrEqual(_getConfig().minFundingRate) ); } // Fetches a funding rate from the Store, determines the period over which to compute an effective fee, // and multiplies the current multiplier by the effective fee. // A funding rate < 1 will reduce the multiplier, and a funding rate of > 1 will increase the multiplier. // Note: 1 is set as the neutral rate because there are no negative numbers in FixedPoint, so we decide to treat // values < 1 as "negative". function _applyEffectiveFundingRate() internal { // If contract is emergency shutdown, then the funding rate multiplier should no longer change. if (emergencyShutdownTimestamp != 0) { return; } uint256 currentTime = getCurrentTime(); uint256 paymentPeriod = currentTime.sub(fundingRate.applicationTime); _updateFundingRate(); // Update the funding rate if there is a resolved proposal. fundingRate.cumulativeMultiplier = _calculateEffectiveFundingRate( paymentPeriod, fundingRate.rate, fundingRate.cumulativeMultiplier ); fundingRate.applicationTime = currentTime; } function _calculateEffectiveFundingRate( uint256 paymentPeriodSeconds, FixedPoint.Signed memory fundingRatePerSecond, FixedPoint.Unsigned memory currentCumulativeFundingRateMultiplier ) internal pure returns (FixedPoint.Unsigned memory newCumulativeFundingRateMultiplier) { // Note: this method uses named return variables to save a little bytecode. // The overall formula that this function is performing: // newCumulativeFundingRateMultiplier = // (1 + (fundingRatePerSecond * paymentPeriodSeconds)) * currentCumulativeFundingRateMultiplier. FixedPoint.Signed memory ONE = FixedPoint.fromUnscaledInt(1); // Multiply the per-second rate over the number of seconds that have elapsed to get the period rate. FixedPoint.Signed memory periodRate = fundingRatePerSecond.mul(SafeCast.toInt256(paymentPeriodSeconds)); // Add one to create the multiplier to scale the existing fee multiplier. FixedPoint.Signed memory signedPeriodMultiplier = ONE.add(periodRate); // Max with 0 to ensure the multiplier isn't negative, then cast to an Unsigned. FixedPoint.Unsigned memory unsignedPeriodMultiplier = FixedPoint.fromSigned(FixedPoint.max(signedPeriodMultiplier, FixedPoint.fromUnscaledInt(0))); // Multiply the existing cumulative funding rate multiplier by the computed period multiplier to get the new // cumulative funding rate multiplier. newCumulativeFundingRateMultiplier = currentCumulativeFundingRateMultiplier.mul(unsignedPeriodMultiplier); } function _getAncillaryData() internal view returns (bytes memory) { // Note: when ancillary data is passed to the optimistic oracle, it should be tagged with the token address // whose funding rate it's trying to get. return abi.encodePacked(_getTokenAddress()); } function _getTokenAddress() internal view virtual returns (address); } // 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 uint128 from uint256, reverting on * overflow (when the input is greater than largest uint128). * * Counterpart to Solidity's `uint128` operator. * * Requirements: * * - input must fit into 128 bits */ function toUint128(uint256 value) internal pure returns (uint128) { require(value < 2**128, "SafeCast: value doesn\'t fit in 128 bits"); return uint128(value); } /** * @dev Returns the downcasted uint64 from uint256, reverting on * overflow (when the input is greater than largest uint64). * * Counterpart to Solidity's `uint64` operator. * * Requirements: * * - input must fit into 64 bits */ function toUint64(uint256 value) internal pure returns (uint64) { require(value < 2**64, "SafeCast: value doesn\'t fit in 64 bits"); return uint64(value); } /** * @dev Returns the downcasted uint32 from uint256, reverting on * overflow (when the input is greater than largest uint32). * * Counterpart to Solidity's `uint32` operator. * * Requirements: * * - input must fit into 32 bits */ function toUint32(uint256 value) internal pure returns (uint32) { require(value < 2**32, "SafeCast: value doesn\'t fit in 32 bits"); return uint32(value); } /** * @dev Returns the downcasted uint16 from uint256, reverting on * overflow (when the input is greater than largest uint16). * * Counterpart to Solidity's `uint16` operator. * * Requirements: * * - input must fit into 16 bits */ function toUint16(uint256 value) internal pure returns (uint16) { require(value < 2**16, "SafeCast: value doesn\'t fit in 16 bits"); return uint16(value); } /** * @dev Returns the downcasted uint8 from uint256, reverting on * overflow (when the input is greater than largest uint8). * * Counterpart to Solidity's `uint8` operator. * * Requirements: * * - input must fit into 8 bits. */ function toUint8(uint256 value) internal pure returns (uint8) { require(value < 2**8, "SafeCast: value doesn\'t fit in 8 bits"); return uint8(value); } /** * @dev Converts a signed int256 into an unsigned uint256. * * Requirements: * * - input must be greater than or equal to 0. */ function toUint256(int256 value) internal pure returns (uint256) { require(value >= 0, "SafeCast: value must be positive"); return uint256(value); } /** * @dev 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 >= -2**127 && value < 2**127, "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 >= -2**63 && value < 2**63, "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 >= -2**31 && value < 2**31, "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 >= -2**15 && value < 2**15, "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 >= -2**7 && value < 2**7, "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) { require(value < 2**255, "SafeCast: value doesn't fit in an int256"); return int256(value); } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.8.0; pragma abicoder v2; import "@openzeppelin/contracts/utils/math/SafeMath.sol"; /** * @title EmergencyShutdownable contract. * @notice Any contract that inherits this contract will have an emergency shutdown timestamp state variable. * This contract provides modifiers that can be used by children contracts to determine if the contract is * in the shutdown state. The child contract is expected to implement the logic that happens * once a shutdown occurs. */ abstract contract EmergencyShutdownable { using SafeMath for uint256; /**************************************** * EMERGENCY SHUTDOWN DATA STRUCTURES * ****************************************/ // Timestamp used in case of emergency shutdown. 0 if no shutdown has been triggered. uint256 public emergencyShutdownTimestamp; /**************************************** * MODIFIERS * ****************************************/ modifier notEmergencyShutdown() { _notEmergencyShutdown(); _; } modifier isEmergencyShutdown() { _isEmergencyShutdown(); _; } /**************************************** * EXTERNAL FUNCTIONS * ****************************************/ constructor() { emergencyShutdownTimestamp = 0; } /**************************************** * INTERNAL FUNCTIONS * ****************************************/ function _notEmergencyShutdown() internal view { // Note: removed require string to save bytecode. require(emergencyShutdownTimestamp == 0); } function _isEmergencyShutdown() internal view { // Note: removed require string to save bytecode. require(emergencyShutdownTimestamp != 0); } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.8.0; pragma abicoder v2; import "../common/FundingRateApplier.sol"; import "../../common/implementation/FixedPoint.sol"; // Implements FundingRateApplier internal methods to enable unit testing. contract FundingRateApplierTest is FundingRateApplier { constructor( bytes32 _fundingRateIdentifier, address _collateralAddress, address _finderAddress, address _configStoreAddress, FixedPoint.Unsigned memory _tokenScaling, address _timerAddress ) FundingRateApplier( _fundingRateIdentifier, _collateralAddress, _finderAddress, _configStoreAddress, _tokenScaling, _timerAddress ) {} function calculateEffectiveFundingRate( uint256 paymentPeriodSeconds, FixedPoint.Signed memory fundingRatePerSecond, FixedPoint.Unsigned memory currentCumulativeFundingRateMultiplier ) public pure returns (FixedPoint.Unsigned memory) { return _calculateEffectiveFundingRate( paymentPeriodSeconds, fundingRatePerSecond, currentCumulativeFundingRateMultiplier ); } // Required overrides. function _pfc() internal view virtual override returns (FixedPoint.Unsigned memory currentPfc) { return FixedPoint.Unsigned(collateralCurrency.balanceOf(address(this))); } function emergencyShutdown() external override {} function remargin() external override {} function _getTokenAddress() internal view override returns (address) { return address(collateralCurrency); } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.8.0; pragma abicoder v2; import "../../common/interfaces/ExpandedIERC20.sol"; import "../../common/interfaces/IERC20Standard.sol"; import "../../oracle/implementation/ContractCreator.sol"; import "../../common/implementation/Testable.sol"; import "../../common/implementation/AddressWhitelist.sol"; import "../../common/implementation/Lockable.sol"; import "../common/TokenFactory.sol"; import "../common/SyntheticToken.sol"; import "./ExpiringMultiPartyLib.sol"; /** * @title Expiring Multi Party Contract creator. * @notice Factory contract to create and register new instances of expiring multiparty contracts. * Responsible for constraining the parameters used to construct a new EMP. This creator contains a number of constraints * that are applied to newly created expiring multi party contract. These constraints can evolve over time and are * initially constrained to conservative values in this first iteration. Technically there is nothing in the * ExpiringMultiParty contract requiring these constraints. However, because `createExpiringMultiParty()` is intended * to be the only way to create valid financial contracts that are registered with the DVM (via _registerContract), we can enforce deployment configurations here. */ contract ExpiringMultiPartyCreator is ContractCreator, Testable, Lockable { using FixedPoint for FixedPoint.Unsigned; /**************************************** * EMP CREATOR DATA STRUCTURES * ****************************************/ struct Params { uint256 expirationTimestamp; address collateralAddress; bytes32 priceFeedIdentifier; string syntheticName; string syntheticSymbol; FixedPoint.Unsigned collateralRequirement; FixedPoint.Unsigned disputeBondPercentage; FixedPoint.Unsigned sponsorDisputeRewardPercentage; FixedPoint.Unsigned disputerDisputeRewardPercentage; FixedPoint.Unsigned minSponsorTokens; uint256 withdrawalLiveness; uint256 liquidationLiveness; address financialProductLibraryAddress; } // Address of TokenFactory used to create a new synthetic token. address public tokenFactoryAddress; event CreatedExpiringMultiParty(address indexed expiringMultiPartyAddress, address indexed deployerAddress); /** * @notice Constructs the ExpiringMultiPartyCreator contract. * @param _finderAddress UMA protocol Finder used to discover other protocol contracts. * @param _tokenFactoryAddress ERC20 token factory used to deploy synthetic token instances. * @param _timerAddress Contract that stores the current time in a testing environment. */ constructor( address _finderAddress, address _tokenFactoryAddress, address _timerAddress ) ContractCreator(_finderAddress) Testable(_timerAddress) nonReentrant() { tokenFactoryAddress = _tokenFactoryAddress; } /** * @notice Creates an instance of expiring multi party and registers it within the registry. * @param params is a `ConstructorParams` object from ExpiringMultiParty. * @return address of the deployed ExpiringMultiParty contract. */ function createExpiringMultiParty(Params memory params) public nonReentrant() returns (address) { // Create a new synthetic token using the params. require(bytes(params.syntheticName).length != 0, "Missing synthetic name"); require(bytes(params.syntheticSymbol).length != 0, "Missing synthetic symbol"); TokenFactory tf = TokenFactory(tokenFactoryAddress); // If the collateral token does not have a `decimals()` method, then a default precision of 18 will be // applied to the newly created synthetic token. uint8 syntheticDecimals = _getSyntheticDecimals(params.collateralAddress); ExpandedIERC20 tokenCurrency = tf.createToken(params.syntheticName, params.syntheticSymbol, syntheticDecimals); address derivative = ExpiringMultiPartyLib.deploy(_convertParams(params, tokenCurrency)); // Give permissions to new derivative contract and then hand over ownership. tokenCurrency.addMinter(derivative); tokenCurrency.addBurner(derivative); tokenCurrency.resetOwner(derivative); _registerContract(new address[](0), derivative); emit CreatedExpiringMultiParty(derivative, msg.sender); return derivative; } /**************************************** * PRIVATE FUNCTIONS * ****************************************/ // Converts createExpiringMultiParty params to ExpiringMultiParty constructor params. function _convertParams(Params memory params, ExpandedIERC20 newTokenCurrency) private view returns (ExpiringMultiParty.ConstructorParams memory constructorParams) { // Known from creator deployment. constructorParams.finderAddress = finderAddress; constructorParams.timerAddress = timerAddress; // Enforce configuration constraints. require(params.withdrawalLiveness != 0, "Withdrawal liveness cannot be 0"); require(params.liquidationLiveness != 0, "Liquidation liveness cannot be 0"); require(params.expirationTimestamp > block.timestamp, "Invalid expiration time"); _requireWhitelistedCollateral(params.collateralAddress); // We don't want EMP deployers to be able to intentionally or unintentionally set // liveness periods that could induce arithmetic overflow, but we also don't want // to be opinionated about what livenesses are "correct", so we will somewhat // arbitrarily set the liveness upper bound to 100 years (5200 weeks). In practice, liveness // periods even greater than a few days would make the EMP unusable for most users. require(params.withdrawalLiveness < 5200 weeks, "Withdrawal liveness too large"); require(params.liquidationLiveness < 5200 weeks, "Liquidation liveness too large"); // Input from function call. constructorParams.tokenAddress = address(newTokenCurrency); constructorParams.expirationTimestamp = params.expirationTimestamp; constructorParams.collateralAddress = params.collateralAddress; constructorParams.priceFeedIdentifier = params.priceFeedIdentifier; constructorParams.collateralRequirement = params.collateralRequirement; constructorParams.disputeBondPercentage = params.disputeBondPercentage; constructorParams.sponsorDisputeRewardPercentage = params.sponsorDisputeRewardPercentage; constructorParams.disputerDisputeRewardPercentage = params.disputerDisputeRewardPercentage; constructorParams.minSponsorTokens = params.minSponsorTokens; constructorParams.withdrawalLiveness = params.withdrawalLiveness; constructorParams.liquidationLiveness = params.liquidationLiveness; constructorParams.financialProductLibraryAddress = params.financialProductLibraryAddress; } // IERC20Standard.decimals() will revert if the collateral contract has not implemented the decimals() method, // which is possible since the method is only an OPTIONAL method in the ERC20 standard: // https://eips.ethereum.org/EIPS/eip-20#methods. function _getSyntheticDecimals(address _collateralAddress) public view returns (uint8 decimals) { try IERC20Standard(_collateralAddress).decimals() returns (uint8 _decimals) { return _decimals; } catch { return 18; } } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.8.0; pragma abicoder v2; import "./ExpiringMultiParty.sol"; /** * @title Provides convenient Expiring Multi Party contract utilities. * @dev Using this library to deploy EMP's allows calling contracts to avoid importing the full EMP bytecode. */ library ExpiringMultiPartyLib { /** * @notice Returns address of new EMP deployed with given `params` configuration. * @dev Caller will need to register new EMP with the Registry to begin requesting prices. Caller is also * responsible for enforcing constraints on `params`. * @param params is a `ConstructorParams` object from ExpiringMultiParty. * @return address of the deployed ExpiringMultiParty contract */ function deploy(ExpiringMultiParty.ConstructorParams memory params) public returns (address) { ExpiringMultiParty derivative = new ExpiringMultiParty(params); return address(derivative); } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.8.0; pragma abicoder v2; import "./Liquidatable.sol"; /** * @title Expiring Multi Party. * @notice Convenient wrapper for Liquidatable. */ contract ExpiringMultiParty is Liquidatable { /** * @notice Constructs the ExpiringMultiParty contract. * @param params struct to define input parameters for construction of Liquidatable. Some params * are fed directly into the PricelessPositionManager's constructor within the inheritance tree. */ constructor(ConstructorParams memory params) Liquidatable(params) // Note: since there is no logic here, there is no need to add a re-entrancy guard. { } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.8.0; pragma abicoder v2; import "@openzeppelin/contracts/utils/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; import "@openzeppelin/contracts/utils/Address.sol"; import "./PricelessPositionManager.sol"; import "../../common/implementation/FixedPoint.sol"; /** * @title Liquidatable * @notice Adds logic to a position-managing contract that enables callers to liquidate an undercollateralized position. * @dev The liquidation has a liveness period before expiring successfully, during which someone can "dispute" the * liquidation, which sends a price request to the relevant Oracle to settle the final collateralization ratio based on * a DVM price. The contract enforces dispute rewards in order to incentivize disputers to correctly dispute false * liquidations and compensate position sponsors who had their position incorrectly liquidated. Importantly, a * prospective disputer must deposit a dispute bond that they can lose in the case of an unsuccessful dispute. * NOTE: this contract does _not_ work with ERC777 collateral currencies or any others that call into the receiver on * transfer(). Using an ERC777 token would allow a user to maliciously grief other participants (while also losing * money themselves). */ contract Liquidatable is PricelessPositionManager { using FixedPoint for FixedPoint.Unsigned; using SafeMath for uint256; using SafeERC20 for IERC20; using SafeERC20 for ExpandedIERC20; using Address for address; /**************************************** * LIQUIDATION DATA STRUCTURES * ****************************************/ // Because of the check in withdrawable(), the order of these enum values should not change. enum Status { Uninitialized, NotDisputed, Disputed, DisputeSucceeded, DisputeFailed } struct LiquidationData { // Following variables set upon creation of liquidation: address sponsor; // Address of the liquidated position's sponsor address liquidator; // Address who created this liquidation Status state; // Liquidated (and expired or not), Pending a Dispute, or Dispute has resolved uint256 liquidationTime; // Time when liquidation is initiated, needed to get price from Oracle // Following variables determined by the position that is being liquidated: FixedPoint.Unsigned tokensOutstanding; // Synthetic tokens required to be burned by liquidator to initiate dispute FixedPoint.Unsigned lockedCollateral; // Collateral locked by contract and released upon expiry or post-dispute // Amount of collateral being liquidated, which could be different from // lockedCollateral if there were pending withdrawals at the time of liquidation FixedPoint.Unsigned liquidatedCollateral; // Unit value (starts at 1) that is used to track the fees per unit of collateral over the course of the liquidation. FixedPoint.Unsigned rawUnitCollateral; // Following variable set upon initiation of a dispute: address disputer; // Person who is disputing a liquidation // Following variable set upon a resolution of a dispute: FixedPoint.Unsigned settlementPrice; // Final price as determined by an Oracle following a dispute FixedPoint.Unsigned finalFee; } // Define the contract's constructor parameters as a struct to enable more variables to be specified. // This is required to enable more params, over and above Solidity's limits. struct ConstructorParams { // Params for PricelessPositionManager only. uint256 expirationTimestamp; uint256 withdrawalLiveness; address collateralAddress; address tokenAddress; address finderAddress; address timerAddress; address financialProductLibraryAddress; bytes32 priceFeedIdentifier; FixedPoint.Unsigned minSponsorTokens; // Params specifically for Liquidatable. uint256 liquidationLiveness; FixedPoint.Unsigned collateralRequirement; FixedPoint.Unsigned disputeBondPercentage; FixedPoint.Unsigned sponsorDisputeRewardPercentage; FixedPoint.Unsigned disputerDisputeRewardPercentage; } // This struct is used in the `withdrawLiquidation` method that disperses liquidation and dispute rewards. // `payToX` stores the total collateral to withdraw from the contract to pay X. This value might differ // from `paidToX` due to precision loss between accounting for the `rawCollateral` versus the // fee-adjusted collateral. These variables are stored within a struct to avoid the stack too deep error. struct RewardsData { FixedPoint.Unsigned payToSponsor; FixedPoint.Unsigned payToLiquidator; FixedPoint.Unsigned payToDisputer; FixedPoint.Unsigned paidToSponsor; FixedPoint.Unsigned paidToLiquidator; FixedPoint.Unsigned paidToDisputer; } // Liquidations are unique by ID per sponsor mapping(address => LiquidationData[]) public liquidations; // Total collateral in liquidation. FixedPoint.Unsigned public rawLiquidationCollateral; // Immutable contract parameters: // Amount of time for pending liquidation before expiry. // !!Note: The lower the liquidation liveness value, the more risk incurred by sponsors. // Extremely low liveness values increase the chance that opportunistic invalid liquidations // expire without dispute, thereby decreasing the usability for sponsors and increasing the risk // for the contract as a whole. An insolvent contract is extremely risky for any sponsor or synthetic // token holder for the contract. uint256 public liquidationLiveness; // Required collateral:TRV ratio for a position to be considered sufficiently collateralized. FixedPoint.Unsigned public collateralRequirement; // Percent of a Liquidation/Position's lockedCollateral to be deposited by a potential disputer // Represented as a multiplier, for example 1.5e18 = "150%" and 0.05e18 = "5%" FixedPoint.Unsigned public disputeBondPercentage; // Percent of oraclePrice paid to sponsor in the Disputed state (i.e. following a successful dispute) // Represented as a multiplier, see above. FixedPoint.Unsigned public sponsorDisputeRewardPercentage; // Percent of oraclePrice paid to disputer in the Disputed state (i.e. following a successful dispute) // Represented as a multiplier, see above. FixedPoint.Unsigned public disputerDisputeRewardPercentage; /**************************************** * EVENTS * ****************************************/ event LiquidationCreated( address indexed sponsor, address indexed liquidator, uint256 indexed liquidationId, uint256 tokensOutstanding, uint256 lockedCollateral, uint256 liquidatedCollateral, uint256 liquidationTime ); event LiquidationDisputed( address indexed sponsor, address indexed liquidator, address indexed disputer, uint256 liquidationId, uint256 disputeBondAmount ); event DisputeSettled( address indexed caller, address indexed sponsor, address indexed liquidator, address disputer, uint256 liquidationId, bool disputeSucceeded ); event LiquidationWithdrawn( address indexed caller, uint256 paidToLiquidator, uint256 paidToDisputer, uint256 paidToSponsor, Status indexed liquidationStatus, uint256 settlementPrice ); /**************************************** * MODIFIERS * ****************************************/ modifier disputable(uint256 liquidationId, address sponsor) { _disputable(liquidationId, sponsor); _; } modifier withdrawable(uint256 liquidationId, address sponsor) { _withdrawable(liquidationId, sponsor); _; } /** * @notice Constructs the liquidatable contract. * @param params struct to define input parameters for construction of Liquidatable. Some params * are fed directly into the PricelessPositionManager's constructor within the inheritance tree. */ constructor(ConstructorParams memory params) PricelessPositionManager( params.expirationTimestamp, params.withdrawalLiveness, params.collateralAddress, params.tokenAddress, params.finderAddress, params.priceFeedIdentifier, params.minSponsorTokens, params.timerAddress, params.financialProductLibraryAddress ) nonReentrant() { require(params.collateralRequirement.isGreaterThan(1)); require(params.sponsorDisputeRewardPercentage.add(params.disputerDisputeRewardPercentage).isLessThan(1)); // Set liquidatable specific variables. liquidationLiveness = params.liquidationLiveness; collateralRequirement = params.collateralRequirement; disputeBondPercentage = params.disputeBondPercentage; sponsorDisputeRewardPercentage = params.sponsorDisputeRewardPercentage; disputerDisputeRewardPercentage = params.disputerDisputeRewardPercentage; } /**************************************** * LIQUIDATION FUNCTIONS * ****************************************/ /** * @notice Liquidates the sponsor's position if the caller has enough * synthetic tokens to retire the position's outstanding tokens. Liquidations above * a minimum size also reset an ongoing "slow withdrawal"'s liveness. * @dev This method generates an ID that will uniquely identify liquidation for the sponsor. This contract must be * approved to spend at least `tokensLiquidated` of `tokenCurrency` and at least `finalFeeBond` of `collateralCurrency`. * @dev This contract must have the Burner role for the `tokenCurrency`. * @param sponsor address of the sponsor to liquidate. * @param minCollateralPerToken abort the liquidation if the position's collateral per token is below this value. * @param maxCollateralPerToken abort the liquidation if the position's collateral per token exceeds this value. * @param maxTokensToLiquidate max number of tokens to liquidate. * @param deadline abort the liquidation if the transaction is mined after this timestamp. * @return liquidationId ID of the newly created liquidation. * @return tokensLiquidated amount of synthetic tokens removed and liquidated from the `sponsor`'s position. * @return finalFeeBond amount of collateral to be posted by liquidator and returned if not disputed successfully. */ function createLiquidation( address sponsor, FixedPoint.Unsigned calldata minCollateralPerToken, FixedPoint.Unsigned calldata maxCollateralPerToken, FixedPoint.Unsigned calldata maxTokensToLiquidate, uint256 deadline ) external fees() onlyPreExpiration() nonReentrant() returns ( uint256 liquidationId, FixedPoint.Unsigned memory tokensLiquidated, FixedPoint.Unsigned memory finalFeeBond ) { // Check that this transaction was mined pre-deadline. require(getCurrentTime() <= deadline, "Mined after deadline"); // Retrieve Position data for sponsor PositionData storage positionToLiquidate = _getPositionData(sponsor); tokensLiquidated = FixedPoint.min(maxTokensToLiquidate, positionToLiquidate.tokensOutstanding); require(tokensLiquidated.isGreaterThan(0)); // Starting values for the Position being liquidated. If withdrawal request amount is > position's collateral, // then set this to 0, otherwise set it to (startCollateral - withdrawal request amount). FixedPoint.Unsigned memory startCollateral = _getFeeAdjustedCollateral(positionToLiquidate.rawCollateral); FixedPoint.Unsigned memory startCollateralNetOfWithdrawal = FixedPoint.fromUnscaledUint(0); if (positionToLiquidate.withdrawalRequestAmount.isLessThanOrEqual(startCollateral)) { startCollateralNetOfWithdrawal = startCollateral.sub(positionToLiquidate.withdrawalRequestAmount); } // Scoping to get rid of a stack too deep error. { FixedPoint.Unsigned memory startTokens = positionToLiquidate.tokensOutstanding; // The Position's collateralization ratio must be between [minCollateralPerToken, maxCollateralPerToken]. // maxCollateralPerToken >= startCollateralNetOfWithdrawal / startTokens. require( maxCollateralPerToken.mul(startTokens).isGreaterThanOrEqual(startCollateralNetOfWithdrawal), "CR is more than max liq. price" ); // minCollateralPerToken >= startCollateralNetOfWithdrawal / startTokens. require( minCollateralPerToken.mul(startTokens).isLessThanOrEqual(startCollateralNetOfWithdrawal), "CR is less than min liq. price" ); } // Compute final fee at time of liquidation. finalFeeBond = _computeFinalFees(); // These will be populated within the scope below. FixedPoint.Unsigned memory lockedCollateral; FixedPoint.Unsigned memory liquidatedCollateral; // Scoping to get rid of a stack too deep error. { FixedPoint.Unsigned memory ratio = tokensLiquidated.div(positionToLiquidate.tokensOutstanding); // The actual amount of collateral that gets moved to the liquidation. lockedCollateral = startCollateral.mul(ratio); // For purposes of disputes, it's actually this liquidatedCollateral value that's used. This value is net of // withdrawal requests. liquidatedCollateral = startCollateralNetOfWithdrawal.mul(ratio); // Part of the withdrawal request is also removed. Ideally: // liquidatedCollateral + withdrawalAmountToRemove = lockedCollateral. FixedPoint.Unsigned memory withdrawalAmountToRemove = positionToLiquidate.withdrawalRequestAmount.mul(ratio); _reduceSponsorPosition(sponsor, tokensLiquidated, lockedCollateral, withdrawalAmountToRemove); } // Add to the global liquidation collateral count. _addCollateral(rawLiquidationCollateral, lockedCollateral.add(finalFeeBond)); // Construct liquidation object. // Note: All dispute-related values are zeroed out until a dispute occurs. liquidationId is the index of the new // LiquidationData that is pushed into the array, which is equal to the current length of the array pre-push. liquidationId = liquidations[sponsor].length; liquidations[sponsor].push( LiquidationData({ sponsor: sponsor, liquidator: msg.sender, state: Status.NotDisputed, liquidationTime: getCurrentTime(), tokensOutstanding: tokensLiquidated, lockedCollateral: lockedCollateral, liquidatedCollateral: liquidatedCollateral, rawUnitCollateral: _convertToRawCollateral(FixedPoint.fromUnscaledUint(1)), disputer: address(0), settlementPrice: FixedPoint.fromUnscaledUint(0), finalFee: finalFeeBond }) ); // If this liquidation is a subsequent liquidation on the position, and the liquidation size is larger than // some "griefing threshold", then re-set the liveness. This enables a liquidation against a withdraw request to be // "dragged out" if the position is very large and liquidators need time to gather funds. The griefing threshold // is enforced so that liquidations for trivially small # of tokens cannot drag out an honest sponsor's slow withdrawal. // We arbitrarily set the "griefing threshold" to `minSponsorTokens` because it is the only parameter // denominated in token currency units and we can avoid adding another parameter. FixedPoint.Unsigned memory griefingThreshold = minSponsorTokens; if ( positionToLiquidate.withdrawalRequestPassTimestamp > 0 && // The position is undergoing a slow withdrawal. positionToLiquidate.withdrawalRequestPassTimestamp > getCurrentTime() && // The slow withdrawal has not yet expired. tokensLiquidated.isGreaterThanOrEqual(griefingThreshold) // The liquidated token count is above a "griefing threshold". ) { positionToLiquidate.withdrawalRequestPassTimestamp = getCurrentTime().add(withdrawalLiveness); } emit LiquidationCreated( sponsor, msg.sender, liquidationId, tokensLiquidated.rawValue, lockedCollateral.rawValue, liquidatedCollateral.rawValue, getCurrentTime() ); // Destroy tokens tokenCurrency.safeTransferFrom(msg.sender, address(this), tokensLiquidated.rawValue); tokenCurrency.burn(tokensLiquidated.rawValue); // Pull final fee from liquidator. collateralCurrency.safeTransferFrom(msg.sender, address(this), finalFeeBond.rawValue); } /** * @notice Disputes a liquidation, if the caller has enough collateral to post a dispute bond * and pay a fixed final fee charged on each price request. * @dev Can only dispute a liquidation before the liquidation expires and if there are no other pending disputes. * This contract must be approved to spend at least the dispute bond amount of `collateralCurrency`. This dispute * bond amount is calculated from `disputeBondPercentage` times the collateral in the liquidation. * @param liquidationId of the disputed liquidation. * @param sponsor the address of the sponsor whose liquidation is being disputed. * @return totalPaid amount of collateral charged to disputer (i.e. final fee bond + dispute bond). */ function dispute(uint256 liquidationId, address sponsor) external disputable(liquidationId, sponsor) fees() nonReentrant() returns (FixedPoint.Unsigned memory totalPaid) { LiquidationData storage disputedLiquidation = _getLiquidationData(sponsor, liquidationId); // Multiply by the unit collateral so the dispute bond is a percentage of the locked collateral after fees. FixedPoint.Unsigned memory disputeBondAmount = disputedLiquidation.lockedCollateral.mul(disputeBondPercentage).mul( _getFeeAdjustedCollateral(disputedLiquidation.rawUnitCollateral) ); _addCollateral(rawLiquidationCollateral, disputeBondAmount); // Request a price from DVM. Liquidation is pending dispute until DVM returns a price. disputedLiquidation.state = Status.Disputed; disputedLiquidation.disputer = msg.sender; // Enqueue a request with the DVM. _requestOraclePriceLiquidation(disputedLiquidation.liquidationTime); emit LiquidationDisputed( sponsor, disputedLiquidation.liquidator, msg.sender, liquidationId, disputeBondAmount.rawValue ); totalPaid = disputeBondAmount.add(disputedLiquidation.finalFee); // Pay the final fee for requesting price from the DVM. _payFinalFees(msg.sender, disputedLiquidation.finalFee); // Transfer the dispute bond amount from the caller to this contract. collateralCurrency.safeTransferFrom(msg.sender, address(this), disputeBondAmount.rawValue); } /** * @notice After a dispute has settled or after a non-disputed liquidation has expired, * anyone can call this method to disperse payments to the sponsor, liquidator, and disdputer. * @dev If the dispute SUCCEEDED: the sponsor, liquidator, and disputer are eligible for payment. * If the dispute FAILED: only the liquidator can receive payment. * This method will revert if rewards have already been dispersed. * @param liquidationId uniquely identifies the sponsor's liquidation. * @param sponsor address of the sponsor associated with the liquidation. * @return data about rewards paid out. */ function withdrawLiquidation(uint256 liquidationId, address sponsor) public withdrawable(liquidationId, sponsor) fees() nonReentrant() returns (RewardsData memory) { LiquidationData storage liquidation = _getLiquidationData(sponsor, liquidationId); // Settles the liquidation if necessary. This call will revert if the price has not resolved yet. _settle(liquidationId, sponsor); // Calculate rewards as a function of the TRV. // Note: all payouts are scaled by the unit collateral value so all payouts are charged the fees pro rata. FixedPoint.Unsigned memory feeAttenuation = _getFeeAdjustedCollateral(liquidation.rawUnitCollateral); FixedPoint.Unsigned memory settlementPrice = liquidation.settlementPrice; FixedPoint.Unsigned memory tokenRedemptionValue = liquidation.tokensOutstanding.mul(settlementPrice).mul(feeAttenuation); FixedPoint.Unsigned memory collateral = liquidation.lockedCollateral.mul(feeAttenuation); FixedPoint.Unsigned memory disputerDisputeReward = disputerDisputeRewardPercentage.mul(tokenRedemptionValue); FixedPoint.Unsigned memory sponsorDisputeReward = sponsorDisputeRewardPercentage.mul(tokenRedemptionValue); FixedPoint.Unsigned memory disputeBondAmount = collateral.mul(disputeBondPercentage); FixedPoint.Unsigned memory finalFee = liquidation.finalFee.mul(feeAttenuation); // There are three main outcome states: either the dispute succeeded, failed or was not updated. // Based on the state, different parties of a liquidation receive different amounts. // After assigning rewards based on the liquidation status, decrease the total collateral held in this contract // by the amount to pay each party. The actual amounts withdrawn might differ if _removeCollateral causes // precision loss. RewardsData memory rewards; if (liquidation.state == Status.DisputeSucceeded) { // If the dispute is successful then all three users should receive rewards: // Pay DISPUTER: disputer reward + dispute bond + returned final fee rewards.payToDisputer = disputerDisputeReward.add(disputeBondAmount).add(finalFee); // Pay SPONSOR: remaining collateral (collateral - TRV) + sponsor reward rewards.payToSponsor = sponsorDisputeReward.add(collateral.sub(tokenRedemptionValue)); // Pay LIQUIDATOR: TRV - dispute reward - sponsor reward // If TRV > Collateral, then subtract rewards from collateral // NOTE: `payToLiquidator` should never be below zero since we enforce that // (sponsorDisputePct+disputerDisputePct) <= 1 in the constructor when these params are set. rewards.payToLiquidator = tokenRedemptionValue.sub(sponsorDisputeReward).sub(disputerDisputeReward); // Transfer rewards and debit collateral rewards.paidToLiquidator = _removeCollateral(rawLiquidationCollateral, rewards.payToLiquidator); rewards.paidToSponsor = _removeCollateral(rawLiquidationCollateral, rewards.payToSponsor); rewards.paidToDisputer = _removeCollateral(rawLiquidationCollateral, rewards.payToDisputer); collateralCurrency.safeTransfer(liquidation.disputer, rewards.paidToDisputer.rawValue); collateralCurrency.safeTransfer(liquidation.liquidator, rewards.paidToLiquidator.rawValue); collateralCurrency.safeTransfer(liquidation.sponsor, rewards.paidToSponsor.rawValue); // In the case of a failed dispute only the liquidator can withdraw. } else if (liquidation.state == Status.DisputeFailed) { // Pay LIQUIDATOR: collateral + dispute bond + returned final fee rewards.payToLiquidator = collateral.add(disputeBondAmount).add(finalFee); // Transfer rewards and debit collateral rewards.paidToLiquidator = _removeCollateral(rawLiquidationCollateral, rewards.payToLiquidator); collateralCurrency.safeTransfer(liquidation.liquidator, rewards.paidToLiquidator.rawValue); // If the state is pre-dispute but time has passed liveness then there was no dispute. We represent this // state as a dispute failed and the liquidator can withdraw. } else if (liquidation.state == Status.NotDisputed) { // Pay LIQUIDATOR: collateral + returned final fee rewards.payToLiquidator = collateral.add(finalFee); // Transfer rewards and debit collateral rewards.paidToLiquidator = _removeCollateral(rawLiquidationCollateral, rewards.payToLiquidator); collateralCurrency.safeTransfer(liquidation.liquidator, rewards.paidToLiquidator.rawValue); } emit LiquidationWithdrawn( msg.sender, rewards.paidToLiquidator.rawValue, rewards.paidToDisputer.rawValue, rewards.paidToSponsor.rawValue, liquidation.state, settlementPrice.rawValue ); // Free up space after collateral is withdrawn by removing the liquidation object from the array. delete liquidations[sponsor][liquidationId]; return rewards; } /** * @notice Gets all liquidation information for a given sponsor address. * @param sponsor address of the position sponsor. * @return liquidationData array of all liquidation information for the given sponsor address. */ function getLiquidations(address sponsor) external view nonReentrantView() returns (LiquidationData[] memory liquidationData) { return liquidations[sponsor]; } /** * @notice Accessor method to calculate a transformed collateral requirement using the finanical product library specified during contract deployment. If no library was provided then no modification to the collateral requirement is done. * @param price input price used as an input to transform the collateral requirement. * @return transformedCollateralRequirement collateral requirement with transformation applied to it. * @dev This method should never revert. */ function transformCollateralRequirement(FixedPoint.Unsigned memory price) public view nonReentrantView() returns (FixedPoint.Unsigned memory) { return _transformCollateralRequirement(price); } /**************************************** * INTERNAL FUNCTIONS * ****************************************/ // This settles a liquidation if it is in the Disputed state. If not, it will immediately return. // If the liquidation is in the Disputed state, but a price is not available, this will revert. function _settle(uint256 liquidationId, address sponsor) internal { LiquidationData storage liquidation = _getLiquidationData(sponsor, liquidationId); // Settlement only happens when state == Disputed and will only happen once per liquidation. // If this liquidation is not ready to be settled, this method should return immediately. if (liquidation.state != Status.Disputed) { return; } // Get the returned price from the oracle. If this has not yet resolved will revert. liquidation.settlementPrice = _getOraclePriceLiquidation(liquidation.liquidationTime); // Find the value of the tokens in the underlying collateral. FixedPoint.Unsigned memory tokenRedemptionValue = liquidation.tokensOutstanding.mul(liquidation.settlementPrice); // The required collateral is the value of the tokens in underlying * required collateral ratio. The Transform // Collateral requirement method applies a from the financial Product library to change the scaled the collateral // requirement based on the settlement price. If no library was specified when deploying the emp then this makes no change. FixedPoint.Unsigned memory requiredCollateral = tokenRedemptionValue.mul(_transformCollateralRequirement(liquidation.settlementPrice)); // If the position has more than the required collateral it is solvent and the dispute is valid(liquidation is invalid) // Note that this check uses the liquidatedCollateral not the lockedCollateral as this considers withdrawals. bool disputeSucceeded = liquidation.liquidatedCollateral.isGreaterThanOrEqual(requiredCollateral); liquidation.state = disputeSucceeded ? Status.DisputeSucceeded : Status.DisputeFailed; emit DisputeSettled( msg.sender, sponsor, liquidation.liquidator, liquidation.disputer, liquidationId, disputeSucceeded ); } function _pfc() internal view override returns (FixedPoint.Unsigned memory) { return super._pfc().add(_getFeeAdjustedCollateral(rawLiquidationCollateral)); } function _getLiquidationData(address sponsor, uint256 liquidationId) internal view returns (LiquidationData storage liquidation) { LiquidationData[] storage liquidationArray = liquidations[sponsor]; // Revert if the caller is attempting to access an invalid liquidation // (one that has never been created or one has never been initialized). require( liquidationId < liquidationArray.length && liquidationArray[liquidationId].state != Status.Uninitialized, "Invalid liquidation ID" ); return liquidationArray[liquidationId]; } function _getLiquidationExpiry(LiquidationData storage liquidation) internal view returns (uint256) { return liquidation.liquidationTime.add(liquidationLiveness); } // These internal functions are supposed to act identically to modifiers, but re-used modifiers // unnecessarily increase contract bytecode size. // source: https://blog.polymath.network/solidity-tips-and-tricks-to-save-gas-and-reduce-bytecode-size-c44580b218e6 function _disputable(uint256 liquidationId, address sponsor) internal view { LiquidationData storage liquidation = _getLiquidationData(sponsor, liquidationId); require( (getCurrentTime() < _getLiquidationExpiry(liquidation)) && (liquidation.state == Status.NotDisputed), "Liquidation not disputable" ); } function _withdrawable(uint256 liquidationId, address sponsor) internal view { LiquidationData storage liquidation = _getLiquidationData(sponsor, liquidationId); Status state = liquidation.state; // Must be disputed or the liquidation has passed expiry. require( (state > Status.NotDisputed) || ((_getLiquidationExpiry(liquidation) <= getCurrentTime()) && (state == Status.NotDisputed)), "Liquidation not withdrawable" ); } function _transformCollateralRequirement(FixedPoint.Unsigned memory price) internal view returns (FixedPoint.Unsigned memory) { if (!address(financialProductLibrary).isContract()) return collateralRequirement; try financialProductLibrary.transformCollateralRequirement(price, collateralRequirement) returns ( FixedPoint.Unsigned memory transformedCollateralRequirement ) { return transformedCollateralRequirement; } catch { return collateralRequirement; } } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.8.0; pragma abicoder v2; import "@openzeppelin/contracts/utils/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; import "../common/FeePayer.sol"; import "../../common/implementation/FixedPoint.sol"; import "../../oracle/interfaces/IdentifierWhitelistInterface.sol"; import "../../oracle/interfaces/OracleInterface.sol"; import "../../oracle/implementation/ContractCreator.sol"; /** * @title Token Deposit Box * @notice This is a minimal example of a financial template that depends on price requests from the DVM. * This contract should be thought of as a "Deposit Box" into which the user deposits some ERC20 collateral. * The main feature of this box is that the user can withdraw their ERC20 corresponding to a desired USD amount. * When the user wants to make a withdrawal, a price request is enqueued with the UMA DVM. * For simplicty, the user is constrained to have one outstanding withdrawal request at any given time. * Regular fees are charged on the collateral in the deposit box throughout the lifetime of the deposit box, * and final fees are charged on each price request. * * This example is intended to accompany a technical tutorial for how to integrate the DVM into a project. * The main feature this demo serves to showcase is how to build a financial product on-chain that "pulls" price * requests from the DVM on-demand, which is an implementation of the "priceless" oracle framework. * * The typical user flow would be: * - User sets up a deposit box for the (wETH - USD) price-identifier. The "collateral currency" in this deposit * box is therefore wETH. * The user can subsequently make withdrawal requests for USD-denominated amounts of wETH. * - User deposits 10 wETH into their deposit box. * - User later requests to withdraw $100 USD of wETH. * - DepositBox asks DVM for latest wETH/USD exchange rate. * - DVM resolves the exchange rate at: 1 wETH is worth 200 USD. * - DepositBox transfers 0.5 wETH to user. */ contract DepositBox is FeePayer, ContractCreator { using SafeMath for uint256; using FixedPoint for FixedPoint.Unsigned; using SafeERC20 for IERC20; // Represents a single caller's deposit box. All collateral is held by this contract. struct DepositBoxData { // Requested amount of collateral, denominated in quote asset of the price identifier. // Example: If the price identifier is wETH-USD, and the `withdrawalRequestAmount = 100`, then // this represents a withdrawal request for 100 USD worth of wETH. FixedPoint.Unsigned withdrawalRequestAmount; // Timestamp of the latest withdrawal request. A withdrawal request is pending if `requestPassTimestamp != 0`. uint256 requestPassTimestamp; // Raw collateral value. This value should never be accessed directly -- always use _getFeeAdjustedCollateral(). // To add or remove collateral, use _addCollateral() and _removeCollateral(). FixedPoint.Unsigned rawCollateral; } // Maps addresses to their deposit boxes. Each address can have only one position. mapping(address => DepositBoxData) private depositBoxes; // Unique identifier for DVM price feed ticker. bytes32 private priceIdentifier; // Similar to the rawCollateral in DepositBoxData, this value should not be used directly. // _getFeeAdjustedCollateral(), _addCollateral() and _removeCollateral() must be used to access and adjust. FixedPoint.Unsigned private rawTotalDepositBoxCollateral; // This blocks every public state-modifying method until it flips to true, via the `initialize()` method. bool private initialized; /**************************************** * EVENTS * ****************************************/ event NewDepositBox(address indexed user); event EndedDepositBox(address indexed user); event Deposit(address indexed user, uint256 indexed collateralAmount); event RequestWithdrawal(address indexed user, uint256 indexed collateralAmount, uint256 requestPassTimestamp); event RequestWithdrawalExecuted( address indexed user, uint256 indexed collateralAmount, uint256 exchangeRate, uint256 requestPassTimestamp ); event RequestWithdrawalCanceled( address indexed user, uint256 indexed collateralAmount, uint256 requestPassTimestamp ); /**************************************** * MODIFIERS * ****************************************/ modifier noPendingWithdrawal(address user) { _depositBoxHasNoPendingWithdrawal(user); _; } modifier isInitialized() { _isInitialized(); _; } /**************************************** * PUBLIC FUNCTIONS * ****************************************/ /** * @notice Construct the DepositBox. * @param _collateralAddress ERC20 token to be deposited. * @param _finderAddress UMA protocol Finder used to discover other protocol contracts. * @param _priceIdentifier registered in the DVM, used to price the ERC20 deposited. * The price identifier consists of a "base" asset and a "quote" asset. The "base" asset corresponds to the collateral ERC20 * currency deposited into this account, and it is denominated in the "quote" asset on withdrawals. * An example price identifier would be "ETH-USD" which will resolve and return the USD price of ETH. * @param _timerAddress Contract that stores the current time in a testing environment. * Must be set to 0x0 for production environments that use live time. */ constructor( address _collateralAddress, address _finderAddress, bytes32 _priceIdentifier, address _timerAddress ) ContractCreator(_finderAddress) FeePayer(_collateralAddress, _finderAddress, _timerAddress) nonReentrant() { require(_getIdentifierWhitelist().isIdentifierSupported(_priceIdentifier), "Unsupported price identifier"); priceIdentifier = _priceIdentifier; } /** * @notice This should be called after construction of the DepositBox and handles registration with the Registry, which is required * to make price requests in production environments. * @dev This contract must hold the `ContractCreator` role with the Registry in order to register itself as a financial-template with the DVM. * Note that `_registerContract` cannot be called from the constructor because this contract first needs to be given the `ContractCreator` role * in order to register with the `Registry`. But, its address is not known until after deployment. */ function initialize() public nonReentrant() { initialized = true; _registerContract(new address[](0), address(this)); } /** * @notice Transfers `collateralAmount` of `collateralCurrency` into caller's deposit box. * @dev This contract must be approved to spend at least `collateralAmount` of `collateralCurrency`. * @param collateralAmount total amount of collateral tokens to be sent to the sponsor's position. */ function deposit(FixedPoint.Unsigned memory collateralAmount) public isInitialized() fees() nonReentrant() { require(collateralAmount.isGreaterThan(0), "Invalid collateral amount"); DepositBoxData storage depositBoxData = depositBoxes[msg.sender]; if (_getFeeAdjustedCollateral(depositBoxData.rawCollateral).isEqual(0)) { emit NewDepositBox(msg.sender); } // Increase the individual deposit box and global collateral balance by collateral amount. _incrementCollateralBalances(depositBoxData, collateralAmount); emit Deposit(msg.sender, collateralAmount.rawValue); // Move collateral currency from sender to contract. collateralCurrency.safeTransferFrom(msg.sender, address(this), collateralAmount.rawValue); } /** * @notice Starts a withdrawal request that allows the sponsor to withdraw `denominatedCollateralAmount` * from their position denominated in the quote asset of the price identifier, following a DVM price resolution. * @dev The request will be pending for the duration of the DVM vote and can be cancelled at any time. * Only one withdrawal request can exist for the user. * @param denominatedCollateralAmount the quote-asset denominated amount of collateral requested to withdraw. */ function requestWithdrawal(FixedPoint.Unsigned memory denominatedCollateralAmount) public isInitialized() noPendingWithdrawal(msg.sender) nonReentrant() { DepositBoxData storage depositBoxData = depositBoxes[msg.sender]; require(denominatedCollateralAmount.isGreaterThan(0), "Invalid collateral amount"); // Update the position object for the user. depositBoxData.withdrawalRequestAmount = denominatedCollateralAmount; depositBoxData.requestPassTimestamp = getCurrentTime(); emit RequestWithdrawal(msg.sender, denominatedCollateralAmount.rawValue, depositBoxData.requestPassTimestamp); // Every price request costs a fixed fee. Check that this user has enough deposited to cover the final fee. FixedPoint.Unsigned memory finalFee = _computeFinalFees(); require( _getFeeAdjustedCollateral(depositBoxData.rawCollateral).isGreaterThanOrEqual(finalFee), "Cannot pay final fee" ); _payFinalFees(address(this), finalFee); // A price request is sent for the current timestamp. _requestOraclePrice(depositBoxData.requestPassTimestamp); } /** * @notice After a passed withdrawal request (i.e., by a call to `requestWithdrawal` and subsequent DVM price resolution), * withdraws `depositBoxData.withdrawalRequestAmount` of collateral currency denominated in the quote asset. * @dev Might not withdraw the full requested amount in order to account for precision loss or if the full requested * amount exceeds the collateral in the position (due to paying fees). * @return amountWithdrawn The actual amount of collateral withdrawn. */ function executeWithdrawal() external isInitialized() fees() nonReentrant() returns (FixedPoint.Unsigned memory amountWithdrawn) { DepositBoxData storage depositBoxData = depositBoxes[msg.sender]; require( depositBoxData.requestPassTimestamp != 0 && depositBoxData.requestPassTimestamp <= getCurrentTime(), "Invalid withdraw request" ); // Get the resolved price or revert. FixedPoint.Unsigned memory exchangeRate = _getOraclePrice(depositBoxData.requestPassTimestamp); // Calculate denomated amount of collateral based on resolved exchange rate. // Example 1: User wants to withdraw $100 of ETH, exchange rate is $200/ETH, therefore user to receive 0.5 ETH. // Example 2: User wants to withdraw $250 of ETH, exchange rate is $200/ETH, therefore user to receive 1.25 ETH. FixedPoint.Unsigned memory denominatedAmountToWithdraw = depositBoxData.withdrawalRequestAmount.div(exchangeRate); // If withdrawal request amount is > collateral, then withdraw the full collateral amount and delete the deposit box data. if (denominatedAmountToWithdraw.isGreaterThan(_getFeeAdjustedCollateral(depositBoxData.rawCollateral))) { denominatedAmountToWithdraw = _getFeeAdjustedCollateral(depositBoxData.rawCollateral); // Reset the position state as all the value has been removed after settlement. emit EndedDepositBox(msg.sender); } // Decrease the individual deposit box and global collateral balance. amountWithdrawn = _decrementCollateralBalances(depositBoxData, denominatedAmountToWithdraw); emit RequestWithdrawalExecuted( msg.sender, amountWithdrawn.rawValue, exchangeRate.rawValue, depositBoxData.requestPassTimestamp ); // Reset withdrawal request by setting withdrawal request timestamp to 0. _resetWithdrawalRequest(depositBoxData); // Transfer approved withdrawal amount from the contract to the caller. collateralCurrency.safeTransfer(msg.sender, amountWithdrawn.rawValue); } /** * @notice Cancels a pending withdrawal request. */ function cancelWithdrawal() external isInitialized() nonReentrant() { DepositBoxData storage depositBoxData = depositBoxes[msg.sender]; require(depositBoxData.requestPassTimestamp != 0, "No pending withdrawal"); emit RequestWithdrawalCanceled( msg.sender, depositBoxData.withdrawalRequestAmount.rawValue, depositBoxData.requestPassTimestamp ); // Reset withdrawal request by setting withdrawal request timestamp to 0. _resetWithdrawalRequest(depositBoxData); } /** * @notice `emergencyShutdown` and `remargin` are required to be implemented by all financial contracts and exposed to the DVM, but * because this is a minimal demo they will simply exit silently. */ function emergencyShutdown() external override isInitialized() nonReentrant() { return; } /** * @notice Same comment as `emergencyShutdown`. For the sake of simplicity, this will simply exit silently. */ function remargin() external override isInitialized() nonReentrant() { return; } /** * @notice Accessor method for a user's collateral. * @dev This is necessary because the struct returned by the depositBoxes() method shows * rawCollateral, which isn't a user-readable value. * @param user address whose collateral amount is retrieved. * @return the fee-adjusted collateral amount in the deposit box (i.e. available for withdrawal). */ function getCollateral(address user) external view nonReentrantView() returns (FixedPoint.Unsigned memory) { return _getFeeAdjustedCollateral(depositBoxes[user].rawCollateral); } /** * @notice Accessor method for the total collateral stored within the entire contract. * @return the total fee-adjusted collateral amount in the contract (i.e. across all users). */ function totalDepositBoxCollateral() external view nonReentrantView() returns (FixedPoint.Unsigned memory) { return _getFeeAdjustedCollateral(rawTotalDepositBoxCollateral); } /**************************************** * INTERNAL FUNCTIONS * ****************************************/ // Requests a price for `priceIdentifier` at `requestedTime` from the Oracle. function _requestOraclePrice(uint256 requestedTime) internal { OracleInterface oracle = _getOracle(); oracle.requestPrice(priceIdentifier, requestedTime); } // Ensure individual and global consistency when increasing collateral balances. Returns the change to the position. function _incrementCollateralBalances( DepositBoxData storage depositBoxData, FixedPoint.Unsigned memory collateralAmount ) internal returns (FixedPoint.Unsigned memory) { _addCollateral(depositBoxData.rawCollateral, collateralAmount); return _addCollateral(rawTotalDepositBoxCollateral, collateralAmount); } // Ensure individual and global consistency when decrementing collateral balances. Returns the change to the // position. We elect to return the amount that the global collateral is decreased by, rather than the individual // position's collateral, because we need to maintain the invariant that the global collateral is always // <= the collateral owned by the contract to avoid reverts on withdrawals. The amount returned = amount withdrawn. function _decrementCollateralBalances( DepositBoxData storage depositBoxData, FixedPoint.Unsigned memory collateralAmount ) internal returns (FixedPoint.Unsigned memory) { _removeCollateral(depositBoxData.rawCollateral, collateralAmount); return _removeCollateral(rawTotalDepositBoxCollateral, collateralAmount); } function _resetWithdrawalRequest(DepositBoxData storage depositBoxData) internal { depositBoxData.withdrawalRequestAmount = FixedPoint.fromUnscaledUint(0); depositBoxData.requestPassTimestamp = 0; } function _depositBoxHasNoPendingWithdrawal(address user) internal view { require(depositBoxes[user].requestPassTimestamp == 0, "Pending withdrawal"); } function _isInitialized() internal view { require(initialized, "Uninitialized contract"); } function _getIdentifierWhitelist() internal view returns (IdentifierWhitelistInterface) { return IdentifierWhitelistInterface(finder.getImplementationAddress(OracleInterfaces.IdentifierWhitelist)); } function _getOracle() internal view returns (OracleInterface) { return OracleInterface(finder.getImplementationAddress(OracleInterfaces.Oracle)); } // Fetches a resolved Oracle price from the Oracle. Reverts if the Oracle hasn't resolved for this request. function _getOraclePrice(uint256 requestedTime) internal view returns (FixedPoint.Unsigned memory) { OracleInterface oracle = _getOracle(); require(oracle.hasPrice(priceIdentifier, requestedTime), "Unresolved oracle price"); int256 oraclePrice = oracle.getPrice(priceIdentifier, requestedTime); // For simplicity we don't want to deal with negative prices. if (oraclePrice < 0) { oraclePrice = 0; } return FixedPoint.Unsigned(uint256(oraclePrice)); } // `_pfc()` is inherited from FeePayer and must be implemented to return the available pool of collateral from // which fees can be charged. For this contract, the available fee pool is simply all of the collateral locked up in the // contract. function _pfc() internal view virtual override returns (FixedPoint.Unsigned memory) { return _getFeeAdjustedCollateral(rawTotalDepositBoxCollateral); } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.8.0; pragma abicoder v2; import "../../common/implementation/FixedPoint.sol"; import "../../common/interfaces/ExpandedIERC20.sol"; import "./VotingToken.sol"; /** * @title Migration contract for VotingTokens. * @dev Handles migrating token holders from one token to the next. */ contract TokenMigrator { using FixedPoint for FixedPoint.Unsigned; /**************************************** * INTERNAL VARIABLES AND STORAGE * ****************************************/ VotingToken public oldToken; ExpandedIERC20 public newToken; uint256 public snapshotId; FixedPoint.Unsigned public rate; mapping(address => bool) public hasMigrated; /** * @notice Construct the TokenMigrator contract. * @dev This function triggers the snapshot upon which all migrations will be based. * @param _rate the number of old tokens it takes to generate one new token. * @param _oldToken address of the token being migrated from. * @param _newToken address of the token being migrated to. */ constructor( FixedPoint.Unsigned memory _rate, address _oldToken, address _newToken ) { // Prevents division by 0 in migrateTokens(). // Also it doesn’t make sense to have “0 old tokens equate to 1 new token”. require(_rate.isGreaterThan(0), "Rate can't be 0"); rate = _rate; newToken = ExpandedIERC20(_newToken); oldToken = VotingToken(_oldToken); snapshotId = oldToken.snapshot(); } /** * @notice Migrates the tokenHolder's old tokens to new tokens. * @dev This function can only be called once per `tokenHolder`. Anyone can call this method * on behalf of any other token holder since there is no disadvantage to receiving the tokens earlier. * @param tokenHolder address of the token holder to migrate. */ function migrateTokens(address tokenHolder) external { require(!hasMigrated[tokenHolder], "Already migrated tokens"); hasMigrated[tokenHolder] = true; FixedPoint.Unsigned memory oldBalance = FixedPoint.Unsigned(oldToken.balanceOfAt(tokenHolder, snapshotId)); if (!oldBalance.isGreaterThan(0)) { return; } FixedPoint.Unsigned memory newBalance = oldBalance.div(rate); require(newToken.mint(tokenHolder, newBalance.rawValue), "Mint failed"); } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.8.0; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; /** * @title An implementation of ERC20 with the same interface as the Compound project's testnet tokens (mainly DAI) * @dev This contract can be deployed or the interface can be used to communicate with Compound's ERC20 tokens. Note: * this token should never be used to store real value since it allows permissionless minting. */ contract TestnetERC20 is ERC20 { uint8 _decimals; /** * @notice Constructs the TestnetERC20. * @param _name The name which describes the new token. * @param _symbol The ticker abbreviation of the name. Ideally < 5 chars. * @param _tokenDecimals The number of decimals to define token precision. */ constructor( string memory _name, string memory _symbol, uint8 _tokenDecimals ) ERC20(_name, _symbol) { _decimals = _tokenDecimals; } function decimals() public view virtual override(ERC20) returns (uint8) { return _decimals; } // Sample token information. /** * @notice Mints value tokens to the owner address. * @param ownerAddress the address to mint to. * @param value the amount of tokens to mint. */ function allocateTo(address ownerAddress, uint256 value) external { _mint(ownerAddress, value); } } // SPDX-License-Identifier: 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: AGPL-3.0-only pragma solidity ^0.8.0; pragma abicoder v2; import "@openzeppelin/contracts/access/AccessControl.sol"; import "@openzeppelin/contracts/security/Pausable.sol"; import "@openzeppelin/contracts/utils/math/SafeMath.sol"; import "./IDepositExecute.sol"; import "./IBridge.sol"; import "./IERCHandler.sol"; import "./IGenericHandler.sol"; /** @title Facilitates deposits, creation and votiing of deposit proposals, and deposit executions. @dev Copied directly from here: https://github.com/ChainSafe/chainbridge-solidity/releases/tag/v1.0.0 except for one small change to the imported Pausable and SafeMath contracts. We replaced local implementations with openzeppelin/contracts versions. @author ChainSafe Systems. */ contract Bridge is Pausable, AccessControl { using SafeMath for uint256; uint8 public _chainID; uint256 public _relayerThreshold; uint256 public _totalRelayers; uint256 public _totalProposals; uint256 public _fee; uint256 public _expiry; enum Vote { No, Yes } enum ProposalStatus { Inactive, Active, Passed, Executed, Cancelled } struct Proposal { bytes32 _resourceID; bytes32 _dataHash; address[] _yesVotes; address[] _noVotes; ProposalStatus _status; uint256 _proposedBlock; } // destinationChainID => number of deposits mapping(uint8 => uint64) public _depositCounts; // resourceID => handler address mapping(bytes32 => address) public _resourceIDToHandlerAddress; // depositNonce => destinationChainID => bytes mapping(uint64 => mapping(uint8 => bytes)) public _depositRecords; // destinationChainID + depositNonce => dataHash => Proposal mapping(uint72 => mapping(bytes32 => Proposal)) public _proposals; // destinationChainID + depositNonce => dataHash => relayerAddress => bool mapping(uint72 => mapping(bytes32 => mapping(address => bool))) public _hasVotedOnProposal; event RelayerThresholdChanged(uint256 indexed newThreshold); event RelayerAdded(address indexed relayer); event RelayerRemoved(address indexed relayer); event Deposit(uint8 indexed destinationChainID, bytes32 indexed resourceID, uint64 indexed depositNonce); event ProposalEvent( uint8 indexed originChainID, uint64 indexed depositNonce, ProposalStatus indexed status, bytes32 resourceID, bytes32 dataHash ); event ProposalVote( uint8 indexed originChainID, uint64 indexed depositNonce, ProposalStatus indexed status, bytes32 resourceID ); bytes32 public constant RELAYER_ROLE = keccak256("RELAYER_ROLE"); modifier onlyAdmin() { _onlyAdmin(); _; } modifier onlyAdminOrRelayer() { _onlyAdminOrRelayer(); _; } modifier onlyRelayers() { _onlyRelayers(); _; } function _onlyAdminOrRelayer() private view { require( hasRole(DEFAULT_ADMIN_ROLE, msg.sender) || hasRole(RELAYER_ROLE, msg.sender), "sender is not relayer or admin" ); } function _onlyAdmin() private view { require(hasRole(DEFAULT_ADMIN_ROLE, msg.sender), "sender doesn't have admin role"); } function _onlyRelayers() private view { require(hasRole(RELAYER_ROLE, msg.sender), "sender doesn't have relayer role"); } /** @notice Initializes Bridge, creates and grants {msg.sender} the admin role, creates and grants {initialRelayers} the relayer role. @param chainID ID of chain the Bridge contract exists on. @param initialRelayers Addresses that should be initially granted the relayer role. @param initialRelayerThreshold Number of votes needed for a deposit proposal to be considered passed. */ constructor( uint8 chainID, address[] memory initialRelayers, uint256 initialRelayerThreshold, uint256 fee, uint256 expiry ) { _chainID = chainID; _relayerThreshold = initialRelayerThreshold; _fee = fee; _expiry = expiry; _setupRole(DEFAULT_ADMIN_ROLE, msg.sender); _setRoleAdmin(RELAYER_ROLE, DEFAULT_ADMIN_ROLE); for (uint256 i; i < initialRelayers.length; i++) { grantRole(RELAYER_ROLE, initialRelayers[i]); _totalRelayers++; } } /** @notice Returns true if {relayer} has the relayer role. @param relayer Address to check. */ function isRelayer(address relayer) external view returns (bool) { return hasRole(RELAYER_ROLE, relayer); } /** @notice Removes admin role from {msg.sender} and grants it to {newAdmin}. @notice Only callable by an address that currently has the admin role. @param newAdmin Address that admin role will be granted to. */ function renounceAdmin(address newAdmin) external onlyAdmin { grantRole(DEFAULT_ADMIN_ROLE, newAdmin); renounceRole(DEFAULT_ADMIN_ROLE, msg.sender); } /** @notice Pauses deposits, proposal creation and voting, and deposit executions. @notice Only callable by an address that currently has the admin role. */ function adminPauseTransfers() external onlyAdmin { _pause(); } /** @notice Unpauses deposits, proposal creation and voting, and deposit executions. @notice Only callable by an address that currently has the admin role. */ function adminUnpauseTransfers() external onlyAdmin { _unpause(); } /** @notice Modifies the number of votes required for a proposal to be considered passed. @notice Only callable by an address that currently has the admin role. @param newThreshold Value {_relayerThreshold} will be changed to. @notice Emits {RelayerThresholdChanged} event. */ function adminChangeRelayerThreshold(uint256 newThreshold) external onlyAdmin { _relayerThreshold = newThreshold; emit RelayerThresholdChanged(newThreshold); } /** @notice Grants {relayerAddress} the relayer role and increases {_totalRelayer} count. @notice Only callable by an address that currently has the admin role. @param relayerAddress Address of relayer to be added. @notice Emits {RelayerAdded} event. */ function adminAddRelayer(address relayerAddress) external onlyAdmin { require(!hasRole(RELAYER_ROLE, relayerAddress), "addr already has relayer role!"); grantRole(RELAYER_ROLE, relayerAddress); emit RelayerAdded(relayerAddress); _totalRelayers++; } /** @notice Removes relayer role for {relayerAddress} and decreases {_totalRelayer} count. @notice Only callable by an address that currently has the admin role. @param relayerAddress Address of relayer to be removed. @notice Emits {RelayerRemoved} event. */ function adminRemoveRelayer(address relayerAddress) external onlyAdmin { require(hasRole(RELAYER_ROLE, relayerAddress), "addr doesn't have relayer role!"); revokeRole(RELAYER_ROLE, relayerAddress); emit RelayerRemoved(relayerAddress); _totalRelayers--; } /** @notice Sets a new resource for handler contracts that use the IERCHandler interface, and maps the {handlerAddress} to {resourceID} in {_resourceIDToHandlerAddress}. @notice Only callable by an address that currently has the admin role. @param handlerAddress Address of handler resource will be set for. @param resourceID ResourceID to be used when making deposits. @param tokenAddress Address of contract to be called when a deposit is made and a deposited is executed. */ function adminSetResource( address handlerAddress, bytes32 resourceID, address tokenAddress ) external onlyAdmin { _resourceIDToHandlerAddress[resourceID] = handlerAddress; IERCHandler handler = IERCHandler(handlerAddress); handler.setResource(resourceID, tokenAddress); } /** @notice Sets a new resource for handler contracts that use the IGenericHandler interface, and maps the {handlerAddress} to {resourceID} in {_resourceIDToHandlerAddress}. @notice Only callable by an address that currently has the admin role. @param handlerAddress Address of handler resource will be set for. @param resourceID ResourceID to be used when making deposits. @param contractAddress Address of contract to be called when a deposit is made and a deposited is executed. */ function adminSetGenericResource( address handlerAddress, bytes32 resourceID, address contractAddress, bytes4 depositFunctionSig, bytes4 executeFunctionSig ) external onlyAdmin { _resourceIDToHandlerAddress[resourceID] = handlerAddress; IGenericHandler handler = IGenericHandler(handlerAddress); handler.setResource(resourceID, contractAddress, depositFunctionSig, executeFunctionSig); } /** @notice Sets a resource as burnable for handler contracts that use the IERCHandler interface. @notice Only callable by an address that currently has the admin role. @param handlerAddress Address of handler resource will be set for. @param tokenAddress Address of contract to be called when a deposit is made and a deposited is executed. */ function adminSetBurnable(address handlerAddress, address tokenAddress) external onlyAdmin { IERCHandler handler = IERCHandler(handlerAddress); handler.setBurnable(tokenAddress); } /** @notice Returns a proposal. @param originChainID Chain ID deposit originated from. @param depositNonce ID of proposal generated by proposal's origin Bridge contract. @param dataHash Hash of data to be provided when deposit proposal is executed. @return Proposal which consists of: - _dataHash Hash of data to be provided when deposit proposal is executed. - _yesVotes Number of votes in favor of proposal. - _noVotes Number of votes against proposal. - _status Current status of proposal. */ function getProposal( uint8 originChainID, uint64 depositNonce, bytes32 dataHash ) external view returns (Proposal memory) { uint72 nonceAndID = (uint72(depositNonce) << 8) | uint72(originChainID); return _proposals[nonceAndID][dataHash]; } /** @notice Changes deposit fee. @notice Only callable by admin. @param newFee Value {_fee} will be updated to. */ function adminChangeFee(uint256 newFee) external onlyAdmin { require(_fee != newFee, "Current fee is equal to new fee"); _fee = newFee; } /** @notice Used to manually withdraw funds from ERC safes. @param handlerAddress Address of handler to withdraw from. @param tokenAddress Address of token to withdraw. @param recipient Address to withdraw tokens to. @param amountOrTokenID Either the amount of ERC20 tokens or the ERC721 token ID to withdraw. */ function adminWithdraw( address handlerAddress, address tokenAddress, address recipient, uint256 amountOrTokenID ) external onlyAdmin { IERCHandler handler = IERCHandler(handlerAddress); handler.withdraw(tokenAddress, recipient, amountOrTokenID); } /** @notice Initiates a transfer using a specified handler contract. @notice Only callable when Bridge is not paused. @param destinationChainID ID of chain deposit will be bridged to. @param resourceID ResourceID used to find address of handler to be used for deposit. @param data Additional data to be passed to specified handler. @notice Emits {Deposit} event. */ function deposit( uint8 destinationChainID, bytes32 resourceID, bytes calldata data ) external payable whenNotPaused { require(msg.value == _fee, "Incorrect fee supplied"); address handler = _resourceIDToHandlerAddress[resourceID]; require(handler != address(0), "resourceID not mapped to handler"); uint64 depositNonce = ++_depositCounts[destinationChainID]; _depositRecords[depositNonce][destinationChainID] = data; IDepositExecute depositHandler = IDepositExecute(handler); depositHandler.deposit(resourceID, destinationChainID, depositNonce, msg.sender, data); emit Deposit(destinationChainID, resourceID, depositNonce); } /** @notice When called, {msg.sender} will be marked as voting in favor of proposal. @notice Only callable by relayers when Bridge is not paused. @param chainID ID of chain deposit originated from. @param depositNonce ID of deposited generated by origin Bridge contract. @param dataHash Hash of data provided when deposit was made. @notice Proposal must not have already been passed or executed. @notice {msg.sender} must not have already voted on proposal. @notice Emits {ProposalEvent} event with status indicating the proposal status. @notice Emits {ProposalVote} event. */ function voteProposal( uint8 chainID, uint64 depositNonce, bytes32 resourceID, bytes32 dataHash ) external onlyRelayers whenNotPaused { uint72 nonceAndID = (uint72(depositNonce) << 8) | uint72(chainID); Proposal storage proposal = _proposals[nonceAndID][dataHash]; require(_resourceIDToHandlerAddress[resourceID] != address(0), "no handler for resourceID"); require(uint256(proposal._status) <= 1, "proposal already passed/executed/cancelled"); require(!_hasVotedOnProposal[nonceAndID][dataHash][msg.sender], "relayer already voted"); if (uint256(proposal._status) == 0) { ++_totalProposals; _proposals[nonceAndID][dataHash] = Proposal({ _resourceID: resourceID, _dataHash: dataHash, _yesVotes: new address[](1), _noVotes: new address[](0), _status: ProposalStatus.Active, _proposedBlock: block.number }); proposal._yesVotes[0] = msg.sender; emit ProposalEvent(chainID, depositNonce, ProposalStatus.Active, resourceID, dataHash); } else { if (block.number.sub(proposal._proposedBlock) > _expiry) { // if the number of blocks that has passed since this proposal was // submitted exceeds the expiry threshold set, cancel the proposal proposal._status = ProposalStatus.Cancelled; emit ProposalEvent(chainID, depositNonce, ProposalStatus.Cancelled, resourceID, dataHash); } else { require(dataHash == proposal._dataHash, "datahash mismatch"); proposal._yesVotes.push(msg.sender); } } if (proposal._status != ProposalStatus.Cancelled) { _hasVotedOnProposal[nonceAndID][dataHash][msg.sender] = true; emit ProposalVote(chainID, depositNonce, proposal._status, resourceID); // If _depositThreshold is set to 1, then auto finalize // or if _relayerThreshold has been exceeded if (_relayerThreshold <= 1 || proposal._yesVotes.length >= _relayerThreshold) { proposal._status = ProposalStatus.Passed; emit ProposalEvent(chainID, depositNonce, ProposalStatus.Passed, resourceID, dataHash); } } } /** @notice Executes a deposit proposal that is considered passed using a specified handler contract. @notice Only callable by relayers when Bridge is not paused. @param chainID ID of chain deposit originated from. @param depositNonce ID of deposited generated by origin Bridge contract. @param dataHash Hash of data originally provided when deposit was made. @notice Proposal must be past expiry threshold. @notice Emits {ProposalEvent} event with status {Cancelled}. */ function cancelProposal( uint8 chainID, uint64 depositNonce, bytes32 dataHash ) public onlyAdminOrRelayer { uint72 nonceAndID = (uint72(depositNonce) << 8) | uint72(chainID); Proposal storage proposal = _proposals[nonceAndID][dataHash]; require(proposal._status != ProposalStatus.Cancelled, "Proposal already cancelled"); require(block.number.sub(proposal._proposedBlock) > _expiry, "Proposal not at expiry threshold"); proposal._status = ProposalStatus.Cancelled; emit ProposalEvent(chainID, depositNonce, ProposalStatus.Cancelled, proposal._resourceID, proposal._dataHash); } /** @notice Executes a deposit proposal that is considered passed using a specified handler contract. @notice Only callable by relayers when Bridge is not paused. @param chainID ID of chain deposit originated from. @param resourceID ResourceID to be used when making deposits. @param depositNonce ID of deposited generated by origin Bridge contract. @param data Data originally provided when deposit was made. @notice Proposal must have Passed status. @notice Hash of {data} must equal proposal's {dataHash}. @notice Emits {ProposalEvent} event with status {Executed}. */ function executeProposal( uint8 chainID, uint64 depositNonce, bytes calldata data, bytes32 resourceID ) external onlyRelayers whenNotPaused { address handler = _resourceIDToHandlerAddress[resourceID]; uint72 nonceAndID = (uint72(depositNonce) << 8) | uint72(chainID); bytes32 dataHash = keccak256(abi.encodePacked(handler, data)); Proposal storage proposal = _proposals[nonceAndID][dataHash]; require(proposal._status != ProposalStatus.Inactive, "proposal is not active"); require(proposal._status == ProposalStatus.Passed, "proposal already transferred"); require(dataHash == proposal._dataHash, "data doesn't match datahash"); proposal._status = ProposalStatus.Executed; IDepositExecute depositHandler = IDepositExecute(_resourceIDToHandlerAddress[proposal._resourceID]); depositHandler.executeProposal(proposal._resourceID, data); emit ProposalEvent(chainID, depositNonce, proposal._status, proposal._resourceID, proposal._dataHash); } /** @notice Transfers eth in the contract to the specified addresses. The parameters addrs and amounts are mapped 1-1. This means that the address at index 0 for addrs will receive the amount (in WEI) from amounts at index 0. @param addrs Array of addresses to transfer {amounts} to. @param amounts Array of amonuts to transfer to {addrs}. */ function transferFunds(address payable[] calldata addrs, uint256[] calldata amounts) external onlyAdmin { for (uint256 i = 0; i < addrs.length; i++) { addrs[i].transfer(amounts[i]); } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../utils/Context.sol"; import "../utils/Strings.sol"; import "../utils/introspection/ERC165.sol"; /** * @dev External interface of AccessControl declared to support ERC165 detection. */ interface IAccessControl { function hasRole(bytes32 role, address account) external view returns (bool); function getRoleAdmin(bytes32 role) external view returns (bytes32); function grantRole(bytes32 role, address account) external; function revokeRole(bytes32 role, address account) external; function renounceRole(bytes32 role, address account) external; } /** * @dev Contract module that allows children to implement role-based access * control mechanisms. This is a lightweight version that doesn't allow enumerating role * members except through off-chain means by accessing the contract event logs. Some * applications may benefit from on-chain enumerability, for those cases see * {AccessControlEnumerable}. * * Roles are referred to by their `bytes32` identifier. These should be exposed * in the external API and be unique. The best way to achieve this is by * using `public constant` hash digests: * * ``` * bytes32 public constant MY_ROLE = keccak256("MY_ROLE"); * ``` * * Roles can be used to represent a set of permissions. To restrict access to a * function call, use {hasRole}: * * ``` * function foo() public { * require(hasRole(MY_ROLE, msg.sender)); * ... * } * ``` * * Roles can be granted and revoked dynamically via the {grantRole} and * {revokeRole} functions. Each role has an associated admin role, and only * accounts that have a role's admin role can call {grantRole} and {revokeRole}. * * By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means * that only accounts with this role will be able to grant or revoke other * roles. More complex role relationships can be created by using * {_setRoleAdmin}. * * WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to * grant and revoke this role. Extra precautions should be taken to secure * accounts that have been granted it. */ abstract contract 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 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 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]{20}) is missing role (0x[0-9a-f]{32})$/ * * _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]{20}) is missing role (0x[0-9a-f]{32})$/ */ 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 { emit RoleAdminChanged(role, getRoleAdmin(role), adminRole); _roles[role].adminRole = adminRole; } function _grantRole(bytes32 role, address account) private { if (!hasRole(role, account)) { _roles[role].members[account] = true; emit RoleGranted(role, account, _msgSender()); } } function _revokeRole(bytes32 role, address account) private { if (hasRole(role, account)) { _roles[role].members[account] = false; emit RoleRevoked(role, account, _msgSender()); } } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.8.0; /** @title Interface for handler contracts that support deposits and deposit executions. @dev Copied directly from here: https://github.com/ChainSafe/chainbridge-solidity/releases/tag/v1.0.0. @author ChainSafe Systems. */ interface IDepositExecute { /** @notice It is intended that deposit are made using the Bridge contract. @param destinationChainID Chain ID deposit is expected to be bridged to. @param depositNonce This value is generated as an ID by the Bridge contract. @param depositer Address of account making the deposit in the Bridge contract. @param data Consists of additional data needed for a specific deposit. */ function deposit( bytes32 resourceID, uint8 destinationChainID, uint64 depositNonce, address depositer, bytes calldata data ) external; /** @notice It is intended that proposals are executed by the Bridge contract. @param data Consists of additional data needed for a specific deposit execution. */ function executeProposal(bytes32 resourceID, bytes calldata data) external; } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.8.0; /** @title Interface for Bridge contract. @dev Copied directly from here: https://github.com/ChainSafe/chainbridge-solidity/releases/tag/v1.0.0 except for the addition of `deposit()` so that this contract can be called from Sink and Source Oracle contracts. @author ChainSafe Systems. */ interface IBridge { /** @notice Exposing getter for {_chainID} instead of forcing the use of call. @return uint8 The {_chainID} that is currently set for the Bridge contract. */ function _chainID() external returns (uint8); function deposit( uint8 destinationChainID, bytes32 resourceID, bytes calldata data ) external; } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.8.0; /** @title Interface to be used with handlers that support ERC20s and ERC721s. @dev Copied directly from here: https://github.com/ChainSafe/chainbridge-solidity/releases/tag/v1.0.0. @author ChainSafe Systems. */ interface IERCHandler { /** @notice Correlates {resourceID} with {contractAddress}. @param resourceID ResourceID to be used when making deposits. @param contractAddress Address of contract to be called when a deposit is made and a deposited is executed. */ function setResource(bytes32 resourceID, address contractAddress) external; /** @notice Marks {contractAddress} as mintable/burnable. @param contractAddress Address of contract to be used when making or executing deposits. */ function setBurnable(address contractAddress) external; /** @notice Used to manually release funds from ERC safes. @param tokenAddress Address of token contract to release. @param recipient Address to release tokens to. @param amountOrTokenID Either the amount of ERC20 tokens or the ERC721 token ID to release. */ function withdraw( address tokenAddress, address recipient, uint256 amountOrTokenID ) external; } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.8.0; /** @title Interface for handler that handles generic deposits and deposit executions. @dev Copied directly from here: https://github.com/ChainSafe/chainbridge-solidity/releases/tag/v1.0.0. @author ChainSafe Systems. */ interface IGenericHandler { /** @notice Correlates {resourceID} with {contractAddress}, {depositFunctionSig}, and {executeFunctionSig}. @param resourceID ResourceID to be used when making deposits. @param contractAddress Address of contract to be called when a deposit is made and a deposited is executed. @param depositFunctionSig Function signature of method to be called in {contractAddress} when a deposit is made. @param executeFunctionSig Function signature of method to be called in {contractAddress} when a deposit is executed. */ function setResource( bytes32 resourceID, address contractAddress, bytes4 depositFunctionSig, bytes4 executeFunctionSig ) external; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev String operations. */ library Strings { bytes16 private constant alphabet = "0123456789abcdef"; /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0x00"; } uint256 temp = value; uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return toHexString(value, length); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = alphabet[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./IERC165.sol"; /** * @dev Implementation of the {IERC165} interface. * * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check * for the additional interface id that will be supported. For example: * * ```solidity * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId); * } * ``` * * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation. */ abstract contract ERC165 is IERC165 { /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165).interfaceId; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.8.0; pragma abicoder v2; import "./IGenericHandler.sol"; /** @title Handles generic deposits and deposit executions. @author ChainSafe Systems. @notice This contract is intended to be used with the Bridge contract. Copied directly from here: https://github.com/ChainSafe/chainbridge-solidity/releases/tag/v1.0.0 */ contract GenericHandler is IGenericHandler { address public _bridgeAddress; struct DepositRecord { uint8 _destinationChainID; address _depositer; bytes32 _resourceID; bytes _metaData; } // depositNonce => Deposit Record mapping(uint8 => mapping(uint64 => DepositRecord)) public _depositRecords; // resourceID => contract address mapping(bytes32 => address) public _resourceIDToContractAddress; // contract address => resourceID mapping(address => bytes32) public _contractAddressToResourceID; // contract address => deposit function signature mapping(address => bytes4) public _contractAddressToDepositFunctionSignature; // contract address => execute proposal function signature mapping(address => bytes4) public _contractAddressToExecuteFunctionSignature; // token contract address => is whitelisted mapping(address => bool) public _contractWhitelist; modifier onlyBridge() { _onlyBridge(); _; } function _onlyBridge() private { require(msg.sender == _bridgeAddress, "sender must be bridge contract"); } /** @param bridgeAddress Contract address of previously deployed Bridge. @param initialResourceIDs Resource IDs used to identify a specific contract address. These are the Resource IDs this contract will initially support. @param initialContractAddresses These are the addresses the {initialResourceIDs} will point to, and are the contracts that will be called to perform deposit and execution calls. @param initialDepositFunctionSignatures These are the function signatures {initialContractAddresses} will point to, and are the function that will be called when executing {deposit} @param initialExecuteFunctionSignatures These are the function signatures {initialContractAddresses} will point to, and are the function that will be called when executing {executeProposal} @dev {initialResourceIDs}, {initialContractAddresses}, {initialDepositFunctionSignatures}, and {initialExecuteFunctionSignatures} must all have the same length. Also, values must be ordered in the way that that index x of any mentioned array must be intended for value x of any other array, e.g. {initialContractAddresses}[0] is the intended address for {initialDepositFunctionSignatures}[0]. */ constructor( address bridgeAddress, bytes32[] memory initialResourceIDs, address[] memory initialContractAddresses, bytes4[] memory initialDepositFunctionSignatures, bytes4[] memory initialExecuteFunctionSignatures ) { require( initialResourceIDs.length == initialContractAddresses.length, "initialResourceIDs and initialContractAddresses len mismatch" ); require( initialContractAddresses.length == initialDepositFunctionSignatures.length, "provided contract addresses and function signatures len mismatch" ); require( initialDepositFunctionSignatures.length == initialExecuteFunctionSignatures.length, "provided deposit and execute function signatures len mismatch" ); _bridgeAddress = bridgeAddress; for (uint256 i = 0; i < initialResourceIDs.length; i++) { _setResource( initialResourceIDs[i], initialContractAddresses[i], initialDepositFunctionSignatures[i], initialExecuteFunctionSignatures[i] ); } } /** @param depositNonce This ID will have been generated by the Bridge contract. @param destId ID of chain deposit will be bridged to. @return DepositRecord which consists of: - _destinationChainID ChainID deposited tokens are intended to end up on. - _resourceID ResourceID used when {deposit} was executed. - _depositer Address that initially called {deposit} in the Bridge contract. - _metaData Data to be passed to method executed in corresponding {resourceID} contract. */ function getDepositRecord(uint64 depositNonce, uint8 destId) external view returns (DepositRecord memory) { return _depositRecords[destId][depositNonce]; } /** @notice First verifies {_resourceIDToContractAddress}[{resourceID}] and {_contractAddressToResourceID}[{contractAddress}] are not already set, then sets {_resourceIDToContractAddress} with {contractAddress}, {_contractAddressToResourceID} with {resourceID}, {_contractAddressToDepositFunctionSignature} with {depositFunctionSig}, {_contractAddressToExecuteFunctionSignature} with {executeFunctionSig}, and {_contractWhitelist} to true for {contractAddress}. @param resourceID ResourceID to be used when making deposits. @param contractAddress Address of contract to be called when a deposit is made and a deposited is executed. @param depositFunctionSig Function signature of method to be called in {contractAddress} when a deposit is made. @param executeFunctionSig Function signature of method to be called in {contractAddress} when a deposit is executed. */ function setResource( bytes32 resourceID, address contractAddress, bytes4 depositFunctionSig, bytes4 executeFunctionSig ) external override onlyBridge { _setResource(resourceID, contractAddress, depositFunctionSig, executeFunctionSig); } /** @notice A deposit is initiatied by making a deposit in the Bridge contract. @param destinationChainID Chain ID deposit is expected to be bridged to. @param depositNonce This value is generated as an ID by the Bridge contract. @param depositer Address of account making the deposit in the Bridge contract. @param data Consists of: {resourceID}, {lenMetaData}, and {metaData} all padded to 32 bytes. @notice Data passed into the function should be constructed as follows: len(data) uint256 bytes 0 - 32 data bytes bytes 64 - END @notice {contractAddress} is required to be whitelisted @notice If {_contractAddressToDepositFunctionSignature}[{contractAddress}] is set, {metaData} is expected to consist of needed function arguments. */ function deposit( bytes32 resourceID, uint8 destinationChainID, uint64 depositNonce, address depositer, bytes calldata data ) external onlyBridge { bytes32 lenMetadata; bytes memory metadata; assembly { // Load length of metadata from data + 64 lenMetadata := calldataload(0xC4) // Load free memory pointer metadata := mload(0x40) mstore(0x40, add(0x20, add(metadata, lenMetadata))) // func sig (4) + destinationChainId (padded to 32) + depositNonce (32) + depositor (32) + // bytes length (32) + resourceId (32) + length (32) = 0xC4 calldatacopy( metadata, // copy to metadata 0xC4, // copy from calldata after metadata length declaration @0xC4 sub(calldatasize(), 0xC4) // copy size (calldatasize - (0xC4 + the space metaData takes up)) ) } address contractAddress = _resourceIDToContractAddress[resourceID]; require(_contractWhitelist[contractAddress], "provided contractAddress is not whitelisted"); bytes4 sig = _contractAddressToDepositFunctionSignature[contractAddress]; if (sig != bytes4(0)) { bytes memory callData = abi.encodePacked(sig, metadata); (bool success, ) = contractAddress.call(callData); require(success, "delegatecall to contractAddress failed"); } _depositRecords[destinationChainID][depositNonce] = DepositRecord( destinationChainID, depositer, resourceID, metadata ); } /** @notice Proposal execution should be initiated when a proposal is finalized in the Bridge contract. @param data Consists of {resourceID}, {lenMetaData}, and {metaData}. @notice Data passed into the function should be constructed as follows: len(data) uint256 bytes 0 - 32 data bytes bytes 32 - END @notice {contractAddress} is required to be whitelisted @notice If {_contractAddressToExecuteFunctionSignature}[{contractAddress}] is set, {metaData} is expected to consist of needed function arguments. */ function executeProposal(bytes32 resourceID, bytes calldata data) external onlyBridge { bytes memory metaData; assembly { // metadata has variable length // load free memory pointer to store metadata metaData := mload(0x40) // first 32 bytes of variable length in storage refer to length let lenMeta := calldataload(0x64) mstore(0x40, add(0x60, add(metaData, lenMeta))) // in the calldata, metadata is stored @0x64 after accounting for function signature, and 2 previous params calldatacopy( metaData, // copy to metaData 0x64, // copy from calldata after data length declaration at 0x64 sub(calldatasize(), 0x64) // copy size (calldatasize - 0x64) ) } address contractAddress = _resourceIDToContractAddress[resourceID]; require(_contractWhitelist[contractAddress], "provided contractAddress is not whitelisted"); bytes4 sig = _contractAddressToExecuteFunctionSignature[contractAddress]; if (sig != bytes4(0)) { bytes memory callData = abi.encodePacked(sig, metaData); (bool success, ) = contractAddress.call(callData); require(success, "delegatecall to contractAddress failed"); } } function _setResource( bytes32 resourceID, address contractAddress, bytes4 depositFunctionSig, bytes4 executeFunctionSig ) internal { _resourceIDToContractAddress[resourceID] = contractAddress; _contractAddressToResourceID[contractAddress] = resourceID; _contractAddressToDepositFunctionSignature[contractAddress] = depositFunctionSig; _contractAddressToExecuteFunctionSignature[contractAddress] = executeFunctionSig; _contractWhitelist[contractAddress] = true; } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.8.0; pragma abicoder v2; import "../oracle/interfaces/FinderInterface.sol"; import "./IBridge.sol"; import "../oracle/implementation/Constants.sol"; /** * @title Simple implementation of the OracleInterface used to communicate price request data cross-chain between * EVM networks. Can be extended either into a "Source" or "Sink" oracle that specializes in making and resolving * cross-chain price requests, respectivly. The "Source" Oracle is the originator or source of price resolution data * and can only resolve prices already published by the DVM. The "Sink" Oracle receives the price resolution data * from the Source Oracle and makes it available on non-Mainnet chains. The "Sink" Oracle can also be used to trigger * price requests from the DVM on Mainnet. */ abstract contract BeaconOracle { enum RequestState { NeverRequested, Requested, Resolved } struct Price { RequestState state; int256 price; } // Chain ID for this Oracle. uint8 public currentChainID; // Mapping of encoded price requests {identifier, time, ancillaryData} to Price objects. mapping(bytes32 => Price) internal prices; // Finder to provide addresses for DVM system contracts. FinderInterface public finder; event PriceRequestAdded( address indexed requester, uint8 indexed chainID, bytes32 indexed identifier, uint256 time, bytes ancillaryData ); event PushedPrice( address indexed pusher, uint8 indexed chainID, bytes32 indexed identifier, uint256 time, bytes ancillaryData, int256 price ); /** * @notice Constructor. * @param _finderAddress finder to use to get addresses of DVM contracts. */ constructor(address _finderAddress, uint8 _chainID) { finder = FinderInterface(_finderAddress); currentChainID = _chainID; } // We assume that there is only one GenericHandler for this network. modifier onlyGenericHandlerContract() { require( msg.sender == finder.getImplementationAddress(OracleInterfaces.GenericHandler), "Caller must be GenericHandler" ); _; } /** * @notice Enqueues a request (if a request isn't already present) for the given (identifier, time, ancillary data) * pair. Will revert if request has been requested already. */ function _requestPrice( uint8 chainID, bytes32 identifier, uint256 time, bytes memory ancillaryData ) internal { bytes32 priceRequestId = _encodePriceRequest(chainID, identifier, time, ancillaryData); Price storage lookup = prices[priceRequestId]; if (lookup.state == RequestState.NeverRequested) { // New query, change state to Requested: lookup.state = RequestState.Requested; emit PriceRequestAdded(msg.sender, chainID, identifier, time, ancillaryData); } } /** * @notice Publishes price for a requested query. Will revert if request hasn't been requested yet or has been * resolved already. */ function _publishPrice( uint8 chainID, bytes32 identifier, uint256 time, bytes memory ancillaryData, int256 price ) internal { bytes32 priceRequestId = _encodePriceRequest(chainID, identifier, time, ancillaryData); Price storage lookup = prices[priceRequestId]; require(lookup.state == RequestState.Requested, "Price request is not currently pending"); lookup.price = price; lookup.state = RequestState.Resolved; emit PushedPrice(msg.sender, chainID, identifier, time, ancillaryData, lookup.price); } /** * @notice Returns Bridge contract on network. */ function _getBridge() internal view returns (IBridge) { return IBridge(finder.getImplementationAddress(OracleInterfaces.Bridge)); } /** * @notice Returns the convenient way to store price requests, uniquely identified by {chainID, identifier, time, * ancillaryData }. */ function _encodePriceRequest( uint8 chainID, bytes32 identifier, uint256 time, bytes memory ancillaryData ) internal pure returns (bytes32) { return keccak256(abi.encode(chainID, identifier, time, ancillaryData)); } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.8.0; import "./BeaconOracle.sol"; import "../oracle/interfaces/OracleAncillaryInterface.sol"; /** * @title Extension of BeaconOracle that is intended to be deployed on Mainnet to give financial * contracts on non-Mainnet networks the ability to trigger cross-chain price requests to the Mainnet DVM. This contract * is responsible for triggering price requests originating from non-Mainnet, and broadcasting resolved price data * back to those networks. Technically, this contract is more of a Proxy than an Oracle, because it does not implement * the full Oracle interface including the getPrice and requestPrice methods. It's goal is to shuttle price request * functionality between L2 and L1. * @dev The intended client of this contract is some off-chain bot watching for resolved price events on the DVM. Once * that bot sees a price has resolved, it can call `publishPrice()` on this contract which will call the local Bridge * contract to signal to an off-chain relayer to bridge a price request to another network. * @dev This contract must be a registered financial contract in order to call DVM methods. */ contract SourceOracle is BeaconOracle { constructor(address _finderAddress, uint8 _chainID) BeaconOracle(_finderAddress, _chainID) {} /*************************************************************** * Publishing Price Request Data to L2: ***************************************************************/ /** * @notice This is the first method that should be called in order to publish a price request to another network * marked by `sinkChainID`. * @dev Publishes the DVM resolved price for the price request, or reverts if not resolved yet. Will call the * local Bridge's deposit() method which will emit a Deposit event in order to signal to an off-chain * relayer to begin the cross-chain process. */ function publishPrice( uint8 sinkChainID, bytes32 identifier, uint256 time, bytes memory ancillaryData ) public { require(_getOracle().hasPrice(identifier, time, ancillaryData), "DVM has not resolved price"); int256 price = _getOracle().getPrice(identifier, time, ancillaryData); _publishPrice(sinkChainID, identifier, time, ancillaryData, price); // Call Bridge.deposit() to initiate cross-chain publishing of price request. _getBridge().deposit( sinkChainID, getResourceId(), _formatMetadata(sinkChainID, identifier, time, ancillaryData, price) ); } /** * @notice This method will ultimately be called after `publishPrice` calls `Bridge.deposit()`, which will call * `GenericHandler.deposit()` and ultimately this method. * @dev This method should basically check that the `Bridge.deposit()` was triggered by a valid publish event. */ function validateDeposit( uint8 sinkChainID, bytes32 identifier, uint256 time, bytes memory ancillaryData, int256 price ) public view { bytes32 priceRequestId = _encodePriceRequest(sinkChainID, identifier, time, ancillaryData); Price storage lookup = prices[priceRequestId]; require(lookup.state == RequestState.Resolved, "Price has not been published"); require(lookup.price == price, "Unexpected price published"); } /*************************************************************** * Responding to a Price Request from L2: ***************************************************************/ /** * @notice This method will ultimately be called after a `requestPrice` has been bridged cross-chain from * non-Mainnet to this network via an off-chain relayer. The relayer will call `Bridge.executeProposal` on this * local network, which call `GenericHandler.executeProposal()` and ultimately this method. * @dev This method should prepare this oracle to receive a published price and then forward the price request * to the DVM. Can only be called by the `GenericHandler`. */ function executeRequestPrice( uint8 sinkChainID, bytes32 identifier, uint256 time, bytes memory ancillaryData ) public onlyGenericHandlerContract() { _requestPrice(sinkChainID, identifier, time, ancillaryData); _getOracle().requestPrice(identifier, time, ancillaryData); } /** * @notice Convenience method to get cross-chain Bridge resource ID linking this contract with its SinkOracles. * @dev More details about Resource ID's here: https://chainbridge.chainsafe.io/spec/#resource-id * @return bytes32 Hash containing this stored chain ID. */ function getResourceId() public view returns (bytes32) { return keccak256(abi.encode("Oracle", currentChainID)); } /** * @notice Return DVM for this network. */ function _getOracle() internal view returns (OracleAncillaryInterface) { return OracleAncillaryInterface(finder.getImplementationAddress(OracleInterfaces.Oracle)); } /** * @notice This helper method is useful for calling Bridge.deposit(). * @dev GenericHandler.deposit() expects data to be formatted as: * len(data) uint256 bytes 0 - 64 * data bytes bytes 64 - END */ function _formatMetadata( uint8 chainID, bytes32 identifier, uint256 time, bytes memory ancillaryData, int256 price ) internal pure returns (bytes memory) { bytes memory metadata = abi.encode(chainID, identifier, time, ancillaryData, price); return abi.encodePacked(metadata.length, metadata); } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.8.0; import "./BeaconOracle.sol"; import "../oracle/interfaces/OracleAncillaryInterface.sol"; import "../oracle/interfaces/RegistryInterface.sol"; /** * @title Extension of BeaconOracle that is intended to be deployed on non-Mainnet networks to give financial * contracts on those networks the ability to trigger cross-chain price requests to the Mainnet DVM. Also has the * ability to receive published prices from Mainnet. This contract can be treated as the "DVM" for a non-Mainnet * network, because a calling contract can request and access a resolved price request from this contract. * @dev The intended client of this contract is an OptimisticOracle on a non-Mainnet network that needs price * resolution secured by the DVM on Mainnet. If a registered contract, such as the OptimisticOracle, calls * `requestPrice()` on this contract, then it will call the network's Bridge contract to signal to an off-chain * relayer to bridge a price request to Mainnet. */ contract SinkOracle is BeaconOracle, OracleAncillaryInterface { // Chain ID of the Source Oracle that will communicate this contract's price request to the DVM on Mainnet. uint8 public destinationChainID; constructor( address _finderAddress, uint8 _chainID, uint8 _destinationChainID ) BeaconOracle(_finderAddress, _chainID) { destinationChainID = _destinationChainID; } // This assumes that the local network has a Registry that resembles the Mainnet registry. modifier onlyRegisteredContract() { RegistryInterface registry = RegistryInterface(finder.getImplementationAddress(OracleInterfaces.Registry)); require(registry.isContractRegistered(msg.sender), "Caller must be registered"); _; } /*************************************************************** * Bridging a Price Request to L1: ***************************************************************/ /** * @notice This is the first method that should be called in order to bridge a price request to Mainnet. * @dev Can be called only by a Registered contract that is allowed to make DVM price requests. Will mark this * price request as Requested, and therefore able to receive the ultimate price resolution data, and also * calls the local Bridge's deposit() method which will emit a Deposit event in order to signal to an off-chain * relayer to begin the cross-chain process. */ function requestPrice( bytes32 identifier, uint256 time, bytes memory ancillaryData ) public override onlyRegisteredContract() { _requestPrice(currentChainID, identifier, time, ancillaryData); // Call Bridge.deposit() to intiate cross-chain price request. _getBridge().deposit( destinationChainID, getResourceId(), _formatMetadata(currentChainID, identifier, time, ancillaryData) ); } /** * @notice This method will ultimately be called after `requestPrice` calls `Bridge.deposit()`, which will call * `GenericHandler.deposit()` and ultimately this method. * @dev This method should basically check that the `Bridge.deposit()` was triggered by a valid price request, * specifically one that has not resolved yet and was called by a registered contract. Without this check, * `Bridge.deposit()` could be called by non-registered contracts to make price requests to the DVM. */ function validateDeposit( uint8 sinkChainID, bytes32 identifier, uint256 time, bytes memory ancillaryData ) public view { bytes32 priceRequestId = _encodePriceRequest(sinkChainID, identifier, time, ancillaryData); Price storage lookup = prices[priceRequestId]; require(lookup.state == RequestState.Requested, "Price has not been requested"); } /*************************************************************** * Responding to Price Request Resolution from L1: ***************************************************************/ /** * @notice This method will ultimately be called after a `publishPrice` has been bridged cross-chain from Mainnet * to this network via an off-chain relayer. The relayer will call `Bridge.executeProposal` on this local network, * which call `GenericHandler.executeProposal()` and ultimately this method. * @dev This method should publish the price data for a requested price request. If this method fails for some * reason, then it means that the price was never requested. Can only be called by the `GenericHandler`. */ function executePublishPrice( uint8 sinkChainID, bytes32 identifier, uint256 time, bytes memory ancillaryData, int256 price ) public onlyGenericHandlerContract() { _publishPrice(sinkChainID, identifier, time, ancillaryData, price); } /** * @notice Returns whether a price has resolved for the request. * @return True if a price is available, False otherwise. If true, then getPrice will succeed for the request. */ function hasPrice( bytes32 identifier, uint256 time, bytes memory ancillaryData ) public view override onlyRegisteredContract() returns (bool) { bytes32 priceRequestId = _encodePriceRequest(currentChainID, identifier, time, ancillaryData); return prices[priceRequestId].state == RequestState.Resolved; } /** * @notice Returns resolved price for the request. * @return int256 Price, or reverts if no resolved price for any reason. */ function getPrice( bytes32 identifier, uint256 time, bytes memory ancillaryData ) public view override onlyRegisteredContract() returns (int256) { bytes32 priceRequestId = _encodePriceRequest(currentChainID, identifier, time, ancillaryData); Price storage lookup = prices[priceRequestId]; require(lookup.state == RequestState.Resolved, "Price has not been resolved"); return lookup.price; } /** * @notice Convenience method to get cross-chain Bridge resource ID linking this contract with the SourceOracle. * @dev More details about Resource ID's here: https://chainbridge.chainsafe.io/spec/#resource-id * @return bytes32 Hash containing the chain ID of the SourceOracle. */ function getResourceId() public view returns (bytes32) { return keccak256(abi.encode("Oracle", destinationChainID)); } /** * @notice This helper method is useful for calling Bridge.deposit(). * @dev GenericHandler.deposit() expects data to be formatted as: * len(data) uint256 bytes 0 - 64 * data bytes bytes 64 - END */ function _formatMetadata( uint8 chainID, bytes32 identifier, uint256 time, bytes memory ancillaryData ) internal pure returns (bytes memory) { bytes memory metadata = abi.encode(chainID, identifier, time, ancillaryData); return abi.encodePacked(metadata.length, metadata); } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.8.0; pragma abicoder v2; import "../../common/implementation/ExpandedERC20.sol"; contract TokenSender { function transferERC20( address tokenAddress, address recipientAddress, uint256 amount ) public returns (bool) { IERC20 token = IERC20(tokenAddress); token.transfer(recipientAddress, amount); return true; } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.8.0; pragma abicoder v2; import "./FinancialProductLibrary.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; import "../../../common/implementation/Lockable.sol"; /** * @title Structured Note Financial Product Library * @notice Adds custom price transformation logic to modify the behavior of the expiring multi party contract. The * contract holds say 1 WETH in collateral and pays out that 1 WETH if, at expiry, ETHUSD is below a set strike. If * ETHUSD is above that strike, the contract pays out a given dollar amount of ETH. * Example: expiry is DEC 31. Strike is $400. Each token is backed by 1 WETH * If ETHUSD < $400 at expiry, token is redeemed for 1 ETH. * If ETHUSD >= $400 at expiry, token is redeemed for $400 worth of ETH, as determined by the DVM. */ contract StructuredNoteFinancialProductLibrary is FinancialProductLibrary, Ownable, Lockable { using FixedPoint for FixedPoint.Unsigned; mapping(address => FixedPoint.Unsigned) financialProductStrikes; /** * @notice Enables the deployer of the library to set the strike price for an associated financial product. * @param financialProduct address of the financial product. * @param strikePrice the strike price for the structured note to be applied to the financial product. * @dev Note: a) Only the owner (deployer) of this library can set new strike prices b) A strike price cannot be 0. * c) A strike price can only be set once to prevent the deployer from changing the strike after the fact. * d) financialProduct must exposes an expirationTimestamp method. */ function setFinancialProductStrike(address financialProduct, FixedPoint.Unsigned memory strikePrice) public onlyOwner nonReentrant() { require(strikePrice.isGreaterThan(0), "Cant set 0 strike"); require(financialProductStrikes[financialProduct].isEqual(0), "Strike already set"); require(ExpiringContractInterface(financialProduct).expirationTimestamp() != 0, "Invalid EMP contract"); financialProductStrikes[financialProduct] = strikePrice; } /** * @notice Returns the strike price associated with a given financial product address. * @param financialProduct address of the financial product. * @return strikePrice for the associated financial product. */ function getStrikeForFinancialProduct(address financialProduct) public view nonReentrantView() returns (FixedPoint.Unsigned memory) { return financialProductStrikes[financialProduct]; } /** * @notice Returns a transformed price by applying the structured note payout structure. * @param oraclePrice price from the oracle to be transformed. * @param requestTime timestamp the oraclePrice was requested at. * @return transformedPrice the input oracle price with the price transformation logic applied to it. */ function transformPrice(FixedPoint.Unsigned memory oraclePrice, uint256 requestTime) public view override nonReentrantView() returns (FixedPoint.Unsigned memory) { FixedPoint.Unsigned memory strike = financialProductStrikes[msg.sender]; require(strike.isGreaterThan(0), "Caller has no strike"); // If price request is made before expiry, return 1. Thus we can keep the contract 100% collateralized with // each token backed 1:1 by collateral currency. if (requestTime < ExpiringContractInterface(msg.sender).expirationTimestamp()) { return FixedPoint.fromUnscaledUint(1); } if (oraclePrice.isLessThan(strike)) { return FixedPoint.fromUnscaledUint(1); } else { // Token expires to be worth strike $ worth of collateral. // eg if ETHUSD is $500 and strike is $400, token is redeemable for 400/500 = 0.8 WETH. return strike.div(oraclePrice); } } /** * @notice Returns a transformed collateral requirement by applying the structured note payout structure. If the price * of the structured note is greater than the strike then the collateral requirement scales down accordingly. * @param oraclePrice price from the oracle to transform the collateral requirement. * @param collateralRequirement financial products collateral requirement to be scaled according to price and strike. * @return transformedCollateralRequirement the input collateral requirement with the transformation logic applied to it. */ function transformCollateralRequirement( FixedPoint.Unsigned memory oraclePrice, FixedPoint.Unsigned memory collateralRequirement ) public view override nonReentrantView() returns (FixedPoint.Unsigned memory) { FixedPoint.Unsigned memory strike = financialProductStrikes[msg.sender]; require(strike.isGreaterThan(0), "Caller has no strike"); // If the price is less than the strike than the original collateral requirement is used. if (oraclePrice.isLessThan(strike)) { return collateralRequirement; } else { // If the price is more than the strike then the collateral requirement is scaled by the strike. For example // a strike of $400 and a CR of 1.2 would yield: // ETHUSD = $350, payout is 1 WETH. CR is multiplied by 1. resulting CR = 1.2 // ETHUSD = $400, payout is 1 WETH. CR is multiplied by 1. resulting CR = 1.2 // ETHUSD = $425, payout is 0.941 WETH (worth $400). CR is multiplied by 0.941. resulting CR = 1.1292 // ETHUSD = $500, payout is 0.8 WETH (worth $400). CR multiplied by 0.8. resulting CR = 0.96 return collateralRequirement.mul(strike.div(oraclePrice)); } } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.8.0; pragma abicoder v2; import "./FinancialProductLibrary.sol"; import "../../../common/implementation/Lockable.sol"; /** * @title Pre-Expiration Identifier Transformation Financial Product Library * @notice Adds custom identifier transformation to enable a financial contract to use two different identifiers, depending * on when a price request is made. If the request is made before expiration then a transformation is made to the identifier * & if it is at or after expiration then the original identifier is returned. This library enables self referential * TWAP identifier to be used on synthetics pre-expiration, in conjunction with a separate identifier at expiration. */ contract PreExpirationIdentifierTransformationFinancialProductLibrary is FinancialProductLibrary, Lockable { mapping(address => bytes32) financialProductTransformedIdentifiers; /** * @notice Enables the deployer of the library to set the transformed identifier for an associated financial product. * @param financialProduct address of the financial product. * @param transformedIdentifier the identifier for the financial product to be used if the contract is pre expiration. * @dev Note: a) Any address can set identifier transformations b) The identifier can't be set to blank. c) A * transformed price can only be set once to prevent the deployer from changing it after the fact. d) financialProduct * must expose an expirationTimestamp method. */ function setFinancialProductTransformedIdentifier(address financialProduct, bytes32 transformedIdentifier) public nonReentrant() { require(transformedIdentifier != "", "Cant set to empty transformation"); require(financialProductTransformedIdentifiers[financialProduct] == "", "Transformation already set"); require(ExpiringContractInterface(financialProduct).expirationTimestamp() != 0, "Invalid EMP contract"); financialProductTransformedIdentifiers[financialProduct] = transformedIdentifier; } /** * @notice Returns the transformed identifier associated with a given financial product address. * @param financialProduct address of the financial product. * @return transformed identifier for the associated financial product. */ function getTransformedIdentifierForFinancialProduct(address financialProduct) public view nonReentrantView() returns (bytes32) { return financialProductTransformedIdentifiers[financialProduct]; } /** * @notice Returns a transformed price identifier if the contract is pre-expiration and no transformation if post. * @param identifier input price identifier to be transformed. * @param requestTime timestamp the identifier is to be used at. * @return transformedPriceIdentifier the input price identifier with the transformation logic applied to it. */ function transformPriceIdentifier(bytes32 identifier, uint256 requestTime) public view override nonReentrantView() returns (bytes32) { require(financialProductTransformedIdentifiers[msg.sender] != "", "Caller has no transformation"); // If the request time is before contract expiration then return the transformed identifier. Else, return the // original price identifier. if (requestTime < ExpiringContractInterface(msg.sender).expirationTimestamp()) { return financialProductTransformedIdentifiers[msg.sender]; } else { return identifier; } } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.8.0; pragma abicoder v2; import "./FinancialProductLibrary.sol"; import "../../../common/implementation/Lockable.sol"; /** * @title Post-Expiration Identifier Transformation Financial Product Library * @notice Adds custom identifier transformation to enable a financial contract to use two different identifiers, depending * on when a price request is made. If the request is made at or after expiration then a transformation is made to the identifier * & if it is before expiration then the original identifier is returned. This library enables self referential * TWAP identifier to be used on synthetics pre-expiration, in conjunction with a separate identifier at expiration. */ contract PostExpirationIdentifierTransformationFinancialProductLibrary is FinancialProductLibrary, Lockable { mapping(address => bytes32) financialProductTransformedIdentifiers; /** * @notice Enables the deployer of the library to set the transformed identifier for an associated financial product. * @param financialProduct address of the financial product. * @param transformedIdentifier the identifier for the financial product to be used if the contract is post expiration. * @dev Note: a) Any address can set identifier transformations b) The identifier can't be set to blank. c) A * transformed price can only be set once to prevent the deployer from changing it after the fact. d) financialProduct * must expose an expirationTimestamp method. */ function setFinancialProductTransformedIdentifier(address financialProduct, bytes32 transformedIdentifier) public nonReentrant() { require(transformedIdentifier != "", "Cant set to empty transformation"); require(financialProductTransformedIdentifiers[financialProduct] == "", "Transformation already set"); require(ExpiringContractInterface(financialProduct).expirationTimestamp() != 0, "Invalid EMP contract"); financialProductTransformedIdentifiers[financialProduct] = transformedIdentifier; } /** * @notice Returns the transformed identifier associated with a given financial product address. * @param financialProduct address of the financial product. * @return transformed identifier for the associated financial product. */ function getTransformedIdentifierForFinancialProduct(address financialProduct) public view nonReentrantView() returns (bytes32) { return financialProductTransformedIdentifiers[financialProduct]; } /** * @notice Returns a transformed price identifier if the contract is post-expiration and no transformation if pre. * @param identifier input price identifier to be transformed. * @param requestTime timestamp the identifier is to be used at. * @return transformedPriceIdentifier the input price identifier with the transformation logic applied to it. */ function transformPriceIdentifier(bytes32 identifier, uint256 requestTime) public view override nonReentrantView() returns (bytes32) { require(financialProductTransformedIdentifiers[msg.sender] != "", "Caller has no transformation"); // If the request time is after contract expiration then return the transformed identifier. Else, return the // original price identifier. if (requestTime < ExpiringContractInterface(msg.sender).expirationTimestamp()) { return identifier; } else { return financialProductTransformedIdentifiers[msg.sender]; } } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.8.0; pragma abicoder v2; import "./FinancialProductLibrary.sol"; import "../../../common/implementation/Lockable.sol"; /** * @title KPI Options Financial Product Library * @notice Adds custom tranformation logic to modify the price and collateral requirement behavior of the expiring multi party contract. * If a price request is made pre-expiry, the price should always be set to 2 and the collateral requirement should be set to 1. * Post-expiry, the collateral requirement is left as 1 and the price is left unchanged. */ contract KpiOptionsFinancialProductLibrary is FinancialProductLibrary, Lockable { using FixedPoint for FixedPoint.Unsigned; mapping(address => FixedPoint.Unsigned) financialProductTransformedPrices; /** * @notice Enables any address to set the transformed pricxe for an associated financial product. * @param financialProduct address of the financial product. * @param transformedPrice the price for the financial product to be used if the contract is pre-expiration. * @dev Note: a) Any address can set identifier transformations b) The price can't be set to blank. * c) A transformed price can only be set once to prevent the deployer from changing it after the fact. * d) financialProduct must expose an expirationTimestamp method. */ function setFinancialProductTransformedPrice(address financialProduct, FixedPoint.Unsigned memory transformedPrice) public nonReentrant() { require(transformedPrice.isGreaterThan(0), "Cant set price of 0"); require(financialProductTransformedPrices[financialProduct].isEqual(0), "Price already set"); require(ExpiringContractInterface(financialProduct).expirationTimestamp() != 0, "Invalid EMP contract"); financialProductTransformedPrices[financialProduct] = transformedPrice; } /** * @notice Returns the transformed price associated with a given financial product address. * @param financialProduct address of the financial product. * @return transformed price for the associated financial product. */ function getTransformedPriceForFinancialProduct(address financialProduct) public view nonReentrantView() returns (FixedPoint.Unsigned memory) { return financialProductTransformedPrices[financialProduct]; } /** * @notice Returns a transformed price for pre-expiry price requests. * @param oraclePrice price from the oracle to be transformed. * @param requestTime timestamp the oraclePrice was requested at. * @return transformedPrice the input oracle price with the price transformation logic applied to it. */ function transformPrice(FixedPoint.Unsigned memory oraclePrice, uint256 requestTime) public view override nonReentrantView() returns (FixedPoint.Unsigned memory) { FixedPoint.Unsigned memory transformedPrice = financialProductTransformedPrices[msg.sender]; require(transformedPrice.isGreaterThan(0), "Caller has no transformation"); // If price request is made before expiry, return transformed price. Post-expiry, leave unchanged. // if (requestTime < ExpiringContractInterface(msg.sender).expirationTimestamp()) { return transformedPrice; } else { return oraclePrice; } } /** * @notice Returns a transformed collateral requirement that is set to be equivalent to 2 tokens pre-expiry. * @param oraclePrice price from the oracle to transform the collateral requirement. * @param collateralRequirement financial products collateral requirement to be scaled to a flat rate. * @return transformedCollateralRequirement the input collateral requirement with the transformation logic applied to it. */ function transformCollateralRequirement( FixedPoint.Unsigned memory oraclePrice, FixedPoint.Unsigned memory collateralRequirement ) public view override nonReentrantView() returns (FixedPoint.Unsigned memory) { // Always return 1. return FixedPoint.fromUnscaledUint(1); } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.8.0; pragma abicoder v2; import "./FinancialProductLibrary.sol"; import "../../../common/implementation/Lockable.sol"; /** * @title CoveredCall Financial Product Library * @notice Adds custom price transformation logic to modify the behavior of the expiring multi party contract. The * contract holds say 1 WETH in collateral and pays out a portion of that, at expiry, if ETHUSD is above a set strike. If * ETHUSD is below that strike, the contract pays out 0. The fraction paid out if above the strike is defined by * (oraclePrice - strikePrice) / oraclePrice; * Example: expiry is DEC 31. Strike is $400. Each token is backed by 1 WETH. * If ETHUSD = $600 at expiry, the call is $200 in the money, and the contract pays out 0.333 WETH (worth $200). * If ETHUSD = $800 at expiry, the call is $400 in the money, and the contract pays out 0.5 WETH (worth $400). * If ETHUSD =< $400 at expiry, the call is out of the money, and the contract pays out 0 WETH. */ contract CoveredCallFinancialProductLibrary is FinancialProductLibrary, Lockable { using FixedPoint for FixedPoint.Unsigned; mapping(address => FixedPoint.Unsigned) private financialProductStrikes; /** * @notice Enables any address to set the strike price for an associated financial product. * @param financialProduct address of the financial product. * @param strikePrice the strike price for the covered call to be applied to the financial product. * @dev Note: a) Any address can set the initial strike price b) A strike price cannot be 0. * c) A strike price can only be set once to prevent the deployer from changing the strike after the fact. * d) For safety, a strike price should be set before depositing any synthetic tokens in a liquidity pool. * e) financialProduct must expose an expirationTimestamp method. */ function setFinancialProductStrike(address financialProduct, FixedPoint.Unsigned memory strikePrice) public nonReentrant() { require(strikePrice.isGreaterThan(0), "Cant set 0 strike"); require(financialProductStrikes[financialProduct].isEqual(0), "Strike already set"); require(ExpiringContractInterface(financialProduct).expirationTimestamp() != 0, "Invalid EMP contract"); financialProductStrikes[financialProduct] = strikePrice; } /** * @notice Returns the strike price associated with a given financial product address. * @param financialProduct address of the financial product. * @return strikePrice for the associated financial product. */ function getStrikeForFinancialProduct(address financialProduct) public view nonReentrantView() returns (FixedPoint.Unsigned memory) { return financialProductStrikes[financialProduct]; } /** * @notice Returns a transformed price by applying the call option payout structure. * @param oraclePrice price from the oracle to be transformed. * @param requestTime timestamp the oraclePrice was requested at. * @return transformedPrice the input oracle price with the price transformation logic applied to it. */ function transformPrice(FixedPoint.Unsigned memory oraclePrice, uint256 requestTime) public view override nonReentrantView() returns (FixedPoint.Unsigned memory) { FixedPoint.Unsigned memory strike = financialProductStrikes[msg.sender]; require(strike.isGreaterThan(0), "Caller has no strike"); // If price request is made before expiry, return 1. Thus we can keep the contract 100% collateralized with // each token backed 1:1 by collateral currency. if (requestTime < ExpiringContractInterface(msg.sender).expirationTimestamp()) { return FixedPoint.fromUnscaledUint(1); } if (oraclePrice.isLessThanOrEqual(strike)) { return FixedPoint.fromUnscaledUint(0); } else { // Token expires to be worth the fraction of a collateral token that's in the money. // eg if ETHUSD is $500 and strike is $400, token is redeemable for 100/500 = 0.2 WETH (worth $100). // Note: oraclePrice cannot be 0 here because it would always satisfy the if above because 0 <= x is always // true. return (oraclePrice.sub(strike)).div(oraclePrice); } } /** * @notice Returns a transformed collateral requirement by applying the covered call payout structure. * @param oraclePrice price from the oracle to transform the collateral requirement. * @param collateralRequirement financial products collateral requirement to be scaled according to price and strike. * @return transformedCollateralRequirement the input collateral requirement with the transformation logic applied to it. */ function transformCollateralRequirement( FixedPoint.Unsigned memory oraclePrice, FixedPoint.Unsigned memory collateralRequirement ) public view override nonReentrantView() returns (FixedPoint.Unsigned memory) { FixedPoint.Unsigned memory strike = financialProductStrikes[msg.sender]; require(strike.isGreaterThan(0), "Caller has no strike"); // Always return 1 because option must be collateralized by 1 token. return FixedPoint.fromUnscaledUint(1); } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.8.0; import "../implementation/Lockable.sol"; import "./ReentrancyAttack.sol"; // Tests reentrancy guards defined in Lockable.sol. // Extends https://github.com/OpenZeppelin/openzeppelin-contracts/blob/v3.0.1/contracts/mocks/ReentrancyMock.sol. contract ReentrancyMock is Lockable { uint256 public counter; constructor() { counter = 0; } function callback() external nonReentrant { _count(); } function countAndSend(ReentrancyAttack attacker) external nonReentrant { _count(); bytes4 func = bytes4(keccak256("callback()")); attacker.callSender(func); } function countAndCall(ReentrancyAttack attacker) external nonReentrant { _count(); bytes4 func = bytes4(keccak256("getCount()")); attacker.callSender(func); } function countLocalRecursive(uint256 n) public nonReentrant { if (n > 0) { _count(); countLocalRecursive(n - 1); } } function countThisRecursive(uint256 n) public nonReentrant { if (n > 0) { _count(); // solhint-disable-next-line avoid-low-level-calls (bool success, ) = address(this).call(abi.encodeWithSignature("countThisRecursive(uint256)", n - 1)); require(success, "ReentrancyMock: failed call"); } } function countLocalCall() public nonReentrant { getCount(); } function countThisCall() public nonReentrant { // solhint-disable-next-line avoid-low-level-calls (bool success, ) = address(this).call(abi.encodeWithSignature("getCount()")); require(success, "ReentrancyMock: failed call"); } function getCount() public view nonReentrantView returns (uint256) { return counter; } function _count() private { counter += 1; } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.8.0; // Tests reentrancy guards defined in Lockable.sol. // Copied from https://github.com/OpenZeppelin/openzeppelin-contracts/blob/v3.0.1/contracts/mocks/ReentrancyAttack.sol. contract ReentrancyAttack { function callSender(bytes4 data) public { // solhint-disable-next-line avoid-low-level-calls (bool success, ) = msg.sender.call(abi.encodeWithSelector(data)); require(success, "ReentrancyAttack: failed call"); } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.8.0; import "@openzeppelin/contracts/utils/math/SafeMath.sol"; import "@uniswap/v2-core/contracts/interfaces/IUniswapV2Pair.sol"; import "@uniswap/lib/contracts/libraries/Babylonian.sol"; import "@uniswap/lib/contracts/libraries/TransferHelper.sol"; import "@uniswap/v2-periphery/contracts/interfaces/IUniswapV2Router01.sol"; /** * @title UniswapBroker * @notice Trading contract used to arb uniswap pairs to a desired "true" price. Intended use is to arb UMA perpetual * synthetics that trade off peg. This implementation can ber used in conjunction with a DSProxy contract to atomically * swap and move a uniswap market. */ contract UniswapBroker { using SafeMath for uint256; /** * @notice Swaps an amount of either token such that the trade results in the uniswap pair's price being as close as * possible to the truePrice. * @dev True price is expressed in the ratio of token A to token B. * @dev The caller must approve this contract to spend whichever token is intended to be swapped. * @param tradingAsEOA bool to indicate if the UniswapBroker is being called by a DSProxy or an EOA. * @param uniswapRouter address of the uniswap router used to facilitate trades. * @param uniswapFactory address of the uniswap factory used to fetch current pair reserves. * @param swappedTokens array of addresses which are to be swapped. The order does not matter as the function will figure * out which tokens need to be exchanged to move the market to the desired "true" price. * @param truePriceTokens array of unit used to represent the true price. 0th value is the numerator of the true price * and the 1st value is the the denominator of the true price. * @param maxSpendTokens array of unit to represent the max to spend in the two tokens. * @param to recipient of the trade proceeds. * @param deadline to limit when the trade can execute. If the tx is mined after this timestamp then revert. */ function swapToPrice( bool tradingAsEOA, address uniswapRouter, address uniswapFactory, address[2] memory swappedTokens, uint256[2] memory truePriceTokens, uint256[2] memory maxSpendTokens, address to, uint256 deadline ) public { IUniswapV2Router01 router = IUniswapV2Router01(uniswapRouter); // true price is expressed as a ratio, so both values must be non-zero require(truePriceTokens[0] != 0 && truePriceTokens[1] != 0, "SwapToPrice: ZERO_PRICE"); // caller can specify 0 for either if they wish to swap in only one direction, but not both require(maxSpendTokens[0] != 0 || maxSpendTokens[1] != 0, "SwapToPrice: ZERO_SPEND"); bool aToB; uint256 amountIn; { (uint256 reserveA, uint256 reserveB) = getReserves(uniswapFactory, swappedTokens[0], swappedTokens[1]); (aToB, amountIn) = computeTradeToMoveMarket(truePriceTokens[0], truePriceTokens[1], reserveA, reserveB); } require(amountIn > 0, "SwapToPrice: ZERO_AMOUNT_IN"); // spend up to the allowance of the token in uint256 maxSpend = aToB ? maxSpendTokens[0] : maxSpendTokens[1]; if (amountIn > maxSpend) { amountIn = maxSpend; } address tokenIn = aToB ? swappedTokens[0] : swappedTokens[1]; address tokenOut = aToB ? swappedTokens[1] : swappedTokens[0]; TransferHelper.safeApprove(tokenIn, address(router), amountIn); if (tradingAsEOA) TransferHelper.safeTransferFrom(tokenIn, msg.sender, address(this), amountIn); address[] memory path = new address[](2); path[0] = tokenIn; path[1] = tokenOut; router.swapExactTokensForTokens( amountIn, 0, // amountOutMin: we can skip computing this number because the math is tested within the uniswap tests. path, to, deadline ); } /** * @notice Given the "true" price a token (represented by truePriceTokenA/truePriceTokenB) and the reservers in the * uniswap pair, calculate: a) the direction of trade (aToB) and b) the amount needed to trade (amountIn) to move * the pool price to be equal to the true price. * @dev Note that this method uses the Babylonian square root method which has a small margin of error which will * result in a small over or under estimation on the size of the trade needed. * @param truePriceTokenA the nominator of the true price. * @param truePriceTokenB the denominator of the true price. * @param reserveA number of token A in the pair reserves * @param reserveB number of token B in the pair reserves */ // function computeTradeToMoveMarket( uint256 truePriceTokenA, uint256 truePriceTokenB, uint256 reserveA, uint256 reserveB ) public pure returns (bool aToB, uint256 amountIn) { aToB = FullMath.mulDiv(reserveA, truePriceTokenB, reserveB) < truePriceTokenA; uint256 invariant = reserveA.mul(reserveB); // The trade ∆a of token a required to move the market to some desired price P' from the current price P can be // found with ∆a=(kP')^1/2-Ra. uint256 leftSide = Babylonian.sqrt( FullMath.mulDiv( invariant, aToB ? truePriceTokenA : truePriceTokenB, aToB ? truePriceTokenB : truePriceTokenA ) ); uint256 rightSide = (aToB ? reserveA : reserveB); if (leftSide < rightSide) return (false, 0); // compute the amount that must be sent to move the price back to the true price. amountIn = leftSide.sub(rightSide); } // The methods below are taken from https://github.com/Uniswap/uniswap-v2-periphery/blob/master/contracts/libraries/UniswapV2Library.sol // We could import this library into this contract but this library is dependent Uniswap's SafeMath, which is bound // to solidity 6.6.6. UMA uses 0.8.0 and so a modified version is needed to accomidate this solidity version. function getReserves( address factory, address tokenA, address tokenB ) public view returns (uint256 reserveA, uint256 reserveB) { (address token0, ) = sortTokens(tokenA, tokenB); (uint256 reserve0, uint256 reserve1, ) = IUniswapV2Pair(pairFor(factory, tokenA, tokenB)).getReserves(); (reserveA, reserveB) = tokenA == token0 ? (reserve0, reserve1) : (reserve1, reserve0); } function sortTokens(address tokenA, address tokenB) internal pure returns (address token0, address token1) { require(tokenA != tokenB, "UniswapV2Library: IDENTICAL_ADDRESSES"); (token0, token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA); require(token0 != address(0), "UniswapV2Library: ZERO_ADDRESS"); } // calculates the CREATE2 address for a pair without making any external calls function pairFor( address factory, address tokenA, address tokenB ) internal pure returns (address pair) { (address token0, address token1) = sortTokens(tokenA, tokenB); pair = address( uint160( uint256( keccak256( abi.encodePacked( hex"ff", factory, keccak256(abi.encodePacked(token0, token1)), hex"96e8ac4277198ff8b6f785478aa9a39f403cb768dd02cbee326c3e7da348845f" // init code hash ) ) ) ) ); } } // The library below is taken from @uniswap/lib/contracts/libraries/FullMath.sol. It has been modified to work with solidity 0.8 library FullMath { /// @notice Calculates floor(a×b÷denominator) with full precision. Throws if result overflows a uint256 or denominator == 0 /// @param a The multiplicand /// @param b The multiplier /// @param denominator The divisor /// @return result The 256-bit result /// @dev Credit to Remco Bloemen under MIT license https://xn--2-umb.com/21/muldiv function mulDiv( uint256 a, uint256 b, uint256 denominator ) internal pure returns (uint256 result) { // 512-bit multiply [prod1 prod0] = a * b // Compute the product mod 2**256 and mod 2**256 - 1 // then use the Chinese Remainder Theorem to reconstruct // the 512 bit result. The result is stored in two 256 // variables such that product = prod1 * 2**256 + prod0 uint256 prod0; // Least significant 256 bits of the product uint256 prod1; // Most significant 256 bits of the product assembly { let mm := mulmod(a, b, not(0)) prod0 := mul(a, b) prod1 := sub(sub(mm, prod0), lt(mm, prod0)) } // Handle non-overflow cases, 256 by 256 division if (prod1 == 0) { require(denominator > 0); assembly { result := div(prod0, denominator) } return result; } // Make sure the result is less than 2**256. // Also prevents denominator == 0 require(denominator > prod1); /////////////////////////////////////////////// // 512 by 256 division. /////////////////////////////////////////////// // Make division exact by subtracting the remainder from [prod1 prod0] // Compute remainder using mulmod uint256 remainder; assembly { remainder := mulmod(a, b, denominator) } // Subtract 256 bit number from 512 bit number assembly { prod1 := sub(prod1, gt(remainder, prod0)) prod0 := sub(prod0, remainder) } // Factor powers of two out of denominator // Compute largest power of two divisor of denominator. // Always >= 1. uint256 twos = denominator & (~denominator + 1); // Divide denominator by power of two assembly { denominator := div(denominator, twos) } // Divide [prod1 prod0] by the factors of two assembly { prod0 := div(prod0, twos) } // Shift in bits from prod1 into prod0. For this we need // to flip `twos` such that it is 2**256 / twos. // If twos is zero, then it becomes one assembly { twos := add(div(sub(0, twos), twos), 1) } prod0 |= prod1 * twos; // Invert denominator mod 2**256 // Now that denominator is an odd number, it has an inverse // modulo 2**256 such that denominator * inv = 1 mod 2**256. // Compute the inverse by starting with a seed that is correct // correct for four bits. That is, denominator * inv = 1 mod 2**4 uint256 inv = (3 * denominator) ^ 2; // Now use Newton-Raphson iteration to improve the precision. // Thanks to Hensel's lifting lemma, this also works in modular // arithmetic, doubling the correct bits in each step. inv *= 2 - denominator * inv; // inverse mod 2**8 inv *= 2 - denominator * inv; // inverse mod 2**16 inv *= 2 - denominator * inv; // inverse mod 2**32 inv *= 2 - denominator * inv; // inverse mod 2**64 inv *= 2 - denominator * inv; // inverse mod 2**128 inv *= 2 - denominator * inv; // inverse mod 2**256 // Because the division is now exact we can divide by multiplying // with the modular inverse of denominator. This will give us the // correct result modulo 2**256. Since the precoditions guarantee // that the outcome is less than 2**256, this is the final result. // We don't need to compute the high bits of the result and prod1 // is no longer required. result = prod0 * inv; return result; } /// @notice Calculates ceil(a×b÷denominator) with full precision. Throws if result overflows a uint256 or denominator == 0 /// @param a The multiplicand /// @param b The multiplier /// @param denominator The divisor /// @return result The 256-bit result function mulDivRoundingUp( uint256 a, uint256 b, uint256 denominator ) internal pure returns (uint256 result) { result = mulDiv(a, b, denominator); if (mulmod(a, b, denominator) > 0) { require(result < type(uint256).max); result++; } } } pragma solidity >=0.5.0; interface IUniswapV2Pair { event Approval(address indexed owner, address indexed spender, uint value); event Transfer(address indexed from, address indexed to, uint value); function name() external pure returns (string memory); function symbol() external pure returns (string memory); function decimals() external pure returns (uint8); function totalSupply() external view returns (uint); function balanceOf(address owner) external view returns (uint); function allowance(address owner, address spender) external view returns (uint); function approve(address spender, uint value) external returns (bool); function transfer(address to, uint value) external returns (bool); function transferFrom(address from, address to, uint value) external returns (bool); function DOMAIN_SEPARATOR() external view returns (bytes32); function PERMIT_TYPEHASH() external pure returns (bytes32); function nonces(address owner) external view returns (uint); function permit(address owner, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) external; event Mint(address indexed sender, uint amount0, uint amount1); event Burn(address indexed sender, uint amount0, uint amount1, address indexed to); event Swap( address indexed sender, uint amount0In, uint amount1In, uint amount0Out, uint amount1Out, address indexed to ); event Sync(uint112 reserve0, uint112 reserve1); function MINIMUM_LIQUIDITY() external pure returns (uint); function factory() external view returns (address); function token0() external view returns (address); function token1() external view returns (address); function getReserves() external view returns (uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast); function price0CumulativeLast() external view returns (uint); function price1CumulativeLast() external view returns (uint); function kLast() external view returns (uint); function mint(address to) external returns (uint liquidity); function burn(address to) external returns (uint amount0, uint amount1); function swap(uint amount0Out, uint amount1Out, address to, bytes calldata data) external; function skim(address to) external; function sync() external; function initialize(address, address) external; } // SPDX-License-Identifier: GPL-3.0-or-later pragma solidity >=0.4.0; // computes square roots using the babylonian method // https://en.wikipedia.org/wiki/Methods_of_computing_square_roots#Babylonian_method library Babylonian { // credit for this implementation goes to // https://github.com/abdk-consulting/abdk-libraries-solidity/blob/master/ABDKMath64x64.sol#L687 function sqrt(uint256 x) internal pure returns (uint256) { if (x == 0) return 0; // this block is equivalent to r = uint256(1) << (BitMath.mostSignificantBit(x) / 2); // however that code costs significantly more gas uint256 xx = x; uint256 r = 1; if (xx >= 0x100000000000000000000000000000000) { xx >>= 128; r <<= 64; } if (xx >= 0x10000000000000000) { xx >>= 64; r <<= 32; } if (xx >= 0x100000000) { xx >>= 32; r <<= 16; } if (xx >= 0x10000) { xx >>= 16; r <<= 8; } if (xx >= 0x100) { xx >>= 8; r <<= 4; } if (xx >= 0x10) { xx >>= 4; r <<= 2; } if (xx >= 0x8) { r <<= 1; } r = (r + x / r) >> 1; r = (r + x / r) >> 1; r = (r + x / r) >> 1; r = (r + x / r) >> 1; r = (r + x / r) >> 1; r = (r + x / r) >> 1; r = (r + x / r) >> 1; // Seven iterations should be enough uint256 r1 = x / r; return (r < r1 ? r : r1); } } // SPDX-License-Identifier: GPL-3.0-or-later pragma solidity >=0.6.0; // helper methods for interacting with ERC20 tokens and sending ETH that do not consistently return true/false library TransferHelper { function safeApprove( address token, address to, uint256 value ) internal { // bytes4(keccak256(bytes('approve(address,uint256)'))); (bool success, bytes memory data) = token.call(abi.encodeWithSelector(0x095ea7b3, to, value)); require( success && (data.length == 0 || abi.decode(data, (bool))), 'TransferHelper::safeApprove: approve failed' ); } function safeTransfer( address token, address to, uint256 value ) internal { // bytes4(keccak256(bytes('transfer(address,uint256)'))); (bool success, bytes memory data) = token.call(abi.encodeWithSelector(0xa9059cbb, to, value)); require( success && (data.length == 0 || abi.decode(data, (bool))), 'TransferHelper::safeTransfer: transfer failed' ); } function safeTransferFrom( address token, address from, address to, uint256 value ) internal { // bytes4(keccak256(bytes('transferFrom(address,address,uint256)'))); (bool success, bytes memory data) = token.call(abi.encodeWithSelector(0x23b872dd, from, to, value)); require( success && (data.length == 0 || abi.decode(data, (bool))), 'TransferHelper::transferFrom: transferFrom failed' ); } function safeTransferETH(address to, uint256 value) internal { (bool success, ) = to.call{value: value}(new bytes(0)); require(success, 'TransferHelper::safeTransferETH: ETH transfer failed'); } } 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: AGPL-3.0-only pragma solidity ^0.8.0; pragma abicoder v2; import "@openzeppelin/contracts/utils/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@uniswap/lib/contracts/libraries/TransferHelper.sol"; import "@uniswap/v2-periphery/contracts/interfaces/IUniswapV2Router01.sol"; import "../../common/implementation/FixedPoint.sol"; /** * @title ReserveCurrencyLiquidator * @notice Helper contract to enable a liquidator to hold one reserver currency and liquidate against any number of * financial contracts. Is assumed to be called by a DSProxy which holds reserve currency. */ contract ReserveCurrencyLiquidator { using SafeMath for uint256; using FixedPoint for FixedPoint.Unsigned; /** * @notice Swaps required amount of reserve currency to collateral currency which is then used to mint tokens to * liquidate a position within one transaction. * @dev After the liquidation is done the DSProxy that called this method will have an open position AND pending * liquidation within the financial contract. The bot using the DSProxy should withdraw the liquidation once it has * passed liveness. At this point the position can be manually unwound. * @dev Any synthetics & collateral that the DSProxy already has are considered in the amount swapped and minted. * These existing tokens will be used first before any swaps or mints are done. * @dev If there is a token shortfall (either from not enough reserve to buy sufficient collateral or not enough * collateral to begins with or due to slippage) the script will liquidate as much as possible given the reserves. * @param uniswapRouter address of the uniswap router used to facilitate trades. * @param financialContract address of the financial contract on which the liquidation is occurring. * @param reserveCurrency address of the token to swap for collateral. THis is the common currency held by the DSProxy. * @param liquidatedSponsor address of the sponsor to be liquidated. * @param maxReserveTokenSpent maximum number of reserve tokens to spend in the trade. Bounds slippage. * @param minCollateralPerTokenLiquidated abort the liquidation if the position's collateral per token is below this value. * @param maxCollateralPerTokenLiquidated abort the liquidation if the position's collateral per token exceeds this value. * @param maxTokensToLiquidate max number of tokens to liquidate. For a full liquidation this is the full position debt. * @param deadline abort the trade and liquidation if the transaction is mined after this timestamp. **/ function swapMintLiquidate( address uniswapRouter, address financialContract, address reserveCurrency, address liquidatedSponsor, FixedPoint.Unsigned calldata maxReserveTokenSpent, FixedPoint.Unsigned calldata minCollateralPerTokenLiquidated, FixedPoint.Unsigned calldata maxCollateralPerTokenLiquidated, FixedPoint.Unsigned calldata maxTokensToLiquidate, uint256 deadline ) public { IFinancialContract fc = IFinancialContract(financialContract); // 1. Calculate the token shortfall. This is the synthetics to liquidate minus any synthetics the DSProxy already // has. If this number is negative(balance large than synthetics to liquidate) the return 0 (no shortfall). FixedPoint.Unsigned memory tokenShortfall = subOrZero(maxTokensToLiquidate, getSyntheticBalance(fc)); // 2. Calculate how much collateral is needed to make up the token shortfall from minting new synthetics. FixedPoint.Unsigned memory gcr = fc.pfc().divCeil(fc.totalTokensOutstanding()); FixedPoint.Unsigned memory collateralToMintShortfall = tokenShortfall.mulCeil(gcr); // 3. Calculate the total collateral required. This considers the final fee for the given collateral type + any // collateral needed to mint the token short fall. FixedPoint.Unsigned memory totalCollateralRequired = getFinalFee(fc).add(collateralToMintShortfall); // 4.a. Calculate how much collateral needs to be purchased. If the DSProxy already has some collateral then this // will factor this in. If the DSProxy has more collateral than the total amount required the purchased = 0. FixedPoint.Unsigned memory collateralToBePurchased = subOrZero(totalCollateralRequired, getCollateralBalance(fc)); // 4.b. If there is some collateral to be purchased, execute a trade on uniswap to meet the shortfall. // Note the path assumes a direct route from the reserve currency to the collateral currency. if (collateralToBePurchased.isGreaterThan(0) && reserveCurrency != fc.collateralCurrency()) { IUniswapV2Router01 router = IUniswapV2Router01(uniswapRouter); address[] memory path = new address[](2); path[0] = reserveCurrency; path[1] = fc.collateralCurrency(); TransferHelper.safeApprove(reserveCurrency, address(router), maxReserveTokenSpent.rawValue); router.swapTokensForExactTokens( collateralToBePurchased.rawValue, maxReserveTokenSpent.rawValue, path, address(this), deadline ); } // 4.c. If at this point we were not able to get the required amount of collateral (due to insufficient reserve // or not enough collateral in the contract) the script should try to liquidate as much as it can regardless. // Update the values of total collateral to the current collateral balance and re-compute the tokenShortfall // as the maximum tokens that could be liquidated at the current GCR. if (totalCollateralRequired.isGreaterThan(getCollateralBalance(fc))) { totalCollateralRequired = getCollateralBalance(fc); collateralToMintShortfall = totalCollateralRequired.sub(getFinalFee(fc)); tokenShortfall = collateralToMintShortfall.divCeil(gcr); } // 5. Mint the shortfall synthetics with collateral. Note we are minting at the GCR. // If the DSProxy already has enough tokens (tokenShortfall = 0) we still preform the approval on the collateral // currency as this is needed to pay the final fee in the liquidation tx. TransferHelper.safeApprove(fc.collateralCurrency(), address(fc), totalCollateralRequired.rawValue); if (tokenShortfall.isGreaterThan(0)) fc.create(collateralToMintShortfall, tokenShortfall); // The liquidatableTokens is either the maxTokensToLiquidate (if we were able to buy/mint enough) or the full // token token balance at this point if there was a shortfall. FixedPoint.Unsigned memory liquidatableTokens = maxTokensToLiquidate; if (maxTokensToLiquidate.isGreaterThan(getSyntheticBalance(fc))) liquidatableTokens = getSyntheticBalance(fc); // 6. Liquidate position with newly minted synthetics. TransferHelper.safeApprove(fc.tokenCurrency(), address(fc), liquidatableTokens.rawValue); fc.createLiquidation( liquidatedSponsor, minCollateralPerTokenLiquidated, maxCollateralPerTokenLiquidated, liquidatableTokens, deadline ); } // Helper method to work around subtraction overflow in the case of: a - b with b > a. function subOrZero(FixedPoint.Unsigned memory a, FixedPoint.Unsigned memory b) internal pure returns (FixedPoint.Unsigned memory) { return b.isGreaterThanOrEqual(a) ? FixedPoint.fromUnscaledUint(0) : a.sub(b); } // Helper method to return the current final fee for a given financial contract instance. function getFinalFee(IFinancialContract fc) internal returns (FixedPoint.Unsigned memory) { return IStore(IFinder(fc.finder()).getImplementationAddress("Store")).computeFinalFee(fc.collateralCurrency()); } // Helper method to return the collateral balance of this contract. function getCollateralBalance(IFinancialContract fc) internal returns (FixedPoint.Unsigned memory) { return FixedPoint.Unsigned(IERC20(fc.collateralCurrency()).balanceOf(address(this))); } // Helper method to return the synthetic balance of this contract. function getSyntheticBalance(IFinancialContract fc) internal returns (FixedPoint.Unsigned memory) { return FixedPoint.Unsigned(IERC20(fc.tokenCurrency()).balanceOf(address(this))); } } // Define some simple interfaces for dealing with UMA contracts. interface IFinancialContract { struct PositionData { FixedPoint.Unsigned tokensOutstanding; uint256 withdrawalRequestPassTimestamp; FixedPoint.Unsigned withdrawalRequestAmount; FixedPoint.Unsigned rawCollateral; uint256 transferPositionRequestPassTimestamp; } function positions(address sponsor) external returns (PositionData memory); function collateralCurrency() external returns (address); function tokenCurrency() external returns (address); function finder() external returns (address); function pfc() external returns (FixedPoint.Unsigned memory); function totalTokensOutstanding() external returns (FixedPoint.Unsigned memory); function create(FixedPoint.Unsigned memory collateralAmount, FixedPoint.Unsigned memory numTokens) external; function createLiquidation( address sponsor, FixedPoint.Unsigned calldata minCollateralPerToken, FixedPoint.Unsigned calldata maxCollateralPerToken, FixedPoint.Unsigned calldata maxTokensToLiquidate, uint256 deadline ) external returns ( uint256 liquidationId, FixedPoint.Unsigned memory tokensLiquidated, FixedPoint.Unsigned memory finalFeeBond ); } interface IStore { function computeFinalFee(address currency) external returns (FixedPoint.Unsigned memory); } interface IFinder { function getImplementationAddress(bytes32 interfaceName) external view returns (address); } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.8.0; pragma abicoder v2; import "../../common/implementation/FixedPoint.sol"; import "@uniswap/lib/contracts/libraries/TransferHelper.sol"; // Simple contract used to redeem tokens using a DSProxy from an emp. contract TokenRedeemer { function redeem(address financialContractAddress, FixedPoint.Unsigned memory numTokens) public returns (FixedPoint.Unsigned memory) { IFinancialContract fc = IFinancialContract(financialContractAddress); TransferHelper.safeApprove(fc.tokenCurrency(), financialContractAddress, numTokens.rawValue); return fc.redeem(numTokens); } } interface IFinancialContract { function redeem(FixedPoint.Unsigned memory numTokens) external returns (FixedPoint.Unsigned memory amountWithdrawn); function tokenCurrency() external returns (address); } /* MultiRoleTest contract. */ // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.8.0; import "../implementation/MultiRole.sol"; // The purpose of this contract is to make the MultiRole creation methods externally callable for testing purposes. contract MultiRoleTest is MultiRole { function createSharedRole( uint256 roleId, uint256 managingRoleId, address[] calldata initialMembers ) external { _createSharedRole(roleId, managingRoleId, initialMembers); } function createExclusiveRole( uint256 roleId, uint256 managingRoleId, address initialMember ) external { _createExclusiveRole(roleId, managingRoleId, initialMember); } // solhint-disable-next-line no-empty-blocks function revertIfNotHoldingRole(uint256 roleId) external view onlyRoleHolder(roleId) {} } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.8.0; import "../implementation/Testable.sol"; // TestableTest is derived from the abstract contract Testable for testing purposes. contract TestableTest is Testable { // solhint-disable-next-line no-empty-blocks constructor(address _timerAddress) Testable(_timerAddress) {} function getTestableTimeAndBlockTime() external view returns (uint256 testableTime, uint256 blockTime) { // solhint-disable-next-line not-rely-on-time return (getCurrentTime(), block.timestamp); } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.8.0; import "../interfaces/VaultInterface.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; /** * @title Mock for yearn-style vaults for use in tests. */ contract VaultMock is VaultInterface { IERC20 public override token; uint256 private pricePerFullShare = 0; constructor(IERC20 _token) { token = _token; } function getPricePerFullShare() external view override returns (uint256) { return pricePerFullShare; } function setPricePerFullShare(uint256 _pricePerFullShare) external { pricePerFullShare = _pricePerFullShare; } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.8.0; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; /** * @title Interface for Yearn-style vaults. * @dev This only contains the methods/events that we use in our contracts or offchain infrastructure. */ abstract contract VaultInterface { // Return the underlying token. function token() external view virtual returns (IERC20); // Gets the number of return tokens that a "share" of this vault is worth. function getPricePerFullShare() external view virtual returns (uint256); } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.8.0; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; /** * @title Implements only the required ERC20 methods. This contract is used * test how contracts handle ERC20 contracts that have not implemented `decimals()` * @dev Mostly copied from Consensys EIP-20 implementation: * https://github.com/ConsenSys/Tokens/blob/fdf687c69d998266a95f15216b1955a4965a0a6d/contracts/eip20/EIP20.sol */ contract BasicERC20 is IERC20 { uint256 private constant MAX_UINT256 = 2**256 - 1; mapping(address => uint256) public balances; mapping(address => mapping(address => uint256)) public allowed; uint256 private _totalSupply; constructor(uint256 _initialAmount) { balances[msg.sender] = _initialAmount; _totalSupply = _initialAmount; } function totalSupply() public view override returns (uint256) { return _totalSupply; } function transfer(address _to, uint256 _value) public override returns (bool success) { require(balances[msg.sender] >= _value); balances[msg.sender] -= _value; balances[_to] += _value; emit Transfer(msg.sender, _to, _value); return true; } function transferFrom( address _from, address _to, uint256 _value ) public override returns (bool success) { uint256 allowance = allowed[_from][msg.sender]; require(balances[_from] >= _value && allowance >= _value); balances[_to] += _value; balances[_from] -= _value; if (allowance < MAX_UINT256) { allowed[_from][msg.sender] -= _value; } emit Transfer(_from, _to, _value); //solhint-disable-line indent, no-unused-vars return true; } function balanceOf(address _owner) public view override returns (uint256 balance) { return balances[_owner]; } function approve(address _spender, uint256 _value) public override returns (bool success) { allowed[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); //solhint-disable-line indent, no-unused-vars return true; } function allowance(address _owner, address _spender) public view override returns (uint256 remaining) { return allowed[_owner][_spender]; } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.8.0; pragma abicoder v2; import "../ResultComputation.sol"; import "../../../common/implementation/FixedPoint.sol"; // Wraps the library ResultComputation for testing purposes. contract ResultComputationTest { using ResultComputation for ResultComputation.Data; ResultComputation.Data public data; function wrapAddVote(int256 votePrice, uint256 numberTokens) external { data.addVote(votePrice, FixedPoint.Unsigned(numberTokens)); } function wrapGetResolvedPrice(uint256 minVoteThreshold) external view returns (bool isResolved, int256 price) { return data.getResolvedPrice(FixedPoint.Unsigned(minVoteThreshold)); } function wrapWasVoteCorrect(bytes32 revealHash) external view returns (bool) { return data.wasVoteCorrect(revealHash); } function wrapGetTotalCorrectlyVotedTokens() external view returns (uint256) { return data.getTotalCorrectlyVotedTokens().rawValue; } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.8.0; pragma abicoder v2; import "../Voting.sol"; import "../../../common/implementation/FixedPoint.sol"; // Test contract used to access internal variables in the Voting contract. contract VotingTest is Voting { constructor( uint256 _phaseLength, FixedPoint.Unsigned memory _gatPercentage, FixedPoint.Unsigned memory _inflationRate, uint256 _rewardsExpirationTimeout, address _votingToken, address _finder, address _timerAddress ) Voting( _phaseLength, _gatPercentage, _inflationRate, _rewardsExpirationTimeout, _votingToken, _finder, _timerAddress ) {} function getPendingPriceRequestsArray() external view returns (bytes32[] memory) { return pendingPriceRequests; } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.8.0; import "../implementation/FixedPoint.sol"; // Wraps the FixedPoint library for testing purposes. contract UnsignedFixedPointTest { using FixedPoint for FixedPoint.Unsigned; using FixedPoint for uint256; using SafeMath for uint256; function wrapFromUnscaledUint(uint256 a) external pure returns (uint256) { return FixedPoint.fromUnscaledUint(a).rawValue; } function wrapIsEqual(uint256 a, uint256 b) external pure returns (bool) { return FixedPoint.Unsigned(a).isEqual(FixedPoint.Unsigned(b)); } function wrapMixedIsEqual(uint256 a, uint256 b) external pure returns (bool) { return FixedPoint.Unsigned(a).isEqual(b); } function wrapIsGreaterThan(uint256 a, uint256 b) external pure returns (bool) { return FixedPoint.Unsigned(a).isGreaterThan(FixedPoint.Unsigned(b)); } function wrapIsGreaterThanOrEqual(uint256 a, uint256 b) external pure returns (bool) { return FixedPoint.Unsigned(a).isGreaterThanOrEqual(FixedPoint.Unsigned(b)); } function wrapMixedIsGreaterThan(uint256 a, uint256 b) external pure returns (bool) { return FixedPoint.Unsigned(a).isGreaterThan(b); } function wrapMixedIsGreaterThanOrEqual(uint256 a, uint256 b) external pure returns (bool) { return FixedPoint.Unsigned(a).isGreaterThanOrEqual(b); } function wrapMixedIsGreaterThanOpposite(uint256 a, uint256 b) external pure returns (bool) { return a.isGreaterThan(FixedPoint.Unsigned(b)); } function wrapMixedIsGreaterThanOrEqualOpposite(uint256 a, uint256 b) external pure returns (bool) { return a.isGreaterThanOrEqual(FixedPoint.Unsigned(b)); } function wrapIsLessThan(uint256 a, uint256 b) external pure returns (bool) { return FixedPoint.Unsigned(a).isLessThan(FixedPoint.Unsigned(b)); } function wrapIsLessThanOrEqual(uint256 a, uint256 b) external pure returns (bool) { return FixedPoint.Unsigned(a).isLessThanOrEqual(FixedPoint.Unsigned(b)); } function wrapMixedIsLessThan(uint256 a, uint256 b) external pure returns (bool) { return FixedPoint.Unsigned(a).isLessThan(b); } function wrapMixedIsLessThanOrEqual(uint256 a, uint256 b) external pure returns (bool) { return FixedPoint.Unsigned(a).isLessThanOrEqual(b); } function wrapMixedIsLessThanOpposite(uint256 a, uint256 b) external pure returns (bool) { return a.isLessThan(FixedPoint.Unsigned(b)); } function wrapMixedIsLessThanOrEqualOpposite(uint256 a, uint256 b) external pure returns (bool) { return a.isLessThanOrEqual(FixedPoint.Unsigned(b)); } function wrapMin(uint256 a, uint256 b) external pure returns (uint256) { return FixedPoint.Unsigned(a).min(FixedPoint.Unsigned(b)).rawValue; } function wrapMax(uint256 a, uint256 b) external pure returns (uint256) { return FixedPoint.Unsigned(a).max(FixedPoint.Unsigned(b)).rawValue; } function wrapAdd(uint256 a, uint256 b) external pure returns (uint256) { return FixedPoint.Unsigned(a).add(FixedPoint.Unsigned(b)).rawValue; } // The first uint256 is interpreted with a scaling factor and is converted to an `Unsigned` directly. function wrapMixedAdd(uint256 a, uint256 b) external pure returns (uint256) { return FixedPoint.Unsigned(a).add(b).rawValue; } function wrapSub(uint256 a, uint256 b) external pure returns (uint256) { return FixedPoint.Unsigned(a).sub(FixedPoint.Unsigned(b)).rawValue; } // The first uint256 is interpreted with a scaling factor and is converted to an `Unsigned` directly. function wrapMixedSub(uint256 a, uint256 b) external pure returns (uint256) { return FixedPoint.Unsigned(a).sub(b).rawValue; } // The second uint256 is interpreted with a scaling factor and is converted to an `Unsigned` directly. function wrapMixedSubOpposite(uint256 a, uint256 b) external pure returns (uint256) { return a.sub(FixedPoint.Unsigned(b)).rawValue; } function wrapMul(uint256 a, uint256 b) external pure returns (uint256) { return FixedPoint.Unsigned(a).mul(FixedPoint.Unsigned(b)).rawValue; } function wrapMulCeil(uint256 a, uint256 b) external pure returns (uint256) { return FixedPoint.Unsigned(a).mulCeil(FixedPoint.Unsigned(b)).rawValue; } // The first uint256 is interpreted with a scaling factor and is converted to an `Unsigned` directly. function wrapMixedMul(uint256 a, uint256 b) external pure returns (uint256) { return FixedPoint.Unsigned(a).mul(b).rawValue; } function wrapMixedMulCeil(uint256 a, uint256 b) external pure returns (uint256) { return FixedPoint.Unsigned(a).mulCeil(b).rawValue; } function wrapDiv(uint256 a, uint256 b) external pure returns (uint256) { return FixedPoint.Unsigned(a).div(FixedPoint.Unsigned(b)).rawValue; } function wrapDivCeil(uint256 a, uint256 b) external pure returns (uint256) { return FixedPoint.Unsigned(a).divCeil(FixedPoint.Unsigned(b)).rawValue; } // The first uint256 is interpreted with a scaling factor and is converted to an `Unsigned` directly. function wrapMixedDiv(uint256 a, uint256 b) external pure returns (uint256) { return FixedPoint.Unsigned(a).div(b).rawValue; } function wrapMixedDivCeil(uint256 a, uint256 b) external pure returns (uint256) { return FixedPoint.Unsigned(a).divCeil(b).rawValue; } // The second uint256 is interpreted with a scaling factor and is converted to an `Unsigned` directly. function wrapMixedDivOpposite(uint256 a, uint256 b) external pure returns (uint256) { return a.div(FixedPoint.Unsigned(b)).rawValue; } // The first uint256 is interpreted with a scaling factor and is converted to an `Unsigned` directly. function wrapPow(uint256 a, uint256 b) external pure returns (uint256) { return FixedPoint.Unsigned(a).pow(b).rawValue; } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.8.0; import "../implementation/FixedPoint.sol"; // Wraps the FixedPoint library for testing purposes. contract SignedFixedPointTest { using FixedPoint for FixedPoint.Signed; using FixedPoint for int256; using SafeMath for int256; function wrapFromSigned(int256 a) external pure returns (uint256) { return FixedPoint.fromSigned(FixedPoint.Signed(a)).rawValue; } function wrapFromUnsigned(uint256 a) external pure returns (int256) { return FixedPoint.fromUnsigned(FixedPoint.Unsigned(a)).rawValue; } function wrapFromUnscaledInt(int256 a) external pure returns (int256) { return FixedPoint.fromUnscaledInt(a).rawValue; } function wrapIsEqual(int256 a, int256 b) external pure returns (bool) { return FixedPoint.Signed(a).isEqual(FixedPoint.Signed(b)); } function wrapMixedIsEqual(int256 a, int256 b) external pure returns (bool) { return FixedPoint.Signed(a).isEqual(b); } function wrapIsGreaterThan(int256 a, int256 b) external pure returns (bool) { return FixedPoint.Signed(a).isGreaterThan(FixedPoint.Signed(b)); } function wrapIsGreaterThanOrEqual(int256 a, int256 b) external pure returns (bool) { return FixedPoint.Signed(a).isGreaterThanOrEqual(FixedPoint.Signed(b)); } function wrapMixedIsGreaterThan(int256 a, int256 b) external pure returns (bool) { return FixedPoint.Signed(a).isGreaterThan(b); } function wrapMixedIsGreaterThanOrEqual(int256 a, int256 b) external pure returns (bool) { return FixedPoint.Signed(a).isGreaterThanOrEqual(b); } function wrapMixedIsGreaterThanOpposite(int256 a, int256 b) external pure returns (bool) { return a.isGreaterThan(FixedPoint.Signed(b)); } function wrapMixedIsGreaterThanOrEqualOpposite(int256 a, int256 b) external pure returns (bool) { return a.isGreaterThanOrEqual(FixedPoint.Signed(b)); } function wrapIsLessThan(int256 a, int256 b) external pure returns (bool) { return FixedPoint.Signed(a).isLessThan(FixedPoint.Signed(b)); } function wrapIsLessThanOrEqual(int256 a, int256 b) external pure returns (bool) { return FixedPoint.Signed(a).isLessThanOrEqual(FixedPoint.Signed(b)); } function wrapMixedIsLessThan(int256 a, int256 b) external pure returns (bool) { return FixedPoint.Signed(a).isLessThan(b); } function wrapMixedIsLessThanOrEqual(int256 a, int256 b) external pure returns (bool) { return FixedPoint.Signed(a).isLessThanOrEqual(b); } function wrapMixedIsLessThanOpposite(int256 a, int256 b) external pure returns (bool) { return a.isLessThan(FixedPoint.Signed(b)); } function wrapMixedIsLessThanOrEqualOpposite(int256 a, int256 b) external pure returns (bool) { return a.isLessThanOrEqual(FixedPoint.Signed(b)); } function wrapMin(int256 a, int256 b) external pure returns (int256) { return FixedPoint.Signed(a).min(FixedPoint.Signed(b)).rawValue; } function wrapMax(int256 a, int256 b) external pure returns (int256) { return FixedPoint.Signed(a).max(FixedPoint.Signed(b)).rawValue; } function wrapAdd(int256 a, int256 b) external pure returns (int256) { return FixedPoint.Signed(a).add(FixedPoint.Signed(b)).rawValue; } // The first int256 is interpreted with a scaling factor and is converted to an `Unsigned` directly. function wrapMixedAdd(int256 a, int256 b) external pure returns (int256) { return FixedPoint.Signed(a).add(b).rawValue; } function wrapSub(int256 a, int256 b) external pure returns (int256) { return FixedPoint.Signed(a).sub(FixedPoint.Signed(b)).rawValue; } // The first int256 is interpreted with a scaling factor and is converted to an `Unsigned` directly. function wrapMixedSub(int256 a, int256 b) external pure returns (int256) { return FixedPoint.Signed(a).sub(b).rawValue; } // The second int256 is interpreted with a scaling factor and is converted to an `Unsigned` directly. function wrapMixedSubOpposite(int256 a, int256 b) external pure returns (int256) { return a.sub(FixedPoint.Signed(b)).rawValue; } function wrapMul(int256 a, int256 b) external pure returns (int256) { return FixedPoint.Signed(a).mul(FixedPoint.Signed(b)).rawValue; } function wrapMulAwayFromZero(int256 a, int256 b) external pure returns (int256) { return FixedPoint.Signed(a).mulAwayFromZero(FixedPoint.Signed(b)).rawValue; } // The first int256 is interpreted with a scaling factor and is converted to an `Unsigned` directly. function wrapMixedMul(int256 a, int256 b) external pure returns (int256) { return FixedPoint.Signed(a).mul(b).rawValue; } function wrapMixedMulAwayFromZero(int256 a, int256 b) external pure returns (int256) { return FixedPoint.Signed(a).mulAwayFromZero(b).rawValue; } function wrapDiv(int256 a, int256 b) external pure returns (int256) { return FixedPoint.Signed(a).div(FixedPoint.Signed(b)).rawValue; } function wrapDivAwayFromZero(int256 a, int256 b) external pure returns (int256) { return FixedPoint.Signed(a).divAwayFromZero(FixedPoint.Signed(b)).rawValue; } // The first int256 is interpreted with a scaling factor and is converted to an `Unsigned` directly. function wrapMixedDiv(int256 a, int256 b) external pure returns (int256) { return FixedPoint.Signed(a).div(b).rawValue; } function wrapMixedDivAwayFromZero(int256 a, int256 b) external pure returns (int256) { return FixedPoint.Signed(a).divAwayFromZero(b).rawValue; } // The second int256 is interpreted with a scaling factor and is converted to an `Unsigned` directly. function wrapMixedDivOpposite(int256 a, int256 b) external pure returns (int256) { return a.div(FixedPoint.Signed(b)).rawValue; } // The first int256 is interpreted with a scaling factor and is converted to an `Unsigned` directly. function wrapPow(int256 a, uint256 b) external pure returns (int256) { return FixedPoint.Signed(a).pow(b).rawValue; } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.8.0; pragma abicoder v2; import "../../common/implementation/FixedPoint.sol"; /** * @title Simple Perpetual Mock to serve trivial functions */ contract PerpetualMock { struct FundingRate { FixedPoint.Signed rate; bytes32 identifier; FixedPoint.Unsigned cumulativeMultiplier; uint256 updateTime; uint256 applicationTime; uint256 proposalTime; } using FixedPoint for FixedPoint.Unsigned; using FixedPoint for FixedPoint.Signed; FundingRate public fundingRate; // Interface functions required to be implemented in order for an instance of this contract to be passed into the // off-chain FinancialContractClient helper module: FixedPoint.Unsigned public collateralRequirement; uint256 public liquidationLiveness; FixedPoint.Unsigned public cumulativeFeeMultiplier; mapping(address => uint256) public positions; mapping(address => uint256) public liquidations; event NewSponsor(address indexed sponsor); event EndedSponsorPosition(); event LiquidationCreated(); function getCurrentTime() public view returns (uint256) { return block.timestamp; } // Public methods that are useful for tests: function setFundingRate(FundingRate memory _fundingRate) external { fundingRate = _fundingRate; } function applyFundingRate() external { fundingRate.applicationTime = block.timestamp; // Simplified rate calcualtion. // multiplier = multiplier * (1 + rate) fundingRate.cumulativeMultiplier = fundingRate.cumulativeMultiplier.mul( FixedPoint.fromSigned(FixedPoint.fromUnscaledInt(1).add(fundingRate.rate)) ); } }
This method will ultimately be called after `requestPrice` calls `Bridge.deposit()`, which will call `GenericHandler.deposit()` and ultimately this method. This method should basically check that the `Bridge.deposit()` was triggered by a valid price request, specifically one that has not resolved yet and was called by a registered contract. Without this check, `Bridge.deposit()` could be called by non-registered contracts to make price requests to the DVM./
function validateDeposit( uint8 sinkChainID, bytes32 identifier, uint256 time, bytes memory ancillaryData ) public view { bytes32 priceRequestId = _encodePriceRequest(sinkChainID, identifier, time, ancillaryData); Price storage lookup = prices[priceRequestId]; require(lookup.state == RequestState.Requested, "Price has not been requested"); }
272,986
// SPDX-License-Identifier: MIT pragma solidity =0.7.6; pragma abicoder v2; import "@openzeppelin/contracts/GSN/Context.sol"; import "@openzeppelin/contracts/access/AccessControl.sol"; import "@openzeppelin/contracts/math/Math.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "./Staged.sol"; import "./AuctionHouseMath.sol"; import "./interfaces/IAuctionHouse.sol"; import "../funds/interfaces/basket/IBasketReader.sol"; import "../oracle/interfaces/ITwap.sol"; import "../policy/interfaces/IMonetaryPolicy.sol"; import "../tokens/interfaces/ISupplyControlledERC20.sol"; import "../lib/BasisMath.sol"; import "../lib/BlockNumber.sol"; import "../lib/Recoverable.sol"; import "../external-lib/SafeDecimalMath.sol"; import "../tokens/SafeSupplyControlledERC20.sol"; /** * @title Float Protocol Auction House * @notice The contract used to sell or buy FLOAT * @dev This contract does not store any assets, except for protocol fees, hence * it implements an asset recovery functionality (Recoverable). */ contract AuctionHouse is IAuctionHouse, BlockNumber, AuctionHouseMath, AccessControl, Staged, Recoverable { using SafeMath for uint256; using SafeDecimalMath for uint256; using SafeERC20 for IERC20; using SafeERC20 for ISupplyControlledERC20; using SafeSupplyControlledERC20 for ISupplyControlledERC20; using BasisMath for uint256; /* ========== CONSTANTS ========== */ bytes32 public constant GOVERNANCE_ROLE = keccak256("GOVERNANCE_ROLE"); IERC20 internal immutable weth; ISupplyControlledERC20 internal immutable bank; ISupplyControlledERC20 internal immutable float; IBasketReader internal immutable basket; /* ========== STATE VARIABLES ========== */ // Monetary Policy Contract that decides the target price IMonetaryPolicy internal monetaryPolicy; // Provides the BANK-ETH Time Weighted Average Price (TWAP) [e27] ITwap internal bankEthOracle; // Provides the FLOAT-ETH Time Weighted Average Price (TWAP) [e27] ITwap internal floatEthOracle; /// @inheritdoc IAuctionHouseState uint16 public override buffer = 10_00; // 10% default /// @inheritdoc IAuctionHouseState uint16 public override protocolFee = 5_00; // 5% / 500 bps /// @inheritdoc IAuctionHouseState uint32 public override allowanceCap = 10_00; // 10% / 1000 bps /// @inheritdoc IAuctionHouseVariables uint64 public override round; /** * @notice Allows for monetary policy updates to be enabled and disabled. */ bool public shouldUpdatePolicy = true; /** * Note that we choose to freeze all price values at the start of an auction. * These values are stale _by design_. The burden of price checking * is moved to the arbitrager, already vital for them to make a profit. * We don't mind these values being out of date, as we start the auctions from a position generously in favour of the protocol (assuming our target price is correct). If these market values are stale, then profit opportunity will start earlier / later, and hence close out a mispriced auction early. * We also start the auctions at `buffer`% of the price. */ /// @inheritdoc IAuctionHouseVariables mapping(uint64 => Auction) public override auctions; /* ========== CONSTRUCTOR ========== */ constructor( // Dependencies address _weth, address _bank, address _float, address _basket, address _monetaryPolicy, address _gov, address _bankEthOracle, address _floatEthOracle, // Parameters uint16 _auctionDuration, uint32 _auctionCooldown, uint256 _firstAuctionBlock ) Staged(_auctionDuration, _auctionCooldown, _firstAuctionBlock) { // Tokens weth = IERC20(_weth); bank = ISupplyControlledERC20(_bank); float = ISupplyControlledERC20(_float); // Basket basket = IBasketReader(_basket); // Monetary Policy monetaryPolicy = IMonetaryPolicy(_monetaryPolicy); floatEthOracle = ITwap(_floatEthOracle); bankEthOracle = ITwap(_bankEthOracle); emit ModifyParameters("monetaryPolicy", _monetaryPolicy); emit ModifyParameters("floatEthOracle", _floatEthOracle); emit ModifyParameters("bankEthOracle", _bankEthOracle); emit ModifyParameters("auctionDuration", _auctionDuration); emit ModifyParameters("auctionCooldown", _auctionCooldown); emit ModifyParameters("lastAuctionBlock", lastAuctionBlock); emit ModifyParameters("buffer", buffer); emit ModifyParameters("protocolFee", protocolFee); emit ModifyParameters("allowanceCap", allowanceCap); // Roles _setupRole(DEFAULT_ADMIN_ROLE, _gov); _setupRole(GOVERNANCE_ROLE, _gov); _setupRole(RECOVER_ROLE, _gov); } /* ========== MODIFIERS ========== */ modifier onlyGovernance { require( hasRole(GOVERNANCE_ROLE, _msgSender()), "AuctionHouse/GovernanceRole" ); _; } modifier inExpansion { require( latestAuction().stabilisationCase == Cases.Up || latestAuction().stabilisationCase == Cases.Restock, "AuctionHouse/NotInExpansion" ); _; } modifier inContraction { require( latestAuction().stabilisationCase == Cases.Confidence || latestAuction().stabilisationCase == Cases.Down, "AuctionHouse/NotInContraction" ); _; } /* ========== VIEWS ========== */ /// @inheritdoc IAuctionHouseDerivedState function price() public view override(IAuctionHouseDerivedState) returns (uint256 wethPrice, uint256 bankPrice) { Auction memory _latestAuction = latestAuction(); uint256 _step = step(); wethPrice = lerp( _latestAuction.startWethPrice, _latestAuction.endWethPrice, _step, auctionDuration ); bankPrice = lerp( _latestAuction.startBankPrice, _latestAuction.endBankPrice, _step, auctionDuration ); return (wethPrice, bankPrice); } /// @inheritdoc IAuctionHouseDerivedState function step() public view override(IAuctionHouseDerivedState) atStage(Stages.AuctionActive) returns (uint256) { // .sub is unnecessary here - block number >= lastAuctionBlock. return _blockNumber() - lastAuctionBlock; } function _startPrice( bool expansion, Cases stabilisationCase, uint256 targetFloatInEth, uint256 marketFloatInEth, uint256 bankInEth, uint256 basketFactor ) internal view returns (uint256 wethStart, uint256 bankStart) { uint256 bufferedMarketPrice = _bufferedMarketPrice(expansion, marketFloatInEth); if (stabilisationCase == Cases.Up) { uint256 bankProportion = bufferedMarketPrice.sub(targetFloatInEth).divideDecimalRoundPrecise( bankInEth ); return (targetFloatInEth, bankProportion); } if ( stabilisationCase == Cases.Restock || stabilisationCase == Cases.Confidence ) { return (bufferedMarketPrice, 0); } assert(stabilisationCase == Cases.Down); assert(basketFactor < SafeDecimalMath.PRECISE_UNIT); uint256 invertedBasketFactor = SafeDecimalMath.PRECISE_UNIT.sub(basketFactor); uint256 basketFactorAdjustedEth = bufferedMarketPrice.multiplyDecimalRoundPrecise(basketFactor); // Note that the PRECISE_UNIT factors itself out uint256 basketFactorAdjustedBank = bufferedMarketPrice.mul(invertedBasketFactor).div(bankInEth); return (basketFactorAdjustedEth, basketFactorAdjustedBank); } function _endPrice( Cases stabilisationCase, uint256 targetFloatInEth, uint256 bankInEth, uint256 basketFactor ) internal pure returns (uint256 wethEnd, uint256 bankEnd) { if (stabilisationCase == Cases.Down) { assert(basketFactor < SafeDecimalMath.PRECISE_UNIT); uint256 invertedBasketFactor = SafeDecimalMath.PRECISE_UNIT.sub(basketFactor); uint256 basketFactorAdjustedEth = targetFloatInEth.multiplyDecimalRoundPrecise(basketFactor); // Note that the PRECISE_UNIT factors itself out. uint256 basketFactorAdjustedBank = targetFloatInEth.mul(invertedBasketFactor).div(bankInEth); return (basketFactorAdjustedEth, basketFactorAdjustedBank); } return (targetFloatInEth, 0); } /// @inheritdoc IAuctionHouseDerivedState function latestAuction() public view override(IAuctionHouseDerivedState) returns (Auction memory) { return auctions[round]; } /// @dev Returns a buffered [e27] market price, note that buffer is still [e18], so can use divideDecimal. function _bufferedMarketPrice(bool expansion, uint256 marketPrice) internal view returns (uint256) { uint256 factor = expansion ? BasisMath.FULL_PERCENT.add(buffer) : BasisMath.FULL_PERCENT.sub(buffer); return marketPrice.percentageOf(factor); } /// @dev Calculates the current case based on if we're expanding and basket factor. function _currentCase(bool expansion, uint256 basketFactor) internal pure returns (Cases) { bool underlyingDemand = basketFactor >= SafeDecimalMath.PRECISE_UNIT; if (expansion) { return underlyingDemand ? Cases.Up : Cases.Restock; } return underlyingDemand ? Cases.Confidence : Cases.Down; } /* |||||||||| AuctionPending |||||||||| */ // solhint-disable function-max-lines /// @inheritdoc IAuctionHouseActions function start() external override(IAuctionHouseActions) timedTransition atStage(Stages.AuctionPending) returns (uint64 newRound) { // Check we have up to date oracles, this also ensures we don't have // auctions too close together (reverts based upon timeElapsed < periodSize). bankEthOracle.update(address(bank), address(weth)); floatEthOracle.update(address(float), address(weth)); // [e27] uint256 frozenBankInEth = bankEthOracle.consult( address(bank), SafeDecimalMath.PRECISE_UNIT, address(weth) ); // [e27] uint256 frozenFloatInEth = floatEthOracle.consult( address(float), SafeDecimalMath.PRECISE_UNIT, address(weth) ); // Update Monetary Policy with previous auction results if (round != 0 && shouldUpdatePolicy) { uint256 oldTargetPriceInEth = monetaryPolicy.consult(); uint256 oldBasketFactor = basket.getBasketFactor(oldTargetPriceInEth); monetaryPolicy.updateGivenAuctionResults( round, lastAuctionBlock, frozenFloatInEth, oldBasketFactor ); } // Round only increments by one on start, given auction period of restriction of 150 blocks // this means we'd need 2**64 / 150 blocks or ~3.7 lifetimes of the universe to overflow. // Likely, we'd have upgraded the contract by this point. round++; // Calculate target price [e27] uint256 frozenTargetPriceInEth = monetaryPolicy.consult(); // STC: Pull out to ValidateOracles require(frozenTargetPriceInEth != 0, "AuctionHouse/TargetSenseCheck"); require(frozenBankInEth != 0, "AuctionHouse/BankSenseCheck"); require(frozenFloatInEth != 0, "AuctionHouse/FloatSenseCheck"); uint256 basketFactor = basket.getBasketFactor(frozenTargetPriceInEth); bool expansion = frozenFloatInEth >= frozenTargetPriceInEth; Cases stabilisationCase = _currentCase(expansion, basketFactor); // Calculate Auction Price points (uint256 wethStart, uint256 bankStart) = _startPrice( expansion, stabilisationCase, frozenTargetPriceInEth, frozenFloatInEth, frozenBankInEth, basketFactor ); (uint256 wethEnd, uint256 bankEnd) = _endPrice( stabilisationCase, frozenTargetPriceInEth, frozenBankInEth, basketFactor ); // Calculate Allowance uint256 allowance = AuctionHouseMath.allowance( expansion, allowanceCap, float.totalSupply(), frozenFloatInEth, frozenTargetPriceInEth ); require(allowance != 0, "AuctionHouse/NoAllowance"); auctions[round].stabilisationCase = stabilisationCase; auctions[round].targetFloatInEth = frozenTargetPriceInEth; auctions[round].marketFloatInEth = frozenFloatInEth; auctions[round].bankInEth = frozenBankInEth; auctions[round].basketFactor = basketFactor; auctions[round].allowance = allowance; auctions[round].startWethPrice = wethStart; auctions[round].startBankPrice = bankStart; auctions[round].endWethPrice = wethEnd; auctions[round].endBankPrice = bankEnd; lastAuctionBlock = _blockNumber(); _setStage(Stages.AuctionActive); emit NewAuction(round, allowance, frozenTargetPriceInEth, lastAuctionBlock); return round; } // solhint-enable function-max-lines /* |||||||||| AuctionActive |||||||||| */ function _updateDelta(uint256 floatDelta) internal { Auction memory _currentAuction = latestAuction(); require( floatDelta <= _currentAuction.allowance.sub(_currentAuction.delta), "AuctionHouse/WithinAllowedDelta" ); auctions[round].delta = _currentAuction.delta.add(floatDelta); } /* |||||||||| AuctionActive:inExpansion |||||||||| */ /// @inheritdoc IAuctionHouseActions function buy( uint256 wethInMax, uint256 bankInMax, uint256 floatOutMin, address to, uint256 deadline ) external override(IAuctionHouseActions) timedTransition atStage(Stages.AuctionActive) inExpansion returns ( uint256 usedWethIn, uint256 usedBankIn, uint256 usedFloatOut ) { // solhint-disable-next-line not-rely-on-time require(block.timestamp <= deadline, "AuctionHouse/TransactionTooOld"); (uint256 wethPrice, uint256 bankPrice) = price(); usedFloatOut = Math.min( wethInMax.divideDecimalRoundPrecise(wethPrice), bankPrice == 0 ? type(uint256).max : bankInMax.divideDecimalRoundPrecise(bankPrice) ); require(usedFloatOut != 0, "AuctionHouse/ZeroFloatBought"); require(usedFloatOut >= floatOutMin, "AuctionHouse/RequestedTooMuch"); usedWethIn = wethPrice.multiplyDecimalRoundPrecise(usedFloatOut); usedBankIn = bankPrice.multiplyDecimalRoundPrecise(usedFloatOut); require(wethInMax >= usedWethIn, "AuctionHouse/MinimumWeth"); require(bankInMax >= usedBankIn, "AuctionHouse/MinimumBank"); _updateDelta(usedFloatOut); emit Buy(round, _msgSender(), usedWethIn, usedBankIn, usedFloatOut); _interactBuy(usedWethIn, usedBankIn, usedFloatOut, to); return (usedWethIn, usedBankIn, usedFloatOut); } function _interactBuy( uint256 usedWethIn, uint256 usedBankIn, uint256 usedFloatOut, address to ) internal { weth.safeTransferFrom(_msgSender(), address(basket), usedWethIn); if (usedBankIn != 0) { (uint256 bankToSave, uint256 bankToBurn) = usedBankIn.splitBy(protocolFee); bank.safeTransferFrom(_msgSender(), address(this), bankToSave); bank.safeBurnFrom(_msgSender(), bankToBurn); } float.safeMint(to, usedFloatOut); } /* |||||||||| AuctionActive:inContraction |||||||||| */ /// @inheritdoc IAuctionHouseActions function sell( uint256 floatIn, uint256 wethOutMin, uint256 bankOutMin, address to, uint256 deadline ) external override(IAuctionHouseActions) timedTransition atStage(Stages.AuctionActive) inContraction returns ( uint256 usedfloatIn, uint256 usedWethOut, uint256 usedBankOut ) { // solhint-disable-next-line not-rely-on-time require(block.timestamp <= deadline, "AuctionHouse/TransactionTooOld"); require(floatIn != 0, "AuctionHouse/ZeroFloatSold"); (uint256 wethPrice, uint256 bankPrice) = price(); usedWethOut = wethPrice.multiplyDecimalRoundPrecise(floatIn); usedBankOut = bankPrice.multiplyDecimalRoundPrecise(floatIn); require(wethOutMin <= usedWethOut, "AuctionHouse/ExpectedTooMuchWeth"); require(bankOutMin <= usedBankOut, "AuctionHouse/ExpectedTooMuchBank"); _updateDelta(floatIn); emit Sell(round, _msgSender(), floatIn, usedWethOut, usedBankOut); _interactSell(floatIn, usedWethOut, usedBankOut, to); return (floatIn, usedWethOut, usedBankOut); } function _interactSell( uint256 floatIn, uint256 usedWethOut, uint256 usedBankOut, address to ) internal { float.safeBurnFrom(_msgSender(), floatIn); if (usedWethOut != 0) { weth.safeTransferFrom(address(basket), to, usedWethOut); } if (usedBankOut != 0) { // STC: Maximum mint checks relative to allowance bank.safeMint(to, usedBankOut); } } /* |||||||||| AuctionCooldown, AuctionPending, AuctionActive |||||||||| */ /* ========== RESTRICTED FUNCTIONS ========== */ /* ----- onlyGovernance ----- */ /// @inheritdoc IAuctionHouseGovernedActions function modifyParameters(bytes32 parameter, uint256 data) external override(IAuctionHouseGovernedActions) onlyGovernance { if (parameter == "auctionDuration") { require(data <= type(uint16).max, "AuctionHouse/ModADMax"); require(data != 0, "AuctionHouse/ModADZero"); auctionDuration = uint16(data); } else if (parameter == "auctionCooldown") { require(data <= type(uint32).max, "AuctionHouse/ModCMax"); auctionCooldown = uint32(data); } else if (parameter == "buffer") { // 0% <= buffer <= 1000% require(data <= 10 * BasisMath.FULL_PERCENT, "AuctionHouse/ModBMax"); buffer = uint16(data); } else if (parameter == "protocolFee") { // 0% <= protocolFee <= 100% require(data <= BasisMath.FULL_PERCENT, "AuctionHouse/ModPFMax"); protocolFee = uint16(data); } else if (parameter == "allowanceCap") { // 0% < allowanceCap <= N ~ 1_000% require(data <= type(uint32).max, "AuctionHouse/ModACMax"); require(data != 0, "AuctionHouse/ModACMin"); allowanceCap = uint32(data); } else if (parameter == "shouldUpdatePolicy") { require(data == 1 || data == 0, "AuctionHouse/ModUP"); shouldUpdatePolicy = data == 1; } else if (parameter == "lastAuctionBlock") { // We wouldn't want to disable auctions for more than ~4.3 weeks // A longer period should result in a "burnt" auction house and redeploy. require(data <= block.number + 2e5, "AuctionHouse/ModLABMax"); require(data != 0, "AuctionHouse/ModLABMin"); // Can be used to pause auctions if set in the future. lastAuctionBlock = data; } else revert("AuctionHouse/InvalidParameter"); emit ModifyParameters(parameter, data); } /// @inheritdoc IAuctionHouseGovernedActions function modifyParameters(bytes32 parameter, address data) external override(IAuctionHouseGovernedActions) onlyGovernance { if (parameter == "monetaryPolicy") { // STC: Sense check monetaryPolicy = IMonetaryPolicy(data); } else if (parameter == "bankEthOracle") { // STC: Sense check bankEthOracle = ITwap(data); } else if (parameter == "floatEthOracle") { // STC: Sense check floatEthOracle = ITwap(data); } else revert("AuctionHouse/InvalidParameter"); emit ModifyParameters(parameter, data); } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "../utils/Context.sol"; // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "../utils/EnumerableSet.sol"; import "../utils/Address.sol"; import "../utils/Context.sol"; /** * @dev Contract module that allows children to implement role-based access * control mechanisms. * * Roles are referred to by their `bytes32` identifier. These should be exposed * in the external API and be unique. The best way to achieve this is by * using `public constant` hash digests: * * ``` * bytes32 public constant MY_ROLE = keccak256("MY_ROLE"); * ``` * * Roles can be used to represent a set of permissions. To restrict access to a * function call, use {hasRole}: * * ``` * function foo() public { * require(hasRole(MY_ROLE, msg.sender)); * ... * } * ``` * * Roles can be granted and revoked dynamically via the {grantRole} and * {revokeRole} functions. Each role has an associated admin role, and only * accounts that have a role's admin role can call {grantRole} and {revokeRole}. * * By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means * that only accounts with this role will be able to grant or revoke other * roles. More complex role relationships can be created by using * {_setRoleAdmin}. * * WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to * grant and revoke this role. Extra precautions should be taken to secure * accounts that have been granted it. */ abstract contract AccessControl is Context { using EnumerableSet for EnumerableSet.AddressSet; using Address for address; struct RoleData { EnumerableSet.AddressSet members; bytes32 adminRole; } mapping (bytes32 => RoleData) private _roles; bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00; /** * @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole` * * `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite * {RoleAdminChanged} not being emitted signaling this. * * _Available since v3.1._ */ event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole); /** * @dev Emitted when `account` is granted `role`. * * `sender` is the account that originated the contract call, an admin role * bearer except when using {_setupRole}. */ event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Emitted when `account` is revoked `role`. * * `sender` is the account that originated the contract call: * - if using `revokeRole`, it is the admin role bearer * - if using `renounceRole`, it is the role bearer (i.e. `account`) */ event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Returns `true` if `account` has been granted `role`. */ function hasRole(bytes32 role, address account) public view returns (bool) { return _roles[role].members.contains(account); } /** * @dev Returns the number of accounts that have `role`. Can be used * together with {getRoleMember} to enumerate all bearers of a role. */ function getRoleMemberCount(bytes32 role) public view returns (uint256) { return _roles[role].members.length(); } /** * @dev Returns one of the accounts that have `role`. `index` must be a * value between 0 and {getRoleMemberCount}, non-inclusive. * * Role bearers are not sorted in any particular way, and their ordering may * change at any point. * * WARNING: When using {getRoleMember} and {getRoleMemberCount}, make sure * you perform all queries on the same block. See the following * https://forum.openzeppelin.com/t/iterating-over-elements-on-enumerableset-in-openzeppelin-contracts/2296[forum post] * for more information. */ function getRoleMember(bytes32 role, uint256 index) public view returns (address) { return _roles[role].members.at(index); } /** * @dev Returns the admin role that controls `role`. See {grantRole} and * {revokeRole}. * * To change a role's admin, use {_setRoleAdmin}. */ function getRoleAdmin(bytes32 role) public view returns (bytes32) { return _roles[role].adminRole; } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function grantRole(bytes32 role, address account) public virtual { require(hasRole(_roles[role].adminRole, _msgSender()), "AccessControl: sender must be an admin to grant"); _grantRole(role, account); } /** * @dev Revokes `role` from `account`. * * If `account` had been granted `role`, emits a {RoleRevoked} event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function revokeRole(bytes32 role, address account) public virtual { require(hasRole(_roles[role].adminRole, _msgSender()), "AccessControl: sender must be an admin to revoke"); _revokeRole(role, account); } /** * @dev Revokes `role` from the calling account. * * Roles are often managed via {grantRole} and {revokeRole}: this function's * purpose is to provide a mechanism for accounts to lose their privileges * if they are compromised (such as when a trusted device is misplaced). * * If the calling account had been granted `role`, emits a {RoleRevoked} * event. * * Requirements: * * - the caller must be `account`. */ function renounceRole(bytes32 role, address account) public virtual { require(account == _msgSender(), "AccessControl: can only renounce roles for self"); _revokeRole(role, account); } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. Note that unlike {grantRole}, this function doesn't perform any * checks on the calling account. * * [WARNING] * ==== * This function should only be called from the constructor when setting * up the initial roles for the system. * * Using this function in any other way is effectively circumventing the admin * system imposed by {AccessControl}. * ==== */ function _setupRole(bytes32 role, address account) internal virtual { _grantRole(role, account); } /** * @dev Sets `adminRole` as ``role``'s admin role. * * Emits a {RoleAdminChanged} event. */ function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual { emit RoleAdminChanged(role, _roles[role].adminRole, adminRole); _roles[role].adminRole = adminRole; } function _grantRole(bytes32 role, address account) private { if (_roles[role].members.add(account)) { emit RoleGranted(role, account, _msgSender()); } } function _revokeRole(bytes32 role, address account) private { if (_roles[role].members.remove(account)) { emit RoleRevoked(role, account, _msgSender()); } } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Standard math utilities missing in the Solidity language. */ library Math { /** * @dev Returns the largest of two numbers. */ function max(uint256 a, uint256 b) internal pure returns (uint256) { return a >= b ? a : b; } /** * @dev Returns the smallest of two numbers. */ function min(uint256 a, uint256 b) internal pure returns (uint256) { return a < b ? a : b; } /** * @dev Returns the average of two numbers. The result is rounded towards * zero. */ function average(uint256 a, uint256 b) internal pure returns (uint256) { // (a + b) / 2 can overflow, so we distribute return (a / 2) + (b / 2) + ((a % 2 + b % 2) / 2); } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b > a) return (false, 0); return (true, a - b); } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a / b); } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a % b); } /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a, "SafeMath: subtraction overflow"); return a - b; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) return 0; uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers, reverting on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: division by zero"); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: modulo by zero"); return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); return a - b; } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryDiv}. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a % b; } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "./IERC20.sol"; import "../../math/SafeMath.sol"; import "../../utils/Address.sol"; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using SafeMath for uint256; using Address for address; function safeTransfer(IERC20 token, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove(IERC20 token, address spender, uint256 value) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' // solhint-disable-next-line max-line-length require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).add(value); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero"); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // SPDX-License-Identifier: MIT pragma solidity =0.7.6; import "../lib/BlockNumber.sol"; contract Staged is BlockNumber { /** * @dev The current auction stage. * - AuctionCooling - We cannot start an auction due to Cooling Period. * - AuctionPending - We can start an auction at any time. * - AuctionActive - Auction is ongoing. */ enum Stages {AuctionCooling, AuctionPending, AuctionActive} /* ========== STATE VARIABLES ========== */ /** * @dev The cooling period between each auction in blocks. */ uint32 internal auctionCooldown; /** * @dev The length of the auction in blocks. */ uint16 internal auctionDuration; /** * @notice The current stage */ Stages public stage; /** * @notice Block number when the last auction started. */ uint256 public lastAuctionBlock; /* ========== CONSTRUCTOR ========== */ constructor( uint16 _auctionDuration, uint32 _auctionCooldown, uint256 _firstAuctionBlock ) { require( _firstAuctionBlock >= _auctionDuration + _auctionCooldown, "Staged/InvalidAuctionStart" ); auctionDuration = _auctionDuration; auctionCooldown = _auctionCooldown; lastAuctionBlock = _firstAuctionBlock - _auctionDuration - _auctionCooldown; stage = Stages.AuctionCooling; } /* ============ Events ============ */ event StageChanged(uint8 _prevStage, uint8 _newStage); /* ========== MODIFIERS ========== */ modifier atStage(Stages _stage) { require(stage == _stage, "Staged/InvalidStage"); _; } /** * @dev Modify the stages as necessary on call. */ modifier timedTransition() { uint256 _blockNumber = _blockNumber(); if ( stage == Stages.AuctionActive && _blockNumber > lastAuctionBlock + auctionDuration ) { stage = Stages.AuctionCooling; emit StageChanged(uint8(Stages.AuctionActive), uint8(stage)); } // Note that this can cascade so AuctionActive -> AuctionPending in one update, when auctionCooldown = 0. if ( stage == Stages.AuctionCooling && _blockNumber > lastAuctionBlock + auctionDuration + auctionCooldown ) { stage = Stages.AuctionPending; emit StageChanged(uint8(Stages.AuctionCooling), uint8(stage)); } _; } /* ========== MUTATIVE FUNCTIONS ========== */ /** * @notice Updates the stage, even if a function with timedTransition modifier has not yet been called * @return Returns current auction stage */ function updateStage() external timedTransition returns (Stages) { return stage; } /** * @dev Set the stage manually. */ function _setStage(Stages _stage) internal { Stages priorStage = stage; stage = _stage; emit StageChanged(uint8(priorStage), uint8(_stage)); } } // SPDX-License-Identifier: MIT pragma solidity =0.7.6; import "@openzeppelin/contracts/math/Math.sol"; import "../lib/BasisMath.sol"; import "../external-lib/SafeDecimalMath.sol"; contract AuctionHouseMath { using SafeMath for uint256; using SafeDecimalMath for uint256; using BasisMath for uint256; /** * @notice Calculate the maximum allowance for this action to do a price correction * This is normally an over-estimate as it assumes all Float is circulating * and the market cap is constant through supply changes. */ function allowance( bool expansion, uint256 capBasisPoint, uint256 floatSupply, uint256 marketFloatPrice, uint256 targetFloatPrice ) internal pure returns (uint256) { uint256 targetSupply = marketFloatPrice.mul(floatSupply).div(targetFloatPrice); uint256 allowanceForAdjustment = expansion ? targetSupply.sub(floatSupply) : floatSupply.sub(targetSupply); // Cap Allowance per auction; e.g. with 10% of total supply => ~20% price move. uint256 allowanceByCap = floatSupply.percentageOf(capBasisPoint); return Math.min(allowanceForAdjustment, allowanceByCap); } /** * @notice Linear interpolation: start + (end - start) * (step/duration) * @dev For 150 steps, duration = 149, start / end can be in any format * as long as <= 10 ** 49. * @param start The starting value * @param end The ending value * @param step Number of blocks into interpolation * @param duration Total range */ function lerp( uint256 start, uint256 end, uint256 step, uint256 duration ) internal pure returns (uint256 result) { require(duration != 0, "AuctionHouseMath/ZeroDuration"); require(step <= duration, "AuctionHouseMath/InvalidStep"); // Max value <= 2^256 / 10^27 of which 10^49 is. require(start <= 10**49, "AuctionHouseMath/StartTooLarge"); require(end <= 10**49, "AuctionHouseMath/EndTooLarge"); // 0 <= t <= PRECISE_UNIT uint256 t = step.divideDecimalRoundPrecise(duration); // result = start + (end - start) * t // = end * t + start - start * t return result = end.multiplyDecimalRoundPrecise(t).add(start).sub( start.multiplyDecimalRoundPrecise(t) ); } } // SPDX-License-Identifier: MIT pragma solidity ^0.7.6; pragma abicoder v2; import "./ah/IAuctionHouseState.sol"; import "./ah/IAuctionHouseVariables.sol"; import "./ah/IAuctionHouseDerivedState.sol"; import "./ah/IAuctionHouseActions.sol"; import "./ah/IAuctionHouseGovernedActions.sol"; import "./ah/IAuctionHouseEvents.sol"; /** * @title The interface for a Float Protocol Auction House * @notice The Auction House enables the sale and buy of FLOAT tokens from the * market in order to stabilise price. * @dev The Auction House interface is broken up into many smaller pieces */ interface IAuctionHouse is IAuctionHouseState, IAuctionHouseVariables, IAuctionHouseDerivedState, IAuctionHouseActions, IAuctionHouseGovernedActions, IAuctionHouseEvents { } // SPDX-License-Identifier: MIT pragma solidity ^0.7.6; pragma abicoder v2; interface IBasketReader { /** * @notice Underlying token that is kept in this Basket */ function underlying() external view returns (address); /** * @notice Given a target price, what is the basket factor * @param targetPriceInUnderlying the current target price to calculate the * basket factor for in the units of the underlying token. */ function getBasketFactor(uint256 targetPriceInUnderlying) external view returns (uint256 basketFactor); } // SPDX-License-Identifier: MIT pragma solidity >=0.7.0 <0.8.0; interface ITwap { /** * @notice Returns the amount out corresponding to the amount in for a given token using the moving average over time range [`block.timestamp` - [`windowSize`, `windowSize - periodSize * 2`], `block.timestamp`]. * E.g. with a windowSize = 24hrs, periodSize = 6hrs. * [24hrs ago to 12hrs ago, now] * @dev Update must have been called for the bucket corresponding to the timestamp `now - windowSize` * @param tokenIn the address of the token we are offering * @param amountIn the quantity of tokens we are pricing * @param tokenOut the address of the token we want * @return amountOut the `tokenOut` amount corresponding to the `amountIn` for `tokenIn` over the time range */ function consult( address tokenIn, uint256 amountIn, address tokenOut ) external view returns (uint256 amountOut); /** * @notice Checks if a particular pair can be updated * @param tokenA Token A of pair (any order) * @param tokenB Token B of pair (any order) * @return If an update call will succeed */ function updateable(address tokenA, address tokenB) external view returns (bool); /** * @notice Update the cumulative price for the observation at the current timestamp. Each observation is updated at most once per epoch period. * @param tokenA the first token to create pair from * @param tokenB the second token to create pair from * @return if the observation was updated or not. */ function update(address tokenA, address tokenB) external returns (bool); } // SPDX-License-Identifier: MIT pragma solidity >=0.7.0 <0.8.0; interface IMonetaryPolicy { /** * @notice Consult the monetary policy for the target price in eth */ function consult() external view returns (uint256 targetPriceInEth); /** * @notice Update the Target price given the auction results. * @dev 0 values are used to indicate missing data. */ function updateGivenAuctionResults( uint256 round, uint256 lastAuctionBlock, uint256 floatMarketPrice, uint256 basketFactor ) external returns (uint256 targetPriceInEth); } // SPDX-License-Identifier: MIT pragma solidity >=0.5.0; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; interface ISupplyControlledERC20 is IERC20 { /** * @dev Creates `amount` new tokens for `to`. * * See {ERC20-_mint}. * * Requirements: * - the caller must have the `MINTER_ROLE`. */ function mint(address to, uint256 amount) external; /** * @dev Destroys `amount` tokens from the caller. * * See {ERC20-_burn}. */ function burn(uint256 amount) external; /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * See {ERC20-_burn}. */ function burnFrom(address account, uint256 amount) external; } // SPDX-License-Identifier: MIT pragma solidity =0.7.6; /** * @title Basis Mathematics * @notice Provides helpers to perform percentage calculations * @dev Percentages are [e2] i.e. with 2 decimals precision / basis point. */ library BasisMath { uint256 internal constant FULL_PERCENT = 1e4; // 100.00% / 1000 bp uint256 internal constant HALF_ONCE_SCALED = FULL_PERCENT / 2; /** * @dev Percentage pct, round 0.5+ up. * @param self The value to take a percentage pct * @param percentage The percentage to be calculated [e2] * @return pct self * percentage */ function percentageOf(uint256 self, uint256 percentage) internal pure returns (uint256 pct) { if (self == 0 || percentage == 0) { pct = 0; } else { require( self <= (type(uint256).max - HALF_ONCE_SCALED) / percentage, "BasisMath/Overflow" ); pct = (self * percentage + HALF_ONCE_SCALED) / FULL_PERCENT; } } /** * @dev Split value into percentage, round 0.5+ up. * @param self The value to split * @param percentage The percentage to be calculated [e2] * @return pct The percentage of the value * @return rem Anything leftover from the value */ function splitBy(uint256 self, uint256 percentage) internal pure returns (uint256 pct, uint256 rem) { require(percentage <= FULL_PERCENT, "BasisMath/ExcessPercentage"); pct = percentageOf(self, percentage); rem = self - pct; } } // SPDX-License-Identifier: MIT pragma solidity =0.7.6; /// @title Function for getting block number /// @dev Base contract that is overridden for tests abstract contract BlockNumber { /// @dev Method that exists purely to be overridden for tests /// @return The current block number function _blockNumber() internal view virtual returns (uint256) { return block.number; } } // SPDX-License-Identifier: MIT pragma solidity =0.7.6; import "@openzeppelin/contracts/access/AccessControl.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "@openzeppelin/contracts/utils/Address.sol"; /** * @title Recoverable feature * @dev should _only_ be used with contracts that should not store assets, * but instead interacted with value so there is potential to lose assets. */ abstract contract Recoverable is AccessControl { using SafeERC20 for IERC20; using Address for address payable; /* ========== CONSTANTS ========== */ bytes32 public constant RECOVER_ROLE = keccak256("RECOVER_ROLE"); /* ============ Events ============ */ event Recovered(address onBehalfOf, address tokenAddress, uint256 amount); /* ========== MODIFIERS ========== */ modifier isRecoverer { require(hasRole(RECOVER_ROLE, _msgSender()), "Recoverable/RecoverRole"); _; } /* ========== RESTRICTED FUNCTIONS ========== */ /* ----- RECOVER_ROLE ----- */ /** * @notice Provide accidental token retrieval. * @dev Sourced from synthetix/contracts/StakingRewards.sol */ function recoverERC20( address to, address tokenAddress, uint256 tokenAmount ) external isRecoverer { emit Recovered(to, tokenAddress, tokenAmount); IERC20(tokenAddress).safeTransfer(to, tokenAmount); } /** * @notice Provide accidental ETH retrieval. */ function recoverETH(address to) external isRecoverer { uint256 contractBalance = address(this).balance; emit Recovered(to, address(0), contractBalance); payable(to).sendValue(contractBalance); } } // SPDX-License-Identifier: MIT pragma solidity ^0.7.6; import "@openzeppelin/contracts/math/SafeMath.sol"; // https://docs.synthetix.io/contracts/source/libraries/safedecimalmath library SafeDecimalMath { using SafeMath for uint256; /* Number of decimal places in the representations. */ uint8 public constant decimals = 18; uint8 public constant highPrecisionDecimals = 27; /* The number representing 1.0. */ uint256 public constant UNIT = 10**uint256(decimals); /* The number representing 1.0 for higher fidelity numbers. */ uint256 public constant PRECISE_UNIT = 10**uint256(highPrecisionDecimals); uint256 private constant UNIT_TO_HIGH_PRECISION_CONVERSION_FACTOR = 10**uint256(highPrecisionDecimals - decimals); /** * @return Provides an interface to UNIT. */ function unit() external pure returns (uint256) { return UNIT; } /** * @return Provides an interface to PRECISE_UNIT. */ function preciseUnit() external pure returns (uint256) { return PRECISE_UNIT; } /** * @return The result of multiplying x and y, interpreting the operands as fixed-point * decimals. * * @dev A unit factor is divided out after the product of x and y is evaluated, * so that product must be less than 2**256. As this is an integer division, * the internal division always rounds down. This helps save on gas. Rounding * is more expensive on gas. */ function multiplyDecimal(uint256 x, uint256 y) internal pure returns (uint256) { /* Divide by UNIT to remove the extra factor introduced by the product. */ return x.mul(y) / UNIT; } /** * @return The result of safely multiplying x and y, interpreting the operands * as fixed-point decimals of the specified precision unit. * * @dev The operands should be in the form of a the specified unit factor which will be * divided out after the product of x and y is evaluated, so that product must be * less than 2**256. * * Unlike multiplyDecimal, this function rounds the result to the nearest increment. * Rounding is useful when you need to retain fidelity for small decimal numbers * (eg. small fractions or percentages). */ function _multiplyDecimalRound( uint256 x, uint256 y, uint256 precisionUnit ) private pure returns (uint256) { /* Divide by UNIT to remove the extra factor introduced by the product. */ uint256 quotientTimesTen = x.mul(y) / (precisionUnit / 10); if (quotientTimesTen % 10 >= 5) { quotientTimesTen += 10; } return quotientTimesTen / 10; } /** * @return The result of safely multiplying x and y, interpreting the operands * as fixed-point decimals of a precise unit. * * @dev The operands should be in the precise unit factor which will be * divided out after the product of x and y is evaluated, so that product must be * less than 2**256. * * Unlike multiplyDecimal, this function rounds the result to the nearest increment. * Rounding is useful when you need to retain fidelity for small decimal numbers * (eg. small fractions or percentages). */ function multiplyDecimalRoundPrecise(uint256 x, uint256 y) internal pure returns (uint256) { return _multiplyDecimalRound(x, y, PRECISE_UNIT); } /** * @return The result of safely multiplying x and y, interpreting the operands * as fixed-point decimals of a standard unit. * * @dev The operands should be in the standard unit factor which will be * divided out after the product of x and y is evaluated, so that product must be * less than 2**256. * * Unlike multiplyDecimal, this function rounds the result to the nearest increment. * Rounding is useful when you need to retain fidelity for small decimal numbers * (eg. small fractions or percentages). */ function multiplyDecimalRound(uint256 x, uint256 y) internal pure returns (uint256) { return _multiplyDecimalRound(x, y, UNIT); } /** * @return The result of safely dividing x and y. The return value is a high * precision decimal. * * @dev y is divided after the product of x and the standard precision unit * is evaluated, so the product of x and UNIT must be less than 2**256. As * this is an integer division, the result is always rounded down. * This helps save on gas. Rounding is more expensive on gas. */ function divideDecimal(uint256 x, uint256 y) internal pure returns (uint256) { /* Reintroduce the UNIT factor that will be divided out by y. */ return x.mul(UNIT).div(y); } /** * @return The result of safely dividing x and y. The return value is as a rounded * decimal in the precision unit specified in the parameter. * * @dev y is divided after the product of x and the specified precision unit * is evaluated, so the product of x and the specified precision unit must * be less than 2**256. The result is rounded to the nearest increment. */ function _divideDecimalRound( uint256 x, uint256 y, uint256 precisionUnit ) private pure returns (uint256) { uint256 resultTimesTen = x.mul(precisionUnit * 10).div(y); if (resultTimesTen % 10 >= 5) { resultTimesTen += 10; } return resultTimesTen / 10; } /** * @return The result of safely dividing x and y. The return value is as a rounded * standard precision decimal. * * @dev y is divided after the product of x and the standard precision unit * is evaluated, so the product of x and the standard precision unit must * be less than 2**256. The result is rounded to the nearest increment. */ function divideDecimalRound(uint256 x, uint256 y) internal pure returns (uint256) { return _divideDecimalRound(x, y, UNIT); } /** * @return The result of safely dividing x and y. The return value is as a rounded * high precision decimal. * * @dev y is divided after the product of x and the high precision unit * is evaluated, so the product of x and the high precision unit must * be less than 2**256. The result is rounded to the nearest increment. */ function divideDecimalRoundPrecise(uint256 x, uint256 y) internal pure returns (uint256) { return _divideDecimalRound(x, y, PRECISE_UNIT); } /** * @dev Convert a standard decimal representation to a high precision one. */ function decimalToPreciseDecimal(uint256 i) internal pure returns (uint256) { return i.mul(UNIT_TO_HIGH_PRECISION_CONVERSION_FACTOR); } /** * @dev Convert a high precision decimal to a standard decimal representation. */ function preciseDecimalToDecimal(uint256 i) internal pure returns (uint256) { uint256 quotientTimesTen = i / (UNIT_TO_HIGH_PRECISION_CONVERSION_FACTOR / 10); if (quotientTimesTen % 10 >= 5) { quotientTimesTen += 10; } return quotientTimesTen / 10; } } // SPDX-License-Identifier: MIT pragma solidity =0.7.6; import "../tokens/interfaces/ISupplyControlledERC20.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/utils/Address.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; /** * @title SafeSupplyControlledERC20 * @dev Wrappers around Supply Controlled 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. */ library SafeSupplyControlledERC20 { using SafeMath for uint256; using Address for address; function safeBurnFrom( ISupplyControlledERC20 token, address from, uint256 value ) internal { _callOptionalReturn( token, abi.encodeWithSelector(token.burnFrom.selector, from, value) ); } function safeMint( ISupplyControlledERC20 token, address to, uint256 value ) internal { _callOptionalReturn( token, abi.encodeWithSelector(token.mint.selector, to, value) ); } /** * @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, "SafeSupplyControlled/LowlevelCallFailed" ); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require( abi.decode(returndata, (bool)), "SafeSupplyControlled/ERC20Failed" ); } } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Library for managing * https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive * types. * * Sets have the following properties: * * - Elements are added, removed, and checked for existence in constant time * (O(1)). * - Elements are enumerated in O(n). No guarantees are made on the ordering. * * ``` * contract Example { * // Add the library methods * using EnumerableSet for EnumerableSet.AddressSet; * * // Declare a set state variable * EnumerableSet.AddressSet private mySet; * } * ``` * * As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`) * and `uint256` (`UintSet`) are supported. */ library EnumerableSet { // To implement this library for multiple types with as little code // repetition as possible, we write it in terms of a generic Set type with // bytes32 values. // The Set implementation uses private functions, and user-facing // implementations (such as AddressSet) are just wrappers around the // underlying Set. // This means that we can only create new EnumerableSets for types that fit // in bytes32. struct Set { // Storage of set values bytes32[] _values; // Position of the value in the `values` array, plus 1 because index 0 // means a value is not in the set. mapping (bytes32 => uint256) _indexes; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function _add(Set storage set, bytes32 value) private returns (bool) { if (!_contains(set, value)) { set._values.push(value); // The value is stored at length-1, but we add 1 to all indexes // and use 0 as a sentinel value set._indexes[value] = set._values.length; return true; } else { return false; } } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function _remove(Set storage set, bytes32 value) private returns (bool) { // We read and store the value's index to prevent multiple reads from the same storage slot uint256 valueIndex = set._indexes[value]; if (valueIndex != 0) { // Equivalent to contains(set, value) // To delete an element from the _values array in O(1), we swap the element to delete with the last one in // the array, and then remove the last element (sometimes called as 'swap and pop'). // This modifies the order of the array, as noted in {at}. uint256 toDeleteIndex = valueIndex - 1; uint256 lastIndex = set._values.length - 1; // When the value to delete is the last one, the swap operation is unnecessary. However, since this occurs // so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement. bytes32 lastvalue = set._values[lastIndex]; // Move the last value to the index where the value to delete is set._values[toDeleteIndex] = lastvalue; // Update the index for the moved value set._indexes[lastvalue] = toDeleteIndex + 1; // All indexes are 1-based // Delete the slot where the moved value was stored set._values.pop(); // Delete the index for the deleted slot delete set._indexes[value]; return true; } else { return false; } } /** * @dev Returns true if the value is in the set. O(1). */ function _contains(Set storage set, bytes32 value) private view returns (bool) { return set._indexes[value] != 0; } /** * @dev Returns the number of values on the set. O(1). */ function _length(Set storage set) private view returns (uint256) { return set._values.length; } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function _at(Set storage set, uint256 index) private view returns (bytes32) { require(set._values.length > index, "EnumerableSet: index out of bounds"); return set._values[index]; } // Bytes32Set struct Bytes32Set { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _add(set._inner, value); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _remove(set._inner, value); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) { return _contains(set._inner, value); } /** * @dev Returns the number of values in the set. O(1). */ function length(Bytes32Set storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) { return _at(set._inner, index); } // AddressSet struct AddressSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(AddressSet storage set, address value) internal returns (bool) { return _add(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(AddressSet storage set, address value) internal returns (bool) { return _remove(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(AddressSet storage set, address value) internal view returns (bool) { return _contains(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Returns the number of values in the set. O(1). */ function length(AddressSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(AddressSet storage set, uint256 index) internal view returns (address) { return address(uint160(uint256(_at(set._inner, index)))); } // UintSet struct UintSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(UintSet storage set, uint256 value) internal returns (bool) { return _add(set._inner, bytes32(value)); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(UintSet storage set, uint256 value) internal returns (bool) { return _remove(set._inner, bytes32(value)); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(UintSet storage set, uint256 value) internal view returns (bool) { return _contains(set._inner, bytes32(value)); } /** * @dev Returns the number of values on the set. O(1). */ function length(UintSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(UintSet storage set, uint256 index) internal view returns (uint256) { return uint256(_at(set._inner, index)); } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.2 <0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: value }(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.delegatecall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Interface of the 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.5.0; /// @title Auction House state that can change by governance. /// @notice These methods provide vision on specific state that could be used in wrapper contracts. interface IAuctionHouseState { /** * @notice The buffer around the starting price to handle mispriced / stale oracles. * @dev Basis point * Starts at 10% / 1e3 so market price is buffered by 110% or 90% */ function buffer() external view returns (uint16); /** * @notice The fee taken by the protocol. * @dev Basis point */ function protocolFee() external view returns (uint16); /** * @notice The cap based on total FLOAT supply to change in a single auction. E.g. 10% cap => absolute max of 10% of total supply can be minted / burned * @dev Basis point */ function allowanceCap() external view returns (uint32); } // SPDX-License-Identifier: MIT pragma solidity ^0.7.6; pragma abicoder v2; import "./ICases.sol"; /// @title Auction House state that can change /// @notice These methods compose the auctions state, and will change per action. interface IAuctionHouseVariables is ICases { /** * @notice The number of auctions since inception. */ function round() external view returns (uint64); /** * @notice Returns data about a specific auction. * @param roundNumber The round number for the auction array to fetch * @return stabilisationCase The Auction struct including case */ function auctions(uint64 roundNumber) external view returns ( Cases stabilisationCase, uint256 targetFloatInEth, uint256 marketFloatInEth, uint256 bankInEth, uint256 startWethPrice, uint256 startBankPrice, uint256 endWethPrice, uint256 endBankPrice, uint256 basketFactor, uint256 delta, uint256 allowance ); } // SPDX-License-Identifier: MIT pragma solidity ^0.7.6; pragma abicoder v2; import "./IAuction.sol"; /// @title Auction House state that can change /// @notice These methods are derived from the IAuctionHouseState. interface IAuctionHouseDerivedState is IAuction { /** * @notice The price (that the Protocol with expect on expansion, and give on Contraction) for 1 FLOAT * @dev Under cases, this value is used differently: * - Contraction, Protocol buys FLOAT for pair. * - Expansion, Protocol sells FLOAT for pair. * @return wethPrice [e27] Expected price in wETH. * @return bankPrice [e27] Expected price in BANK. */ function price() external view returns (uint256 wethPrice, uint256 bankPrice); /** * @notice The current step through the auction. * @dev block numbers since auction start (0 indexed) */ function step() external view returns (uint256); /** * @notice Latest Auction alias */ function latestAuction() external view returns (Auction memory); } // SPDX-License-Identifier: MIT pragma solidity ^0.7.6; pragma abicoder v2; /// @title Open Auction House actions /// @notice Contains all actions that can be called by anyone interface IAuctionHouseActions { /** * @notice Starts an auction * @dev This will: * - update the oracles * - calculate the target price * - check stabilisation case * - create allowance. * - Set start / end prices of the auction */ function start() external returns (uint64 newRound); /** * @notice Buy for an amount of <WETH, BANK> for as much FLOAT tokens as possible. * @dev Expansion, Protocol sells FLOAT for pair. As the price descends there should be no opportunity for slippage causing failure `msg.sender` should already have given the auction allowance for at least `wethIn` and `bankIn`. * `wethInMax` / `bankInMax` < 2**256 / 10**18, assumption is that totalSupply * doesn't exceed type(uint128).max * @param wethInMax The max amount of WETH to send (takes maximum from given ratio). * @param bankInMax The max amount of BANK to send (takes maximum from given ratio). * @param floatOutMin The minimum amount of FLOAT that must be received for this transaction not to revert. * @param to Recipient of the FLOAT. * @param deadline Unix timestamp after which the transaction will revert. */ function buy( uint256 wethInMax, uint256 bankInMax, uint256 floatOutMin, address to, uint256 deadline ) external returns ( uint256 usedWethIn, uint256 usedBankIn, uint256 usedFloatOut ); /** * @notice Sell an amount of FLOAT for the given reward tokens. * @dev Contraction, Protocol buys FLOAT for pair. `msg.sender` should already have given the auction allowance for at least `floatIn`. * @param floatIn The amount of FLOAT to sell. * @param wethOutMin The minimum amount of WETH that can be received before the transaction reverts. * @param bankOutMin The minimum amount of BANK that can be received before the tranasction reverts. * @param to Recipient of <WETH, BANK>. * @param deadline Unix timestamp after which the transaction will revert. */ function sell( uint256 floatIn, uint256 wethOutMin, uint256 bankOutMin, address to, uint256 deadline ) external returns ( uint256 usedfloatIn, uint256 usedWethOut, uint256 usedBankOut ); } // SPDX-License-Identifier: MIT pragma solidity ^0.7.6; pragma abicoder v2; /// @title Auction House actions that require certain level of privilege /// @notice Contains Auction House methods that may only be called by controller interface IAuctionHouseGovernedActions { /** * @notice Modify a uint256 parameter * @param parameter The parameter name to modify * @param data New value for the parameter */ function modifyParameters(bytes32 parameter, uint256 data) external; /** * @notice Modify an address parameter * @param parameter The parameter name to modify * @param data New address for the parameter */ function modifyParameters(bytes32 parameter, address data) external; } // SPDX-License-Identifier: MIT pragma solidity ^0.7.6; pragma abicoder v2; /// @title Events emitted by the auction house /// @notice Contains all events emitted by the auction house interface IAuctionHouseEvents { event NewAuction( uint256 indexed round, uint256 allowance, uint256 targetFloatInEth, uint256 startBlock ); event Buy( uint256 indexed round, address indexed buyer, uint256 wethIn, uint256 bankIn, uint256 floatOut ); event Sell( uint256 indexed round, address indexed seller, uint256 floatIn, uint256 wethOut, uint256 bankOut ); event ModifyParameters(bytes32 parameter, uint256 data); event ModifyParameters(bytes32 parameter, address data); } // SPDX-License-Identifier: MIT pragma solidity ^0.7.6; pragma abicoder v2; interface ICases { /** * @dev The Stabilisation Cases * Up (Expansion) - Estimated market price >= target price & Basket Factor >= 1. * Restock (Expansion) - Estimated market price >= target price & Basket Factor < 1. * Confidence (Contraction) - Estimated market price < target price & Basket Factor >= 1. * Down (Contraction) - Estimated market price < target price & Basket Factor < 1. */ enum Cases {Up, Restock, Confidence, Down} } // SPDX-License-Identifier: MIT pragma solidity ^0.7.6; pragma abicoder v2; import "./ICases.sol"; interface IAuction is ICases { /** * The current Stabilisation Case * Auction's target price. * Auction's floatInEth price. * Auction's bankInEth price. * Auction's basket factor. * Auction's used float delta. * Auction's allowed float delta (how much FLOAT can be created or burned). */ struct Auction { Cases stabilisationCase; uint256 targetFloatInEth; uint256 marketFloatInEth; uint256 bankInEth; uint256 startWethPrice; uint256 startBankPrice; uint256 endWethPrice; uint256 endBankPrice; uint256 basketFactor; uint256 delta; uint256 allowance; } } // SPDX-License-Identifier: UNLICENSED pragma solidity =0.7.6; pragma abicoder v2; import "../AuctionHouse.sol"; contract AuctionHouseHarness is AuctionHouse { uint256 public blockNumber; constructor( // Dependencies address _weth, address _bank, address _float, address _basket, address _monetaryPolicy, address _gov, address _bankEthOracle, address _floatEthOracle, // Parameters uint16 _auctionDuration, uint32 _auctionCooldown, uint256 _firstAuctionBlock ) AuctionHouse( _weth, _bank, _float, _basket, _monetaryPolicy, _gov, _bankEthOracle, _floatEthOracle, _auctionDuration, _auctionCooldown, _firstAuctionBlock ) {} function _blockNumber() internal view override returns (uint256) { return blockNumber; } // Private Var checkers function __weth() external view returns (address) { return address(weth); } function __bank() external view returns (address) { return address(bank); } function __float() external view returns (address) { return address(float); } function __basket() external view returns (address) { return address(basket); } function __monetaryPolicy() external view returns (address) { return address(monetaryPolicy); } function __bankEthOracle() external view returns (address) { return address(bankEthOracle); } function __floatEthOracle() external view returns (address) { return address(floatEthOracle); } function __auctionDuration() external view returns (uint16) { return auctionDuration; } function __auctionCooldown() external view returns (uint32) { return auctionCooldown; } function __mine(uint256 _blocks) external { blockNumber = blockNumber + _blocks; } function __setBlock(uint256 _number) external { blockNumber = _number; } function __setCap(uint256 _cap) external { allowanceCap = uint32(_cap); } } // SPDX-License-Identifier: MIT pragma solidity =0.7.6; pragma abicoder v2; import "@openzeppelin/contracts/utils/ReentrancyGuard.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "@openzeppelin/contracts/math/Math.sol"; import "./interfaces/basket/IBasketReader.sol"; import "./interfaces/IMintingCeremony.sol"; import "../external-lib/SafeDecimalMath.sol"; import "../lib/Recoverable.sol"; import "../lib/Windowed.sol"; import "../tokens/SafeSupplyControlledERC20.sol"; import "../tokens/interfaces/ISupplyControlledERC20.sol"; import "../policy/interfaces/IMonetaryPolicy.sol"; /** * @title Minting Ceremony * @dev Note that this is recoverable as it should never store any tokens. */ contract MintingCeremony is IMintingCeremony, Windowed, Recoverable, ReentrancyGuard { using SafeMath for uint256; using SafeDecimalMath for uint256; using SafeERC20 for IERC20; using SafeERC20 for ISupplyControlledERC20; using SafeSupplyControlledERC20 for ISupplyControlledERC20; /* ========== CONSTANTS ========== */ uint8 public constant ALLOWANCE_FACTOR = 100; uint32 private constant CEREMONY_DURATION = 6 days; /* ========== STATE VARIABLES ========== */ // Monetary Policy Contract that decides the target price IMonetaryPolicy internal immutable monetaryPolicy; ISupplyControlledERC20 internal immutable float; IBasketReader internal immutable basket; // Tokens that set allowance IERC20[] internal allowanceTokens; uint256 private _totalSupply; mapping(address => uint256) private _balances; /** * @notice Constructs a new Minting Ceremony */ constructor( address governance_, address monetaryPolicy_, address basket_, address float_, address[] memory allowanceTokens_, uint256 ceremonyStart ) Windowed(ceremonyStart, ceremonyStart + CEREMONY_DURATION) { require(governance_ != address(0), "MC/ZeroAddress"); require(monetaryPolicy_ != address(0), "MC/ZeroAddress"); require(basket_ != address(0), "MC/ZeroAddress"); require(float_ != address(0), "MC/ZeroAddress"); monetaryPolicy = IMonetaryPolicy(monetaryPolicy_); basket = IBasketReader(basket_); float = ISupplyControlledERC20(float_); for (uint256 i = 0; i < allowanceTokens_.length; i++) { IERC20 allowanceToken = IERC20(allowanceTokens_[i]); allowanceToken.balanceOf(address(0)); // Check that this is a valid token allowanceTokens.push(allowanceToken); } _setupRole(RECOVER_ROLE, governance_); } /* ========== EVENTS ========== */ event Committed(address indexed user, uint256 amount); event Minted(address indexed user, uint256 amount); /* ========== VIEWS ========== */ function totalSupply() public view returns (uint256) { return _totalSupply; } function balanceOf(address account) public view returns (uint256) { return _balances[account]; } function underlying() public view override(IMintingCeremony) returns (address) { return basket.underlying(); } /** * @notice The allowance remaining for an account. * @dev Based on the current staked balance in `allowanceTokens` and the existing allowance. */ function allowance(address account) public view override(IMintingCeremony) returns (uint256 remainingAllowance) { uint256 stakedBalance = 0; for (uint256 i = 0; i < allowanceTokens.length; i++) { stakedBalance = stakedBalance.add(allowanceTokens[i].balanceOf(account)); } remainingAllowance = stakedBalance.mul(ALLOWANCE_FACTOR).sub( _balances[account] ); } /** * @notice Simple conversion using monetary policy. */ function quote(uint256 wethIn) public view returns (uint256) { uint256 targetPriceInEth = monetaryPolicy.consult(); require(targetPriceInEth != 0, "MC/MPFailure"); return wethIn.divideDecimalRoundPrecise(targetPriceInEth); } /** * @notice The amount out accounting for quote & allowance. */ function amountOut(address recipient, uint256 underlyingIn) public view returns (uint256 floatOut) { // External calls occur here, but trusted uint256 floatOutFromPrice = quote(underlyingIn); uint256 floatOutFromAllowance = allowance(recipient); floatOut = Math.min(floatOutFromPrice, floatOutFromAllowance); } /* ========== MUTATIVE FUNCTIONS ========== */ /** * @notice Commit a quanity of wETH at the current price * @dev This is marked non-reentrancy to protect against a malicious * allowance token or monetary policy (these are trusted however). * * - Expects `msg.sender` to give approval to this contract from `basket.underlying()` for at least `underlyingIn` * * @param recipient The eventual receiver of the float * @param underlyingIn The underlying token amount to commit to mint * @param floatOutMin The minimum amount of FLOAT that must be received for this transaction not to revert. */ function commit( address recipient, uint256 underlyingIn, uint256 floatOutMin ) external override(IMintingCeremony) nonReentrant inWindow returns (uint256 floatOut) { floatOut = amountOut(recipient, underlyingIn); require(floatOut >= floatOutMin, "MC/SlippageOrLowAllowance"); require(floatOut != 0, "MC/NoAllowance"); _totalSupply = _totalSupply.add(floatOut); _balances[recipient] = _balances[recipient].add(floatOut); emit Committed(recipient, floatOut); IERC20(underlying()).safeTransferFrom( msg.sender, address(basket), underlyingIn ); } /** * @notice Release the float to market which has been committed. */ function mint() external override(IMintingCeremony) afterWindow { uint256 balance = balanceOf(msg.sender); require(balance != 0, "MC/NotDueFloat"); _totalSupply = _totalSupply.sub(balance); _balances[msg.sender] = _balances[msg.sender].sub(balance); emit Minted(msg.sender, balance); float.safeMint(msg.sender, balance); } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Contract module that helps prevent reentrant calls to a function. * * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier * available, which can be applied to functions to make sure there are no nested * (reentrant) calls to them. * * Note that because there is a single `nonReentrant` guard, functions marked as * `nonReentrant` may not call one another. This can be worked around by making * those functions `private`, and then adding `external` `nonReentrant` entry * points to them. * * TIP: If you would like to learn more about reentrancy and alternative ways * to protect against it, check out our blog post * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul]. */ abstract contract ReentrancyGuard { // Booleans are more expensive than uint256 or any type that takes up a full // word because each write operation emits an extra SLOAD to first read the // slot's contents, replace the bits taken up by the boolean, and then write // back. This is the compiler's defense against contract upgrades and // pointer aliasing, and it cannot be disabled. // The values being non-zero value makes deployment a bit more expensive, // but in exchange the refund on every call to nonReentrant will be lower in // amount. Since refunds are capped to a percentage of the total // transaction's gas, it is best to keep them low in cases like this one, to // increase the likelihood of the full refund coming into effect. uint256 private constant _NOT_ENTERED = 1; uint256 private constant _ENTERED = 2; uint256 private _status; constructor () internal { _status = _NOT_ENTERED; } /** * @dev Prevents a contract from calling itself, directly or indirectly. * Calling a `nonReentrant` function from another `nonReentrant` * function is not supported. It is possible to prevent this from happening * by making the `nonReentrant` function external, and make it call a * `private` function that does the actual work. */ modifier nonReentrant() { // On the first call to nonReentrant, _notEntered will be true require(_status != _ENTERED, "ReentrancyGuard: reentrant call"); // Any calls to nonReentrant after this point will fail _status = _ENTERED; _; // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) _status = _NOT_ENTERED; } } // SPDX-License-Identifier: MIT pragma solidity =0.7.6; /** * @title Minting Ceremony */ interface IMintingCeremony { function allowance(address account) external view returns (uint256 remainingAllowance); function underlying() external view returns (address); function commit( address recipient, uint256 underlyingIn, uint256 floatOutMin ) external returns (uint256 floatOut); function mint() external; } // SPDX-License-Identifier: MIT pragma solidity =0.7.6; // The Window is time-based so will rely on time, however period > 30 minutes // minimise the risk of oracle manipulation. // solhint-disable not-rely-on-time /** * @title A windowed contract * @notice Provides a window for actions to occur */ contract Windowed { /* ========== STATE VARIABLES ========== */ /** * @notice The timestamp of the window start */ uint256 public startWindow; /** * @notice The timestamp of the window end */ uint256 public endWindow; /* ========== CONSTRUCTOR ========== */ constructor(uint256 _startWindow, uint256 _endWindow) { require(_startWindow > block.timestamp, "Windowed/StartInThePast"); require(_endWindow > _startWindow + 1 days, "Windowed/MustHaveDuration"); startWindow = _startWindow; endWindow = _endWindow; } /* ========== MODIFIERS ========== */ modifier inWindow() { require(block.timestamp >= startWindow, "Windowed/HasNotStarted"); require(block.timestamp <= endWindow, "Windowed/HasEnded"); _; } modifier afterWindow() { require(block.timestamp > endWindow, "Windowed/NotEnded"); _; } } // SPDX-License-Identifier: MIT pragma solidity =0.7.6; import "../MintingCeremony.sol"; contract MintingCeremonyHarness is MintingCeremony { constructor( address governance_, address monetaryPolicy_, address basket_, address float_, address[] memory allowanceTokens_, uint256 ceremonyStart ) MintingCeremony( governance_, monetaryPolicy_, basket_, float_, allowanceTokens_, ceremonyStart ) {} function __monetaryPolicy() external view returns (address) { return address(monetaryPolicy); } function __basket() external view returns (address) { return address(basket); } function __float() external view returns (address) { return address(float); } function __allowanceTokens(uint256 idx) external view returns (address) { return address(allowanceTokens[idx]); } } // SPDX-License-Identifier: MIT pragma solidity =0.7.6; import "@openzeppelin/contracts/access/AccessControl.sol"; import "./interfaces/IMonetaryPolicy.sol"; import "../lib/BlockNumber.sol"; import "../lib/MathHelper.sol"; import "../external-lib/SafeDecimalMath.sol"; import "../oracle/interfaces/IEthUsdOracle.sol"; contract MonetaryPolicyV1 is IMonetaryPolicy, BlockNumber, AccessControl { using SafeMath for uint256; using SafeDecimalMath for uint256; /* ========== CONSTANTS ========== */ bytes32 public constant GOVERNANCE_ROLE = keccak256("GOVERNANCE_ROLE"); bytes32 public constant AUCTION_HOUSE_ROLE = keccak256("AUCTION_HOUSE_ROLE"); // 0.001$ <= Target Price <= 1000$ as a basic sense check uint256 private constant MAX_TARGET_PRICE = 1000e27; uint256 private constant MIN_TARGET_PRICE = 0.001e27; uint256 private constant MAX_PRICE_DELTA_BOUND = 1e27; uint256 private constant DEFAULT_MAX_PRICE_DELTA = 4e27; uint256 private constant DEFAULT_MAX_ADJ_PERIOD = 1e6; uint256 private constant DEFAULT_MIN_ADJ_PERIOD = 2e5; // 150 blocks (auction duration) < T_min < T_max < 10 000 000 (~4yrs) uint256 private constant CAP_MAX_ADJ_PERIOD = 1e7; uint256 private constant CAP_MIN_ADJ_PERIOD = 150; /** * @notice The default FLOAT starting price, golden ratio * @dev [e27] */ uint256 public constant STARTING_PRICE = 1.618033988749894848204586834e27; /* ========== STATE VARIABLES ========== */ /** * @notice The FLOAT target price in USD. * @dev [e27] */ uint256 public targetPrice = STARTING_PRICE; /** * @notice If dynamic pricing is enabled. */ bool public dynamicPricing = true; /** * @notice Maximum price Delta of 400% */ uint256 public maxPriceDelta = DEFAULT_MAX_PRICE_DELTA; /** * @notice Maximum adjustment period T_max (Blocks) * @dev "How long it takes us to normalise" * - T_max => T_min, quicker initial response with higher price changes. */ uint256 public maxAdjustmentPeriod = DEFAULT_MAX_ADJ_PERIOD; /** * @notice Minimum adjustment period T_min (Blocks) * @dev "How quickly we respond to market price changes" * - Low T_min, increased tracking. */ uint256 public minAdjustmentPeriod = DEFAULT_MIN_ADJ_PERIOD; /** * @notice Provides the ETH-USD exchange rate e.g. 1.5e27 would mean 1 ETH = $1.5 * @dev [e27] decimal fixed point number */ IEthUsdOracle public ethUsdOracle; /* ========== CONSTRUCTOR ========== */ /** * @notice Construct a new Monetary Policy * @param _governance Governance address (can add new roles & parameter control) * @param _ethUsdOracle The [e27] ETH USD price feed. */ constructor(address _governance, address _ethUsdOracle) { ethUsdOracle = IEthUsdOracle(_ethUsdOracle); // Roles _setupRole(DEFAULT_ADMIN_ROLE, _governance); _setupRole(GOVERNANCE_ROLE, _governance); } /* ========== MODIFIERS ========== */ modifier onlyGovernance { require(hasRole(GOVERNANCE_ROLE, msg.sender), "MonetaryPolicy/OnlyGovRole"); _; } modifier onlyAuctionHouse { require( hasRole(AUCTION_HOUSE_ROLE, msg.sender), "MonetaryPolicy/OnlyAuctionHouse" ); _; } /* ========== VIEWS ========== */ /** * @notice Consult monetary policy to get the current target price of FLOAT in ETH * @dev [e27] */ function consult() public view override(IMonetaryPolicy) returns (uint256) { if (!dynamicPricing) return _toEth(STARTING_PRICE); return _toEth(targetPrice); } /* ========== RESTRICTED FUNCTIONS ========== */ /* ----- onlyGovernance ----- */ /** * @notice Updates the EthUsdOracle * @param _ethUsdOracle The address of the ETH-USD price oracle. */ function setEthUsdOracle(address _ethUsdOracle) external onlyGovernance { require(_ethUsdOracle != address(0), "MonetaryPolicyV1/ValidAddress"); ethUsdOracle = IEthUsdOracle(_ethUsdOracle); } /** * @notice Set the target price of FLOAT * @param _targetPrice [e27] */ function setTargetPrice(uint256 _targetPrice) external onlyGovernance { require(_targetPrice <= MAX_TARGET_PRICE, "MonetaryPolicyV1/MaxTarget"); require(_targetPrice >= MIN_TARGET_PRICE, "MonetaryPolicyV1/MinTarget"); targetPrice = _targetPrice; } /** * @notice Allows dynamic pricing to be turned on / off. */ function setDynamicPricing(bool _dynamicPricing) external onlyGovernance { dynamicPricing = _dynamicPricing; } /** * @notice Allows monetary policy parameters to be adjusted. */ function setPolicyParameters( uint256 _minAdjustmentPeriod, uint256 _maxAdjustmentPeriod, uint256 _maxPriceDelta ) external onlyGovernance { require( _minAdjustmentPeriod < _maxAdjustmentPeriod, "MonetaryPolicyV1/MinAdjLTMaxAdj" ); require( _maxAdjustmentPeriod <= CAP_MAX_ADJ_PERIOD, "MonetaryPolicyV1/MaxAdj" ); require( _minAdjustmentPeriod >= CAP_MIN_ADJ_PERIOD, "MonetaryPolicyV1/MinAdj" ); require( _maxPriceDelta >= MAX_PRICE_DELTA_BOUND, "MonetaryPolicyV1/MaxDeltaBound" ); minAdjustmentPeriod = _minAdjustmentPeriod; maxAdjustmentPeriod = _maxAdjustmentPeriod; maxPriceDelta = _maxPriceDelta; } /* ----- onlyAuctionHouse ----- */ /** * @notice Updates with previous auctions result * @dev future:param round Round number * @param lastAuctionBlock The last time an auction started. * @param floatMarketPriceInEth [e27] The current float market price (ETH) * @param basketFactor [e27] The basket factor given the prior target price * @return targetPriceInEth [e27] */ function updateGivenAuctionResults( uint256, uint256 lastAuctionBlock, uint256 floatMarketPriceInEth, uint256 basketFactor ) external override(IMonetaryPolicy) onlyAuctionHouse returns (uint256) { // Exit early if this is the first auction if (lastAuctionBlock == 0) { return consult(); } return _updateTargetPrice(lastAuctionBlock, floatMarketPriceInEth, basketFactor); } /** * @dev Converts [e27] USD price, to an [e27] ETH Price */ function _toEth(uint256 price) internal view returns (uint256) { uint256 ethInUsd = ethUsdOracle.consult(); return price.divideDecimalRoundPrecise(ethInUsd); } /** * @dev Updates the $ valued target price, returns the eth valued target price. */ function _updateTargetPrice( uint256 _lastAuctionBlock, uint256 _floatMarketPriceInEth, uint256 _basketFactor ) internal returns (uint256) { // _toEth pulled out as we do a _fromEth later. uint256 ethInUsd = ethUsdOracle.consult(); uint256 priorTargetPriceInEth = targetPrice.divideDecimalRoundPrecise(ethInUsd); // Check if basket and FLOAT are moving the same direction bool basketFactorDown = _basketFactor < SafeDecimalMath.PRECISE_UNIT; bool floatDown = _floatMarketPriceInEth < priorTargetPriceInEth; if (basketFactorDown != floatDown) { return priorTargetPriceInEth; } // N.B: block number will always be >= _lastAuctionBlock uint256 auctionTimePeriod = _blockNumber().sub(_lastAuctionBlock); uint256 normDelta = _normalisedDelta(_floatMarketPriceInEth, priorTargetPriceInEth); uint256 adjustmentPeriod = _adjustmentPeriod(normDelta); // [e27] uint256 basketFactorDiff = MathHelper.diff(_basketFactor, SafeDecimalMath.PRECISE_UNIT); uint256 targetChange = priorTargetPriceInEth.multiplyDecimalRoundPrecise( basketFactorDiff.mul(auctionTimePeriod).div(adjustmentPeriod) ); // If we have got this far, then we know that market and basket are // in the same direction, so basketFactor can be used to choose direction. uint256 targetPriceInEth = basketFactorDown ? priorTargetPriceInEth.sub(targetChange) : priorTargetPriceInEth.add(targetChange); targetPrice = targetPriceInEth.multiplyDecimalRoundPrecise(ethInUsd); return targetPriceInEth; } function _adjustmentPeriod(uint256 _normDelta) internal view returns (uint256) { // calculate T, 'the adjustment period', similar to "lookback" as it controls the length of the tail // T = T_max - d (T_max - T_min). // = d * T_min + T_max - d * T_max // TBC: This doesn't need safety checks // T_min <= T <= T_max return minAdjustmentPeriod .multiplyDecimalRoundPrecise(_normDelta) .add(maxAdjustmentPeriod) .sub(maxAdjustmentPeriod.multiplyDecimalRoundPrecise(_normDelta)); } /** * @notice Obtain normalised delta between market and target price */ function _normalisedDelta( uint256 _floatMarketPriceInEth, uint256 _priorTargetPriceInEth ) internal view returns (uint256) { uint256 delta = MathHelper.diff(_floatMarketPriceInEth, _priorTargetPriceInEth); uint256 scaledDelta = delta.divideDecimalRoundPrecise(_priorTargetPriceInEth); // Invert delta if contraction to flip curve from concave increasing to convex decreasing // Also allows for a greater response in expansions than contractions. if (_floatMarketPriceInEth < _priorTargetPriceInEth) { scaledDelta = scaledDelta.divideDecimalRoundPrecise( SafeDecimalMath.PRECISE_UNIT.sub(scaledDelta) ); } // Normalise delta based on Dmax -> 0 <= d <= X uint256 normDelta = scaledDelta.divideDecimalRoundPrecise(maxPriceDelta); // Cap normalised delta 0 <= d <= 1 if (normDelta > SafeDecimalMath.PRECISE_UNIT) { normDelta = SafeDecimalMath.PRECISE_UNIT; } return normDelta; } } // SPDX-License-Identifier: MIT pragma solidity =0.7.6; library MathHelper { function diff(uint256 x, uint256 y) internal pure returns (uint256 z) { z = x > y ? x - y : y - x; } } // SPDX-License-Identifier: MIT pragma solidity =0.7.6; interface IEthUsdOracle { /** * @notice Spot price * @return price The latest price as an [e27] */ function consult() external view returns (uint256 price); } // SPDX-License-Identifier: MIT pragma solidity =0.7.6; import "@chainlink/contracts/src/v0.7/interfaces/AggregatorV3Interface.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; import "./interfaces/IEthUsdOracle.sol"; contract ChainlinkEthUsdConsumer is IEthUsdOracle { using SafeMath for uint256; /// @dev Number of decimal places in the representations. */ uint8 private constant AGGREGATOR_DECIMALS = 8; uint8 private constant PRICE_DECIMALS = 27; uint256 private constant UNIT_TO_HIGH_PRECISION_CONVERSION_FACTOR = 10**uint256(PRICE_DECIMALS - AGGREGATOR_DECIMALS); AggregatorV3Interface internal immutable priceFeed; /** * @notice Construct a new price consumer * @dev Source: https://docs.chain.link/docs/ethereum-addresses#config */ constructor(address aggregatorAddress) { priceFeed = AggregatorV3Interface(aggregatorAddress); } /// @inheritdoc IEthUsdOracle function consult() external view override(IEthUsdOracle) returns (uint256 price) { (, int256 _price, , , ) = priceFeed.latestRoundData(); require(_price >= 0, "ChainlinkConsumer/StrangeOracle"); return (price = uint256(_price).mul( UNIT_TO_HIGH_PRECISION_CONVERSION_FACTOR )); } /** * @notice Retrieves decimals of price feed * @dev (`AGGREGATOR_DECIMALS` for ETH-USD by default, scaled up to `PRICE_DECIMALS` here) */ function getDecimals() external pure returns (uint8 decimals) { return (decimals = PRICE_DECIMALS); } } // SPDX-License-Identifier: MIT pragma solidity >=0.7.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.6.0 <0.8.0; import "../../utils/Context.sol"; import "./IERC20.sol"; import "../../math/SafeMath.sol"; /** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20PresetMinterPauser}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin guidelines: functions revert instead * of returning `false` on failure. This behavior is nonetheless conventional * and does not conflict with the expectations of ERC20 applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */ contract ERC20 is Context, IERC20 { using SafeMath for uint256; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; uint8 private _decimals; /** * @dev Sets the values for {name} and {symbol}, initializes {decimals} with * a default value of 18. * * To select a different value for {decimals}, use {_setupDecimals}. * * All three of these values are immutable: they can only be set once during * construction. */ constructor (string memory name_, string memory symbol_) public { _name = name_; _symbol = symbol_; _decimals = 18; } /** * @dev Returns the name of the token. */ function name() public view 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 { } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "./ERC20.sol"; import "../../utils/Pausable.sol"; /** * @dev ERC20 token with pausable token transfers, minting and burning. * * Useful for scenarios such as preventing trades until the end of an evaluation * period, or having an emergency switch for freezing all token transfers in the * event of a large bug. */ abstract contract ERC20Pausable is ERC20, Pausable { /** * @dev See {ERC20-_beforeTokenTransfer}. * * Requirements: * * - the contract must not be paused. */ function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual override { super._beforeTokenTransfer(from, to, amount); require(!paused(), "ERC20Pausable: token transfer while paused"); } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "./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 () internal { _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.7.6; import "@openzeppelin/contracts/access/AccessControl.sol"; import "@openzeppelin/contracts/GSN/Context.sol"; import "@openzeppelin/contracts/math/Math.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "@openzeppelin/contracts/utils/Pausable.sol"; import "@openzeppelin/contracts/utils/ReentrancyGuard.sol"; import "synthetix/contracts/interfaces/IStakingRewards.sol"; import "./RewardDistributionRecipient.sol"; /** * @title Phase 2 BANK Reward Pool for Float Protocol * @notice This contract is used to reward `rewardToken` when `stakeToken` is staked. */ contract Phase2Pool is IStakingRewards, Context, AccessControl, RewardDistributionRecipient, ReentrancyGuard { using SafeMath for uint256; using SafeERC20 for IERC20; /* ========== CONSTANTS ========== */ uint256 public constant DURATION = 7 days; bytes32 public constant RECOVER_ROLE = keccak256("RECOVER_ROLE"); /* ========== STATE VARIABLES ========== */ IERC20 public rewardToken; IERC20 public stakeToken; uint256 public periodFinish = 0; uint256 public rewardRate = 0; uint256 public lastUpdateTime; uint256 public rewardPerTokenStored; mapping(address => uint256) public userRewardPerTokenPaid; mapping(address => uint256) public rewards; uint256 private _totalSupply; mapping(address => uint256) private _balances; /* ========== CONSTRUCTOR ========== */ /** * @notice Construct a new Phase2Pool * @param _admin The default role controller for * @param _rewardDistribution The reward distributor (can change reward rate) * @param _rewardToken The reward token to distribute * @param _stakingToken The staking token used to qualify for rewards */ constructor( address _admin, address _rewardDistribution, address _rewardToken, address _stakingToken ) RewardDistributionRecipient(_admin) { rewardDistribution = _rewardDistribution; rewardToken = IERC20(_rewardToken); stakeToken = IERC20(_stakingToken); _setupRole(DEFAULT_ADMIN_ROLE, _admin); _setupRole(RECOVER_ROLE, _admin); } /* ========== EVENTS ========== */ event RewardAdded(uint256 reward); event Staked(address indexed user, uint256 amount); event Withdrawn(address indexed user, uint256 amount); event RewardPaid(address indexed user, uint256 reward); event Recovered(address token, uint256 amount); /* ========== MODIFIERS ========== */ modifier updateReward(address account) { rewardPerTokenStored = rewardPerToken(); lastUpdateTime = lastTimeRewardApplicable(); if (account != address(0)) { rewards[account] = earned(account); userRewardPerTokenPaid[account] = rewardPerTokenStored; } _; } /* ========== VIEWS ========== */ function totalSupply() public view override(IStakingRewards) returns (uint256) { return _totalSupply; } function balanceOf(address account) public view override(IStakingRewards) returns (uint256) { return _balances[account]; } function lastTimeRewardApplicable() public view override(IStakingRewards) returns (uint256) { return Math.min(block.timestamp, periodFinish); } function rewardPerToken() public view override(IStakingRewards) returns (uint256) { if (totalSupply() == 0) { return rewardPerTokenStored; } return rewardPerTokenStored.add( lastTimeRewardApplicable() .sub(lastUpdateTime) .mul(rewardRate) .mul(1e18) .div(totalSupply()) ); } function earned(address account) public view override(IStakingRewards) returns (uint256) { return balanceOf(account) .mul(rewardPerToken().sub(userRewardPerTokenPaid[account])) .div(1e18) .add(rewards[account]); } function getRewardForDuration() external view override(IStakingRewards) returns (uint256) { return rewardRate.mul(DURATION); } /* ========== MUTATIVE FUNCTIONS ========== */ function stake(uint256 amount) public virtual override(IStakingRewards) updateReward(msg.sender) { require(amount > 0, "Phase2Pool::stake: Cannot stake 0"); _totalSupply = _totalSupply.add(amount); _balances[msg.sender] = _balances[msg.sender].add(amount); stakeToken.safeTransferFrom(msg.sender, address(this), amount); emit Staked(msg.sender, amount); } function withdraw(uint256 amount) public override(IStakingRewards) updateReward(msg.sender) { require(amount > 0, "Phase2Pool::withdraw: Cannot withdraw 0"); _totalSupply = _totalSupply.sub(amount); _balances[msg.sender] = _balances[msg.sender].sub(amount); stakeToken.safeTransfer(msg.sender, amount); emit Withdrawn(msg.sender, amount); } function exit() external override(IStakingRewards) { withdraw(balanceOf(msg.sender)); getReward(); } function getReward() public virtual override(IStakingRewards) updateReward(msg.sender) { uint256 reward = earned(msg.sender); if (reward > 0) { rewards[msg.sender] = 0; rewardToken.safeTransfer(msg.sender, reward); emit RewardPaid(msg.sender, reward); } } /* ========== RESTRICTED FUNCTIONS ========== */ /* ----- Reward Distributor ----- */ /** * @notice Should be called after the amount of reward tokens has been sent to the contract. Reward should be divisible by duration. * @param reward number of tokens to be distributed over the duration. */ function notifyRewardAmount(uint256 reward) external override onlyRewardDistribution updateReward(address(0)) { if (block.timestamp >= periodFinish) { rewardRate = reward.div(DURATION); } else { uint256 remaining = periodFinish.sub(block.timestamp); uint256 leftover = remaining.mul(rewardRate); rewardRate = reward.add(leftover).div(DURATION); } // Ensure provided reward amount is not more than the balance in the contract. // Keeps reward rate within the right range to prevent overflows in earned or rewardsPerToken // Reward + leftover < 1e18 uint256 balance = rewardToken.balanceOf(address(this)); require( rewardRate <= balance.div(DURATION), "Phase2Pool::notifyRewardAmount: Insufficent balance for reward rate" ); lastUpdateTime = block.timestamp; periodFinish = block.timestamp.add(DURATION); emit RewardAdded(reward); } /* ----- RECOVER_ROLE ----- */ /** * @notice Provide accidental token retrieval. * @dev Sourced from synthetix/contracts/StakingRewards.sol */ function recoverERC20(address tokenAddress, uint256 tokenAmount) external { require( hasRole(RECOVER_ROLE, _msgSender()), "Phase2Pool::recoverERC20: You must possess the recover role to recover erc20" ); require( tokenAddress != address(stakeToken), "Phase2Pool::recoverERC20: Cannot recover the staking token" ); require( tokenAddress != address(rewardToken), "Phase2Pool::recoverERC20: Cannot recover the reward token" ); IERC20(tokenAddress).safeTransfer(_msgSender(), tokenAmount); emit Recovered(tokenAddress, tokenAmount); } } pragma solidity >=0.4.24; // https://docs.synthetix.io/contracts/source/interfaces/istakingrewards interface IStakingRewards { // Views function lastTimeRewardApplicable() external view returns (uint256); function rewardPerToken() external view returns (uint256); function earned(address account) external view returns (uint256); function getRewardForDuration() external view returns (uint256); function totalSupply() external view returns (uint256); function balanceOf(address account) external view returns (uint256); // Mutative function stake(uint256 amount) external; function withdraw(uint256 amount) external; function getReward() external; function exit() external; } // SPDX-License-Identifier: MIT pragma solidity ^0.7.6; import "@openzeppelin/contracts/access/AccessControl.sol"; import "@openzeppelin/contracts/GSN/Context.sol"; abstract contract RewardDistributionRecipient is Context, AccessControl { bytes32 public constant DISTRIBUTION_ASSIGNER_ROLE = keccak256("DISTRIBUTION_ASSIGNER_ROLE"); address public rewardDistribution; constructor(address assigner) { _setupRole(DISTRIBUTION_ASSIGNER_ROLE, assigner); } modifier onlyRewardDistribution() { require( _msgSender() == rewardDistribution, "RewardDisributionRecipient::onlyRewardDistribution: Caller is not RewardsDistribution contract" ); _; } /* ========== RESTRICTED FUNCTIONS ========== */ /* ----- rewardDistribution ----- */ function notifyRewardAmount(uint256 reward) external virtual; /* ----- DISTRIBUTION_ASSIGNER_ROLE ----- */ function setRewardDistribution(address _rewardDistribution) external { require( hasRole(DISTRIBUTION_ASSIGNER_ROLE, _msgSender()), "RewardDistributionRecipient::setRewardDistribution: must have distribution assigner role" ); rewardDistribution = _rewardDistribution; } } // SPDX-License-Identifier: MIT pragma solidity ^0.7.6; import "./RewardDistributionRecipient.sol"; import "./interfaces/IStakingRewardWhitelisted.sol"; import "./Whitelisted.sol"; import "./Phase2Pool.sol"; contract Phase1Pool is Phase2Pool, Whitelisted, IStakingRewardWhitelisted { using SafeMath for uint256; using SafeERC20 for IERC20; /* ========== STATE VARIABLES ========== */ uint256 public maximumContribution; /* ========== CONSTRUCTOR ========== */ /** * @notice Construct a new Phase1Pool * @param _admin The default role controller for * @param _rewardDistribution The reward distributor (can change reward rate) * @param _whitelist The address of the deployed whitelist contract * @param _rewardToken The reward token to distribute * @param _stakingToken The staking token used to qualify for rewards * @param _maximumContribution The maximum contribution for this token (in the unit of the respective contract) */ constructor( address _admin, address _rewardDistribution, address _whitelist, address _rewardToken, address _stakingToken, uint256 _maximumContribution ) Phase2Pool(_admin, _rewardDistribution, _rewardToken, _stakingToken) { whitelist = IWhitelist(_whitelist); maximumContribution = _maximumContribution; } /* ========== MUTATIVE FUNCTIONS ========== */ function stake(uint256) public pure override(Phase2Pool, IStakingRewards) { revert( "Phase1Pool::stake: Cannot stake on Phase1Pool directly due to whitelist" ); } /* ========== RESTRICTED FUNCTIONS ========== */ /* ----- onlyWhitelisted ----- */ function stakeWithProof(uint256 amount, bytes32[] calldata proof) public override(IStakingRewardWhitelisted) onlyWhitelisted(proof) updateReward(msg.sender) { require( balanceOf(msg.sender).add(amount) <= maximumContribution, "Phase1Pool::stake: Cannot exceed maximum contribution" ); super.stake(amount); } } // SPDX-License-Identifier: MIT pragma solidity ^0.7.6; import "synthetix/contracts/interfaces/IStakingRewards.sol"; interface IStakingRewardWhitelisted is IStakingRewards { function stakeWithProof(uint256 amount, bytes32[] calldata proof) external; } // SPDX-License-Identifier: MIT pragma solidity ^0.7.6; import '@openzeppelin/contracts/GSN/Context.sol'; import './interfaces/IWhitelist.sol'; abstract contract Whitelisted is Context { IWhitelist public whitelist; modifier onlyWhitelisted(bytes32[] calldata proof) { require( whitelist.whitelisted(_msgSender(), proof), "Whitelisted::onlyWhitelisted: Caller is not whitelisted / proof invalid" ); _; } } // SPDX-License-Identifier: MIT pragma solidity >=0.5.2; interface IWhitelist { // Views function root() external view returns (bytes32); function uri() external view returns (string memory); function whitelisted(address account, bytes32[] memory proof) external view returns (bool); // Mutative function updateWhitelist(bytes32 _root, string memory _uri) external; } // SPDX-License-Identifier: MIT pragma solidity ^0.7.6; import "@openzeppelin/contracts/access/AccessControl.sol"; import "@openzeppelin/contracts/GSN/Context.sol"; import "./interfaces/IWhitelist.sol"; contract MerkleWhitelist is IWhitelist, Context, AccessControl { /* ========== CONSTANTS ========== */ bytes32 public constant WHITELISTER_ROLE = keccak256("WHITELISTER_ROLE"); /* ========== STATE VARIABLES ========== */ bytes32 public merkleRoot; string public sourceUri; /* ========== CONSTRUCTOR ========== */ /** * @notice Construct a new MerkleWhitelist * @param _admin The default role controller and whitelister for the contract. * @param _root The default merkleRoot. * @param _uri The link to the full whitelist. */ constructor( address _admin, bytes32 _root, string memory _uri ) { merkleRoot = _root; sourceUri = _uri; _setupRole(DEFAULT_ADMIN_ROLE, _admin); _setupRole(WHITELISTER_ROLE, _admin); } /* ========== EVENTS ========== */ event UpdatedWhitelist(bytes32 root, string uri); /* ========== VIEWS ========== */ function root() external view override(IWhitelist) returns (bytes32) { return merkleRoot; } function uri() external view override(IWhitelist) returns (string memory) { return sourceUri; } function whitelisted(address account, bytes32[] memory proof) public view override(IWhitelist) returns (bool) { // Need to include bytes1(0x00) in order to prevent pre-image attack. bytes32 leafHash = keccak256(abi.encodePacked(bytes1(0x00), account)); return checkProof(merkleRoot, proof, leafHash); } /* ========== PURE ========== */ function checkProof( bytes32 _root, bytes32[] memory _proof, bytes32 _leaf ) internal pure returns (bool) { bytes32 computedHash = _leaf; for (uint256 i = 0; i < _proof.length; i++) { bytes32 proofElement = _proof[i]; if (computedHash < proofElement) { computedHash = keccak256( abi.encodePacked(bytes1(0x01), computedHash, proofElement) ); } else { computedHash = keccak256( abi.encodePacked(bytes1(0x01), proofElement, computedHash) ); } } return computedHash == _root; } /* ========== RESTRICTED FUNCTIONS ========== */ /* ----- WHITELISTER_ROLE ----- */ function updateWhitelist(bytes32 root_, string memory uri_) public override(IWhitelist) { require( hasRole(WHITELISTER_ROLE, _msgSender()), "MerkleWhitelist::updateWhitelist: only whitelister may update the whitelist" ); merkleRoot = root_; sourceUri = uri_; emit UpdatedWhitelist(merkleRoot, sourceUri); } } // SPDX-License-Identifier: MIT pragma solidity ^0.7.6; import "@openzeppelin/contracts/access/AccessControl.sol"; import "@openzeppelin/contracts/GSN/Context.sol"; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "@openzeppelin/contracts/token/ERC20/ERC20Burnable.sol"; import "@openzeppelin/contracts/token/ERC20/ERC20Pausable.sol"; /** * @dev {ERC20} token, including: * * - ability for holders to burn (destroy) their tokens * - a pauser role that allows to stop all token transfers * * This contract uses {AccessControl} to lock permissioned functions using the * different roles - head to its documentation for details. * * This has an open mint functionality */ contract TokenMock is Context, AccessControl, ERC20Burnable, ERC20Pausable { bytes32 public constant PAUSER_ROLE = keccak256("PAUSER_ROLE"); /** * @dev Grants `DEFAULT_ADMIN_ROLE`, and `PAUSER_ROLE` to the * account that deploys the contract. * * See {ERC20-constructor}. */ constructor( address _admin, string memory _name, string memory _symbol, uint8 _decimals ) ERC20(_name, _symbol) { _setupRole(DEFAULT_ADMIN_ROLE, _admin); _setupRole(PAUSER_ROLE, _admin); _setupDecimals(_decimals); } /** * @dev Creates `amount` new tokens for `to`. * * See {ERC20-_mint}. * */ function mint(address to, uint256 amount) external virtual { _mint(to, amount); } /** * @dev Pauses all token transfers. * * See {ERC20Pausable} and {Pausable-_pause}. * * Requirements: * * - the caller must have the `PAUSER_ROLE`. */ function pause() external virtual { require(hasRole(PAUSER_ROLE, _msgSender()), "TokenMock/PauserRole"); _pause(); } /** * @dev Unpauses all token transfers. * * See {ERC20Pausable} and {Pausable-_unpause}. * * Requirements: * * - the caller must have the `PAUSER_ROLE`. */ function unpause() external virtual { require(hasRole(PAUSER_ROLE, _msgSender()), "TokenMock/PauserRole"); _unpause(); } function _beforeTokenTransfer( address from, address to, uint256 amount ) internal virtual override(ERC20, ERC20Pausable) { super._beforeTokenTransfer(from, to, amount); } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "../../utils/Context.sol"; import "./ERC20.sol"; /** * @dev Extension of {ERC20} that allows token holders to destroy both their own * tokens and those that they have an allowance for, in a way that can be * recognized off-chain (via event analysis). */ abstract contract ERC20Burnable is Context, ERC20 { using SafeMath for uint256; /** * @dev Destroys `amount` tokens from the caller. * * See {ERC20-_burn}. */ function burn(uint256 amount) public virtual { _burn(_msgSender(), amount); } /** * @dev Destroys `amount` tokens from `account`, deducting from the caller's * allowance. * * See {ERC20-_burn} and {ERC20-allowance}. * * Requirements: * * - the caller must have allowance for ``accounts``'s tokens of at least * `amount`. */ function burnFrom(address account, uint256 amount) public virtual { uint256 decreasedAllowance = allowance(account, _msgSender()).sub(amount, "ERC20: burn amount exceeds allowance"); _approve(account, _msgSender(), decreasedAllowance); _burn(account, amount); } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "../utils/Context.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor () internal { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } // SPDX-License-Identifier: MIT pragma solidity =0.7.6; import "../Recoverable.sol"; contract RecoverableHarness is Recoverable { constructor(address governance) { _setupRole(RECOVER_ROLE, governance); } receive() external payable { // Blindly accept ETH. } } // SPDX-License-Identifier: MIT pragma solidity ^0.7.6; import "@openzeppelin/contracts/access/AccessControl.sol"; import "@openzeppelin/contracts/GSN/Context.sol"; import "@openzeppelin/contracts/math/Math.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "@openzeppelin/contracts/utils/Pausable.sol"; import "@openzeppelin/contracts/utils/ReentrancyGuard.sol"; import "./RewardDistributionRecipient.sol"; import "./interfaces/IETHStakingRewards.sol"; /** * @title Phase 2 BANK Reward Pool for Float Protocol, specifically for ETH. * @notice This contract is used to reward `rewardToken` when ETH is staked. */ contract ETHPhase2Pool is IETHStakingRewards, Context, AccessControl, RewardDistributionRecipient, ReentrancyGuard { using SafeMath for uint256; using SafeERC20 for IERC20; /* ========== CONSTANTS ========== */ uint256 public constant DURATION = 7 days; bytes32 public constant RECOVER_ROLE = keccak256("RECOVER_ROLE"); /* ========== STATE VARIABLES ========== */ IERC20 public rewardToken; uint256 public periodFinish = 0; uint256 public rewardRate = 0; uint256 public lastUpdateTime; uint256 public rewardPerTokenStored; mapping(address => uint256) public userRewardPerTokenPaid; mapping(address => uint256) public rewards; uint256 private _totalSupply; mapping(address => uint256) private _balances; /* ========== CONSTRUCTOR ========== */ /** * @notice Construct a new Phase2Pool for ETH * @param _admin The default role controller for * @param _rewardDistribution The reward distributor (can change reward rate) * @param _rewardToken The reward token to distribute */ constructor( address _admin, address _rewardDistribution, address _rewardToken ) RewardDistributionRecipient(_admin) { rewardDistribution = _rewardDistribution; rewardToken = IERC20(_rewardToken); _setupRole(DEFAULT_ADMIN_ROLE, _admin); _setupRole(RECOVER_ROLE, _admin); } /* ========== EVENTS ========== */ event RewardAdded(uint256 reward); event Staked(address indexed user, uint256 amount); event Withdrawn(address indexed user, uint256 amount); event RewardPaid(address indexed user, uint256 reward); event Recovered(address token, uint256 amount); /* ========== MODIFIERS ========== */ modifier updateReward(address account) { rewardPerTokenStored = rewardPerToken(); lastUpdateTime = lastTimeRewardApplicable(); if (account != address(0)) { rewards[account] = earned(account); userRewardPerTokenPaid[account] = rewardPerTokenStored; } _; } /* ========== VIEWS ========== */ function totalSupply() public view override(IETHStakingRewards) returns (uint256) { return _totalSupply; } function balanceOf(address account) public view override(IETHStakingRewards) returns (uint256) { return _balances[account]; } function lastTimeRewardApplicable() public view override(IETHStakingRewards) returns (uint256) { return Math.min(block.timestamp, periodFinish); } function rewardPerToken() public view override(IETHStakingRewards) returns (uint256) { if (totalSupply() == 0) { return rewardPerTokenStored; } return rewardPerTokenStored.add( lastTimeRewardApplicable() .sub(lastUpdateTime) .mul(rewardRate) .mul(1e18) .div(totalSupply()) ); } function earned(address account) public view override(IETHStakingRewards) returns (uint256) { return balanceOf(account) .mul(rewardPerToken().sub(userRewardPerTokenPaid[account])) .div(1e18) .add(rewards[account]); } function getRewardForDuration() external view override(IETHStakingRewards) returns (uint256) { return rewardRate.mul(DURATION); } /* ========== MUTATIVE FUNCTIONS ========== */ /** * @dev Fallback, `msg.value` of ETH sent to this contract grants caller account a matching stake in contract. * Emits {Staked} event to reflect this. */ receive() external payable { stake(msg.value); } function stake(uint256 amount) public payable virtual override(IETHStakingRewards) updateReward(msg.sender) { require(amount > 0, "ETHPhase2Pool/ZeroStake"); require(amount == msg.value, "ETHPhase2Pool/IncorrectEth"); _totalSupply = _totalSupply.add(amount); _balances[msg.sender] = _balances[msg.sender].add(amount); emit Staked(msg.sender, amount); } function withdraw(uint256 amount) public override(IETHStakingRewards) updateReward(msg.sender) { require(amount > 0, "ETHPhase2Pool/ZeroWithdraw"); _totalSupply = _totalSupply.sub(amount); _balances[msg.sender] = _balances[msg.sender].sub(amount); emit Withdrawn(msg.sender, amount); (bool success, ) = msg.sender.call{value: amount}(""); require(success, "ETHPhase2Pool/EthTransferFail"); } function exit() external override(IETHStakingRewards) { withdraw(balanceOf(msg.sender)); getReward(); } function getReward() public virtual override(IETHStakingRewards) updateReward(msg.sender) { uint256 reward = earned(msg.sender); if (reward > 0) { rewards[msg.sender] = 0; rewardToken.safeTransfer(msg.sender, reward); emit RewardPaid(msg.sender, reward); } } /* ========== RESTRICTED FUNCTIONS ========== */ /* ----- Reward Distributor ----- */ /** * @notice Should be called after the amount of reward tokens has been sent to the contract. Reward should be divisible by duration. * @param reward number of tokens to be distributed over the duration. */ function notifyRewardAmount(uint256 reward) external override onlyRewardDistribution updateReward(address(0)) { if (block.timestamp >= periodFinish) { rewardRate = reward.div(DURATION); } else { uint256 remaining = periodFinish.sub(block.timestamp); uint256 leftover = remaining.mul(rewardRate); rewardRate = reward.add(leftover).div(DURATION); } // Ensure provided reward amount is not more than the balance in the contract. // Keeps reward rate within the right range to prevent overflows in earned or rewardsPerToken // Reward + leftover < 1e18 uint256 balance = rewardToken.balanceOf(address(this)); require( rewardRate <= balance.div(DURATION), "ETHPhase2Pool/LowRewardBalance" ); lastUpdateTime = block.timestamp; periodFinish = block.timestamp.add(DURATION); emit RewardAdded(reward); } /* ----- RECOVER_ROLE ----- */ /** * @notice Provide accidental token retrieval. * @dev Sourced from synthetix/contracts/StakingRewards.sol */ function recoverERC20(address tokenAddress, uint256 tokenAmount) external { require( hasRole(RECOVER_ROLE, _msgSender()), "ETHPhase2Pool/HasRecoverRole" ); require(tokenAddress != address(rewardToken), "ETHPhase2Pool/NotReward"); IERC20(tokenAddress).safeTransfer(_msgSender(), tokenAmount); emit Recovered(tokenAddress, tokenAmount); } } // SPDX-License-Identifier: MIT pragma solidity ^0.7.6; interface IETHStakingRewards { // Views function lastTimeRewardApplicable() external view returns (uint256); function rewardPerToken() external view returns (uint256); function earned(address account) external view returns (uint256); function getRewardForDuration() external view returns (uint256); function totalSupply() external view returns (uint256); function balanceOf(address account) external view returns (uint256); // Mutative function stake(uint256 amount) external payable; function withdraw(uint256 amount) external; function getReward() external; function exit() external; } // SPDX-License-Identifier: MIT pragma solidity ^0.7.6; import "@openzeppelin/contracts/access/AccessControl.sol"; import "@openzeppelin/contracts/math/Math.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "@openzeppelin/contracts/utils/Pausable.sol"; import "synthetix/contracts/interfaces/IStakingRewards.sol"; import "./RewardDistributionRecipient.sol"; /** * @title Base Reward Pool for Float Protocol * @notice This contract is used to reward `rewardToken` when `stakeToken` is staked. * @dev The Pools are based on the original Synthetix rewards contract (https://etherscan.io/address/0xDCB6A51eA3CA5d3Fd898Fd6564757c7aAeC3ca92#code) developed by @k06a which is battled tested and widely used. * Alterations: * - duration set on constructor (immutable) * - Internal properties rather than private * - Add virtual marker to functions * - Change stake / withdraw to external and provide internal equivalents * - Change require messages to match convention * - Add hooks for _beforeWithdraw and _beforeStake * - Emit events before external calls in line with best practices. */ abstract contract BasePool is IStakingRewards, AccessControl, RewardDistributionRecipient { using SafeMath for uint256; using SafeERC20 for IERC20; /* ========== CONSTANTS ========== */ bytes32 public constant RECOVER_ROLE = keccak256("RECOVER_ROLE"); uint256 public immutable duration; /* ========== STATE VARIABLES ========== */ IERC20 public rewardToken; IERC20 public stakeToken; uint256 public periodFinish; uint256 public rewardRate; uint256 public lastUpdateTime; uint256 public rewardPerTokenStored; mapping(address => uint256) public userRewardPerTokenPaid; mapping(address => uint256) public rewards; uint256 internal _totalSupply; mapping(address => uint256) internal _balances; /* ========== CONSTRUCTOR ========== */ /** * @notice Construct a new BasePool * @param _admin The default role controller * @param _rewardDistribution The reward distributor (can change reward rate) * @param _rewardToken The reward token to distribute * @param _stakingToken The staking token used to qualify for rewards */ constructor( address _admin, address _rewardDistribution, address _rewardToken, address _stakingToken, uint256 _duration ) RewardDistributionRecipient(_admin) { rewardDistribution = _rewardDistribution; rewardToken = IERC20(_rewardToken); stakeToken = IERC20(_stakingToken); duration = _duration; _setupRole(DEFAULT_ADMIN_ROLE, _admin); _setupRole(RECOVER_ROLE, _admin); } /* ========== EVENTS ========== */ event RewardAdded(uint256 reward); event Staked(address indexed user, uint256 amount); event Withdrawn(address indexed user, uint256 amount); event RewardPaid(address indexed user, uint256 reward); event Recovered(address token, uint256 amount); /* ========== MODIFIERS ========== */ modifier updateReward(address account) virtual { rewardPerTokenStored = rewardPerToken(); lastUpdateTime = lastTimeRewardApplicable(); if (account != address(0)) { rewards[account] = earned(account); userRewardPerTokenPaid[account] = rewardPerTokenStored; } _; } /* ========== VIEWS ========== */ /** * @notice The total reward producing staked supply (total quantity to distribute) */ function totalSupply() public view virtual override(IStakingRewards) returns (uint256) { return _totalSupply; } /** * @notice The total reward producing balance of the account. */ function balanceOf(address account) public view virtual override(IStakingRewards) returns (uint256) { return _balances[account]; } function lastTimeRewardApplicable() public view virtual override(IStakingRewards) returns (uint256) { return Math.min(block.timestamp, periodFinish); } function rewardPerToken() public view virtual override(IStakingRewards) returns (uint256) { if (totalSupply() == 0) { return rewardPerTokenStored; } return rewardPerTokenStored.add( lastTimeRewardApplicable() .sub(lastUpdateTime) .mul(rewardRate) .mul(1e18) .div(totalSupply()) ); } function earned(address account) public view virtual override(IStakingRewards) returns (uint256) { return balanceOf(account) .mul(rewardPerToken().sub(userRewardPerTokenPaid[account])) .div(1e18) .add(rewards[account]); } function getRewardForDuration() external view override(IStakingRewards) returns (uint256) { return rewardRate.mul(duration); } /* ========== MUTATIVE FUNCTIONS ========== */ function stake(uint256 amount) external virtual override(IStakingRewards) updateReward(msg.sender) { require(amount > 0, "BasePool/NonZeroStake"); _stake(msg.sender, msg.sender, amount); } function withdraw(uint256 amount) external virtual override(IStakingRewards) updateReward(msg.sender) { require(amount > 0, "BasePool/NonZeroWithdraw"); _withdraw(msg.sender, amount); } /** * @notice Exit the pool, taking any rewards due and staked */ function exit() external virtual override(IStakingRewards) updateReward(msg.sender) { _withdraw(msg.sender, _balances[msg.sender]); getReward(); } /** * @notice Retrieve any rewards due */ function getReward() public virtual override(IStakingRewards) updateReward(msg.sender) { uint256 reward = earned(msg.sender); if (reward > 0) { rewards[msg.sender] = 0; emit RewardPaid(msg.sender, reward); rewardToken.safeTransfer(msg.sender, reward); } } /** * @dev Stakes `amount` tokens from `staker` to `recipient`, increasing the total supply. * * Emits a {Staked} event. * * Requirements: * - `recipient` cannot be zero address. * - `staker` must have at least `amount` tokens * - `staker` must approve this contract for at least `amount` */ function _stake( address staker, address recipient, uint256 amount ) internal virtual { require(recipient != address(0), "BasePool/ZeroAddressS"); _beforeStake(staker, recipient, amount); _totalSupply = _totalSupply.add(amount); _balances[recipient] = _balances[recipient].add(amount); emit Staked(recipient, amount); stakeToken.safeTransferFrom(staker, address(this), amount); } /** * @dev Withdraws `amount` tokens from `account`, reducing the total supply. * * Emits a {Withdrawn} event. * * Requirements: * - `account` cannot be zero address. * - `account` must have at least `amount` staked. */ function _withdraw(address account, uint256 amount) internal virtual { require(account != address(0), "BasePool/ZeroAddressW"); _beforeWithdraw(account, amount); _balances[account] = _balances[account].sub( amount, "BasePool/WithdrawExceedsBalance" ); _totalSupply = _totalSupply.sub(amount); emit Withdrawn(account, amount); stakeToken.safeTransfer(account, amount); } /* ========== RESTRICTED FUNCTIONS ========== */ /* ----- Reward Distributor ----- */ /** * @notice Should be called after the amount of reward tokens has been sent to the contract. Reward should be divisible by duration. * @param reward number of tokens to be distributed over the duration. */ function notifyRewardAmount(uint256 reward) public virtual override onlyRewardDistribution updateReward(address(0)) { if (block.timestamp >= periodFinish) { rewardRate = reward.div(duration); } else { uint256 remaining = periodFinish.sub(block.timestamp); uint256 leftover = remaining.mul(rewardRate); rewardRate = reward.add(leftover).div(duration); } // Ensure provided reward amount is not more than the balance in the contract. // Keeps reward rate within the right range to prevent overflows in earned or rewardsPerToken // Reward + leftover < 1e18 uint256 balance = rewardToken.balanceOf(address(this)); require(rewardRate <= balance.div(duration), "BasePool/InsufficentBalance"); lastUpdateTime = block.timestamp; periodFinish = block.timestamp.add(duration); emit RewardAdded(reward); } /* ----- RECOVER_ROLE ----- */ /** * @notice Provide accidental token retrieval. * @dev Sourced from synthetix/contracts/StakingRewards.sol */ function recoverERC20(address tokenAddress, uint256 tokenAmount) external { require(hasRole(RECOVER_ROLE, _msgSender()), "BasePool/RecoverRole"); require(tokenAddress != address(stakeToken), "BasePool/NoRecoveryOfStake"); require( tokenAddress != address(rewardToken), "BasePool/NoRecoveryOfReward" ); emit Recovered(tokenAddress, tokenAmount); IERC20(tokenAddress).safeTransfer(_msgSender(), tokenAmount); } /* ========== HOOKS ========== */ /** * @dev Hook that is called before any staking of tokens. * * Calling conditions: * * - `amount` of ``staker``'s tokens will be staked into the pool * - `recipient` can withdraw. */ function _beforeStake( address staker, address recipient, uint256 amount ) internal virtual {} /** * @dev Hook that is called before any staking of tokens. * * Calling conditions: * * - `amount` of ``from``'s tokens will be withdrawn into the pool */ function _beforeWithdraw(address from, uint256 amount) internal virtual {} } // SPDX-License-Identifier: MIT pragma solidity =0.7.6; import "./BasePool.sol"; import "./extensions/DeadlinePool.sol"; import "./extensions/LockInPool.sol"; /** * Phase 4a Pool - is a special ceremony pool that can only be joined within the window period and has a Lock in period for the tokens */ contract Phase4aPool is DeadlinePool, LockInPool { /* ========== CONSTRUCTOR ========== */ /** * @notice Construct a new BasePool * @param _admin The default role controller * @param _rewardDistribution The reward distributor (can change reward rate) * @param _rewardToken The reward token to distribute * @param _stakingToken The staking token used to qualify for rewards * @param _startWindow When ceremony starts * @param _endWindow When ceremony ends */ constructor( address _admin, address _rewardDistribution, address _rewardToken, address _stakingToken, uint256 _duration, uint256 _startWindow, uint256 _endWindow ) DeadlinePool( _admin, _rewardDistribution, _rewardToken, _stakingToken, _duration, _startWindow, _endWindow ) {} // COMPILER HINTS for overrides function _beforeStake( address staker, address recipient, uint256 amount ) internal virtual override(LockInPool, DeadlinePool) { super._beforeStake(staker, recipient, amount); } function _beforeWithdraw(address from, uint256 amount) internal virtual override(BasePool, LockInPool) { super._beforeWithdraw(from, amount); } function balanceOf(address account) public view virtual override(BasePool, LockInPool) returns (uint256) { return super.balanceOf(account); } function totalSupply() public view virtual override(BasePool, LockInPool) returns (uint256) { return super.totalSupply(); } } // SPDX-License-Identifier: MIT pragma solidity ^0.7.6; import "../BasePool.sol"; import "../../lib/Windowed.sol"; /** * @notice Only allow staking before the deadline. */ abstract contract DeadlinePool is BasePool, Windowed { constructor( address _admin, address _rewardDistribution, address _rewardToken, address _stakingToken, uint256 _duration, uint256 _startWindow, uint256 _endWindow ) BasePool( _admin, _rewardDistribution, _rewardToken, _stakingToken, _duration ) Windowed(_startWindow, _endWindow) {} function _beforeStake( address staker, address recipient, uint256 amount ) internal virtual override(BasePool) inWindow { super._beforeStake(staker, recipient, amount); } } // SPDX-License-Identifier: MIT pragma solidity ^0.7.6; import "@openzeppelin/contracts/math/SafeMath.sol"; import "../BasePool.sol"; /** * Integrates a timelock of `LOCK_DURATION` on the Pool. * Can only withdraw from the pool if: * - not started * - or requested an unlock and waited the `LOCK_DURATION` * - or the rewards have finished for `REFILL_ALLOWANCE`. */ abstract contract LockInPool is BasePool { using SafeMath for uint256; uint256 private constant REFILL_ALLOWANCE = 2 hours; uint256 private constant LOCK_DURATION = 8 days; mapping(address => uint256) public unlocks; uint256 private _unlockingSupply; event Unlock(address indexed account); /* ========== VIEWS ========== */ /** * @notice The balance that is currently being unlocked * @param account The account we're interested in. */ function inLimbo(address account) public view returns (uint256) { if (unlocks[account] == 0) { return 0; } return super.balanceOf(account); } /// @inheritdoc BasePool function balanceOf(address account) public view virtual override(BasePool) returns (uint256) { if (unlocks[account] != 0) { return 0; } return super.balanceOf(account); } /// @inheritdoc BasePool function totalSupply() public view virtual override(BasePool) returns (uint256) { return super.totalSupply().sub(_unlockingSupply); } /* ========== MUTATIVE FUNCTIONS ========== */ /** * @notice Request unlock of the token, removing this senders reward accural by: * - Setting balanceOf to return 0 (used for reward calculation) and adjusting total supply by amount unlocking. */ function unlock() external updateReward(msg.sender) { require(unlocks[msg.sender] == 0, "LockIn/UnlockOnce"); _unlockingSupply = _unlockingSupply.add(balanceOf(msg.sender)); unlocks[msg.sender] = block.timestamp; emit Unlock(msg.sender); } /* ========== HOOKS ========== */ /** * @notice Handle unlocks when staking, resets lock if was unlocking */ function _beforeStake( address staker, address recipient, uint256 amount ) internal virtual override(BasePool) { super._beforeStake(staker, recipient, amount); if (unlocks[recipient] != 0) { // If we are resetting an unlock, reset the unlockingSupply _unlockingSupply = _unlockingSupply.sub(inLimbo(recipient)); unlocks[recipient] = 0; } } /** * @dev Prevent withdrawal if: * - has started (i.e. rewards have entered the pool) * - before finished (+ allowance) * - not unlocked `LOCK_DURATION` ago * * - reset the unlock, so you can re-enter. */ function _beforeWithdraw(address recipient, uint256 amount) internal virtual override(BasePool) { super._beforeWithdraw(recipient, amount); // Before rewards have been added / after + `REFILL` bool releaseWithoutLock = block.timestamp >= periodFinish.add(REFILL_ALLOWANCE); // A lock has been requested and the `LOCK_DURATION` has passed. bool releaseWithLock = (unlocks[recipient] != 0) && (unlocks[recipient] <= block.timestamp.sub(LOCK_DURATION)); require(releaseWithoutLock || releaseWithLock, "LockIn/NotReleased"); if (unlocks[recipient] != 0) { // Reduce unlocking supply (so we don't keep discounting total supply when // it is reduced). Amount will be validated in withdraw proper. _unlockingSupply = _unlockingSupply.sub(amount); } } } // SPDX-License-Identifier: MIT pragma solidity =0.7.6; import "./extensions/LockInPool.sol"; /** * Phase4Pool that acts as a SNX Reward Contract, with an 8 day token lock. */ contract Phase4Pool is LockInPool { /* ========== CONSTRUCTOR ========== */ /** * @notice Construct a new Phase4Pool * @param _admin The default role controller * @param _rewardDistribution The reward distributor (can change reward rate) * @param _rewardToken The reward token to distribute * @param _stakingToken The staking token used to qualify for rewards * @param _duration Duration for token */ constructor( address _admin, address _rewardDistribution, address _rewardToken, address _stakingToken, uint256 _duration ) BasePool( _admin, _rewardDistribution, _rewardToken, _stakingToken, _duration ) {} } // SPDX-License-Identifier: MIT pragma solidity ^0.7.6; import "@openzeppelin/contracts/math/SafeMath.sol"; import "../interfaces/IMasterChefRewarder.sol"; import "../BasePool.sol"; // !!!! WIP !!!!! // This code doesn't work. You can deposit via sushi, withdraw through normal functions. // Must separate the balances and only keep them the same for the rewards. /** * Provides adapters to allow this reward contract to be used as a MASTERCHEF V2 Rewards contract */ abstract contract MasterChefV2Pool is BasePool, IMasterChefRewarder { using SafeMath for uint256; address private immutable masterchefV2; /* ========== CONSTRUCTOR ========== */ /** * @notice Construct a new MasterChefV2Pool * @param _admin The default role controller * @param _rewardDistribution The reward distributor (can change reward rate) * @param _rewardToken The reward token to distribute * @param _stakingToken The staking token used to qualify for rewards * @param _duration The duration for each reward distribution * @param _masterchefv2 The trusted masterchef contract */ constructor( address _admin, address _rewardDistribution, address _rewardToken, address _stakingToken, uint256 _duration, address _masterchefv2 ) BasePool( _admin, _rewardDistribution, _rewardToken, _stakingToken, _duration ) { masterchefV2 = _masterchefv2; } /* ========== MODIFIERS ========== */ modifier onlyMCV2 { require(msg.sender == masterchefV2, "MasterChefV2Pool/OnlyMCV2"); _; } /* ========== VIEWS ========== */ function pendingTokens( uint256, address user, uint256 ) external view override(IMasterChefRewarder) returns (IERC20[] memory rewardTokens, uint256[] memory rewardAmounts) { IERC20[] memory _rewardTokens = new IERC20[](1); _rewardTokens[0] = (rewardToken); uint256[] memory _rewardAmounts = new uint256[](1); _rewardAmounts[0] = earned(user); return (_rewardTokens, _rewardAmounts); } /* ========== MUTATIVE FUNCTIONS ========== */ /** * Adds to the internal balance record, */ function onSushiReward( uint256, address _user, address, uint256, uint256 newLpAmount ) external override(IMasterChefRewarder) onlyMCV2 updateReward(_user) { uint256 internalBalance = _balances[_user]; if (internalBalance > newLpAmount) { // _withdrawWithoutPush(_user, internalBalance.sub(newLpAmount)); } else if (internalBalance < newLpAmount) { // _stakeWithoutPull(_user, _user, newLpAmount.sub(internalBalance)); } } } // SPDX-License-Identifier: MIT pragma solidity =0.7.6; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; interface IMasterChefRewarder { function onSushiReward( uint256 pid, address user, address recipient, uint256 sushiAmount, uint256 newLpAmount ) external; function pendingTokens( uint256 pid, address user, uint256 sushiAmount ) external view returns (IERC20[] memory, uint256[] memory); } // SPDX-License-Identifier: MIT pragma solidity ^0.7.6; import "@openzeppelin/contracts/access/AccessControl.sol"; import "@openzeppelin/contracts/GSN/Context.sol"; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "@openzeppelin/contracts/token/ERC20/ERC20Burnable.sol"; import "../interfaces/ISupplyControlledERC20.sol"; import "hardhat/console.sol"; /** * @dev {ERC20} token, including: * * - ability for holders to burn (destroy) their tokens * - a pauser role that allows to stop all token transfers * * This contract uses {AccessControl} to lock permissioned functions using the * different roles - head to its documentation for details. * * This has an open mint functionality */ // ISupplyControlledERC20, contract SupplyControlledTokenMock is AccessControl, ERC20Burnable { bytes32 public constant MINTER_ROLE = keccak256("MINTER_ROLE"); /** * @dev Grants `DEFAULT_ADMIN_ROLE` to the * account that deploys the contract. * * See {ERC20-constructor}. */ constructor( address _admin, string memory _name, string memory _symbol, uint8 _decimals ) ERC20(_name, _symbol) { _setupRole(DEFAULT_ADMIN_ROLE, _admin); _setupRole(MINTER_ROLE, _admin); _setupDecimals(_decimals); } /** * @dev Creates `amount` new tokens for `to`. * * See {ERC20-_mint}. * */ function mint(address to, uint256 amount) external { require(hasRole(MINTER_ROLE, _msgSender()), "SCTokenMock/MinterRole"); _mint(to, amount); } function _beforeTokenTransfer( address from, address to, uint256 amount ) internal override(ERC20) { // console.log(symbol(), from, "->", to); // console.log(symbol(), ">", amount); super._beforeTokenTransfer(from, to, amount); } } // SPDX-License-Identifier: MIT pragma solidity >= 0.4.22 <0.9.0; library console { address constant CONSOLE_ADDRESS = address(0x000000000000000000636F6e736F6c652e6c6f67); function _sendLogPayload(bytes memory payload) private view { uint256 payloadLength = payload.length; address consoleAddress = CONSOLE_ADDRESS; assembly { let payloadStart := add(payload, 32) let r := staticcall(gas(), consoleAddress, payloadStart, payloadLength, 0, 0) } } function log() internal view { _sendLogPayload(abi.encodeWithSignature("log()")); } function logInt(int p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(int)", p0)); } function logUint(uint p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint)", p0)); } function logString(string memory p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(string)", p0)); } function logBool(bool p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool)", p0)); } function logAddress(address p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(address)", p0)); } function logBytes(bytes memory p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes)", p0)); } function logBytes1(bytes1 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes1)", p0)); } function logBytes2(bytes2 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes2)", p0)); } function logBytes3(bytes3 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes3)", p0)); } function logBytes4(bytes4 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes4)", p0)); } function logBytes5(bytes5 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes5)", p0)); } function logBytes6(bytes6 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes6)", p0)); } function logBytes7(bytes7 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes7)", p0)); } function logBytes8(bytes8 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes8)", p0)); } function logBytes9(bytes9 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes9)", p0)); } function logBytes10(bytes10 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes10)", p0)); } function logBytes11(bytes11 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes11)", p0)); } function logBytes12(bytes12 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes12)", p0)); } function logBytes13(bytes13 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes13)", p0)); } function logBytes14(bytes14 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes14)", p0)); } function logBytes15(bytes15 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes15)", p0)); } function logBytes16(bytes16 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes16)", p0)); } function logBytes17(bytes17 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes17)", p0)); } function logBytes18(bytes18 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes18)", p0)); } function logBytes19(bytes19 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes19)", p0)); } function logBytes20(bytes20 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes20)", p0)); } function logBytes21(bytes21 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes21)", p0)); } function logBytes22(bytes22 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes22)", p0)); } function logBytes23(bytes23 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes23)", p0)); } function logBytes24(bytes24 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes24)", p0)); } function logBytes25(bytes25 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes25)", p0)); } function logBytes26(bytes26 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes26)", p0)); } function logBytes27(bytes27 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes27)", p0)); } function logBytes28(bytes28 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes28)", p0)); } function logBytes29(bytes29 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes29)", p0)); } function logBytes30(bytes30 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes30)", p0)); } function logBytes31(bytes31 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes31)", p0)); } function logBytes32(bytes32 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes32)", p0)); } function log(uint p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint)", p0)); } function log(string memory p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(string)", p0)); } function log(bool p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool)", p0)); } function log(address p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(address)", p0)); } function log(uint p0, uint p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint)", p0, p1)); } function log(uint p0, string memory p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string)", p0, p1)); } function log(uint p0, bool p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool)", p0, p1)); } function log(uint p0, address p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address)", p0, p1)); } function log(string memory p0, uint p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint)", p0, p1)); } function log(string memory p0, string memory p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string)", p0, p1)); } function log(string memory p0, bool p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool)", p0, p1)); } function log(string memory p0, address p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address)", p0, p1)); } function log(bool p0, uint p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint)", p0, p1)); } function log(bool p0, string memory p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string)", p0, p1)); } function log(bool p0, bool p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool)", p0, p1)); } function log(bool p0, address p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address)", p0, p1)); } function log(address p0, uint p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint)", p0, p1)); } function log(address p0, string memory p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string)", p0, p1)); } function log(address p0, bool p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool)", p0, p1)); } function log(address p0, address p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address)", p0, p1)); } function log(uint p0, uint p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint)", p0, p1, p2)); } function log(uint p0, uint p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,string)", p0, p1, p2)); } function log(uint p0, uint p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool)", p0, p1, p2)); } function log(uint p0, uint p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,address)", p0, p1, p2)); } function log(uint p0, string memory p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,uint)", p0, p1, p2)); } function log(uint p0, string memory p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,string)", p0, p1, p2)); } function log(uint p0, string memory p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,bool)", p0, p1, p2)); } function log(uint p0, string memory p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,address)", p0, p1, p2)); } function log(uint p0, bool p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint)", p0, p1, p2)); } function log(uint p0, bool p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,string)", p0, p1, p2)); } function log(uint p0, bool p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool)", p0, p1, p2)); } function log(uint p0, bool p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,address)", p0, p1, p2)); } function log(uint p0, address p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,uint)", p0, p1, p2)); } function log(uint p0, address p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,string)", p0, p1, p2)); } function log(uint p0, address p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,bool)", p0, p1, p2)); } function log(uint p0, address p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,address)", p0, p1, p2)); } function log(string memory p0, uint p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,uint)", p0, p1, p2)); } function log(string memory p0, uint p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,string)", p0, p1, p2)); } function log(string memory p0, uint p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,bool)", p0, p1, p2)); } function log(string memory p0, uint p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,address)", p0, p1, p2)); } function log(string memory p0, string memory p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,uint)", p0, p1, p2)); } function log(string memory p0, string memory p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,string)", p0, p1, p2)); } function log(string memory p0, string memory p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,bool)", p0, p1, p2)); } function log(string memory p0, string memory p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,address)", p0, p1, p2)); } function log(string memory p0, bool p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,uint)", p0, p1, p2)); } function log(string memory p0, bool p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,string)", p0, p1, p2)); } function log(string memory p0, bool p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,bool)", p0, p1, p2)); } function log(string memory p0, bool p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,address)", p0, p1, p2)); } function log(string memory p0, address p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,uint)", p0, p1, p2)); } function log(string memory p0, address p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,string)", p0, p1, p2)); } function log(string memory p0, address p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,bool)", p0, p1, p2)); } function log(string memory p0, address p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,address)", p0, p1, p2)); } function log(bool p0, uint p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint)", p0, p1, p2)); } function log(bool p0, uint p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,string)", p0, p1, p2)); } function log(bool p0, uint p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool)", p0, p1, p2)); } function log(bool p0, uint p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,address)", p0, p1, p2)); } function log(bool p0, string memory p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,uint)", p0, p1, p2)); } function log(bool p0, string memory p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,string)", p0, p1, p2)); } function log(bool p0, string memory p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,bool)", p0, p1, p2)); } function log(bool p0, string memory p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,address)", p0, p1, p2)); } function log(bool p0, bool p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint)", p0, p1, p2)); } function log(bool p0, bool p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,string)", p0, p1, p2)); } function log(bool p0, bool p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool)", p0, p1, p2)); } function log(bool p0, bool p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,address)", p0, p1, p2)); } function log(bool p0, address p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,uint)", p0, p1, p2)); } function log(bool p0, address p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,string)", p0, p1, p2)); } function log(bool p0, address p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,bool)", p0, p1, p2)); } function log(bool p0, address p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,address)", p0, p1, p2)); } function log(address p0, uint p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,uint)", p0, p1, p2)); } function log(address p0, uint p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,string)", p0, p1, p2)); } function log(address p0, uint p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,bool)", p0, p1, p2)); } function log(address p0, uint p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,address)", p0, p1, p2)); } function log(address p0, string memory p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,uint)", p0, p1, p2)); } function log(address p0, string memory p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,string)", p0, p1, p2)); } function log(address p0, string memory p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,bool)", p0, p1, p2)); } function log(address p0, string memory p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,address)", p0, p1, p2)); } function log(address p0, bool p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,uint)", p0, p1, p2)); } function log(address p0, bool p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,string)", p0, p1, p2)); } function log(address p0, bool p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,bool)", p0, p1, p2)); } function log(address p0, bool p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,address)", p0, p1, p2)); } function log(address p0, address p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,uint)", p0, p1, p2)); } function log(address p0, address p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,string)", p0, p1, p2)); } function log(address p0, address p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,bool)", p0, p1, p2)); } function log(address p0, address p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,address)", p0, p1, p2)); } function log(uint p0, uint p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint,uint)", p0, p1, p2, p3)); } function log(uint p0, uint p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint,string)", p0, p1, p2, p3)); } function log(uint p0, uint p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint,bool)", p0, p1, p2, p3)); } function log(uint p0, uint p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint,address)", p0, p1, p2, p3)); } function log(uint p0, uint p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,string,uint)", p0, p1, p2, p3)); } function log(uint p0, uint p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,string,string)", p0, p1, p2, p3)); } function log(uint p0, uint p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,string,bool)", p0, p1, p2, p3)); } function log(uint p0, uint p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,string,address)", p0, p1, p2, p3)); } function log(uint p0, uint p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool,uint)", p0, p1, p2, p3)); } function log(uint p0, uint p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool,string)", p0, p1, p2, p3)); } function log(uint p0, uint p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool,bool)", p0, p1, p2, p3)); } function log(uint p0, uint p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool,address)", p0, p1, p2, p3)); } function log(uint p0, uint p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,address,uint)", p0, p1, p2, p3)); } function log(uint p0, uint p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,address,string)", p0, p1, p2, p3)); } function log(uint p0, uint p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,address,bool)", p0, p1, p2, p3)); } function log(uint p0, uint p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,address,address)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,uint,uint)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,uint,string)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,uint,bool)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,uint,address)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,string,uint)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,string,string)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,string,bool)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,string,address)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,bool,uint)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,bool,string)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,bool,bool)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,bool,address)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,address,uint)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,address,string)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,address,bool)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,address,address)", p0, p1, p2, p3)); } function log(uint p0, bool p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint,uint)", p0, p1, p2, p3)); } function log(uint p0, bool p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint,string)", p0, p1, p2, p3)); } function log(uint p0, bool p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint,bool)", p0, p1, p2, p3)); } function log(uint p0, bool p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint,address)", p0, p1, p2, p3)); } function log(uint p0, bool p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,string,uint)", p0, p1, p2, p3)); } function log(uint p0, bool p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,string,string)", p0, p1, p2, p3)); } function log(uint p0, bool p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,string,bool)", p0, p1, p2, p3)); } function log(uint p0, bool p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,string,address)", p0, p1, p2, p3)); } function log(uint p0, bool p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool,uint)", p0, p1, p2, p3)); } function log(uint p0, bool p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool,string)", p0, p1, p2, p3)); } function log(uint p0, bool p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool,bool)", p0, p1, p2, p3)); } function log(uint p0, bool p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool,address)", p0, p1, p2, p3)); } function log(uint p0, bool p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,address,uint)", p0, p1, p2, p3)); } function log(uint p0, bool p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,address,string)", p0, p1, p2, p3)); } function log(uint p0, bool p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,address,bool)", p0, p1, p2, p3)); } function log(uint p0, bool p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,address,address)", p0, p1, p2, p3)); } function log(uint p0, address p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,uint,uint)", p0, p1, p2, p3)); } function log(uint p0, address p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,uint,string)", p0, p1, p2, p3)); } function log(uint p0, address p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,uint,bool)", p0, p1, p2, p3)); } function log(uint p0, address p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,uint,address)", p0, p1, p2, p3)); } function log(uint p0, address p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,string,uint)", p0, p1, p2, p3)); } function log(uint p0, address p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,string,string)", p0, p1, p2, p3)); } function log(uint p0, address p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,string,bool)", p0, p1, p2, p3)); } function log(uint p0, address p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,string,address)", p0, p1, p2, p3)); } function log(uint p0, address p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,bool,uint)", p0, p1, p2, p3)); } function log(uint p0, address p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,bool,string)", p0, p1, p2, p3)); } function log(uint p0, address p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,bool,bool)", p0, p1, p2, p3)); } function log(uint p0, address p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,bool,address)", p0, p1, p2, p3)); } function log(uint p0, address p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,address,uint)", p0, p1, p2, p3)); } function log(uint p0, address p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,address,string)", p0, p1, p2, p3)); } function log(uint p0, address p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,address,bool)", p0, p1, p2, p3)); } function log(uint p0, address p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,address,address)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,uint,uint)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,uint,string)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,uint,bool)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,uint,address)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,string,uint)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,string,string)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,string,bool)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,string,address)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,bool,uint)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,bool,string)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,bool,bool)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,bool,address)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,address,uint)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,address,string)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,address,bool)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,address,address)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,uint,uint)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,uint,string)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,uint,bool)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,uint,address)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,string,uint)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,string,string)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,string,bool)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,string,address)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,bool,uint)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,bool,string)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,bool,bool)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,bool,address)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,address,uint)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,address,string)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,address,bool)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,address,address)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,uint,uint)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,uint,string)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,uint,bool)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,uint,address)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,string,uint)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,string,string)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,string,bool)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,string,address)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,uint)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,string)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,bool)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,address)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,address,uint)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,address,string)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,address,bool)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,address,address)", p0, p1, p2, p3)); } function log(string memory p0, address p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,uint,uint)", p0, p1, p2, p3)); } function log(string memory p0, address p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,uint,string)", p0, p1, p2, p3)); } function log(string memory p0, address p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,uint,bool)", p0, p1, p2, p3)); } function log(string memory p0, address p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,uint,address)", p0, p1, p2, p3)); } function log(string memory p0, address p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,string,uint)", p0, p1, p2, p3)); } function log(string memory p0, address p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,string,string)", p0, p1, p2, p3)); } function log(string memory p0, address p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,string,bool)", p0, p1, p2, p3)); } function log(string memory p0, address p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,string,address)", p0, p1, p2, p3)); } function log(string memory p0, address p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,bool,uint)", p0, p1, p2, p3)); } function log(string memory p0, address p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,bool,string)", p0, p1, p2, p3)); } function log(string memory p0, address p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,bool,bool)", p0, p1, p2, p3)); } function log(string memory p0, address p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,bool,address)", p0, p1, p2, p3)); } function log(string memory p0, address p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,address,uint)", p0, p1, p2, p3)); } function log(string memory p0, address p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,address,string)", p0, p1, p2, p3)); } function log(string memory p0, address p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,address,bool)", p0, p1, p2, p3)); } function log(string memory p0, address p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,address,address)", p0, p1, p2, p3)); } function log(bool p0, uint p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint,uint)", p0, p1, p2, p3)); } function log(bool p0, uint p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint,string)", p0, p1, p2, p3)); } function log(bool p0, uint p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint,bool)", p0, p1, p2, p3)); } function log(bool p0, uint p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint,address)", p0, p1, p2, p3)); } function log(bool p0, uint p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,string,uint)", p0, p1, p2, p3)); } function log(bool p0, uint p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,string,string)", p0, p1, p2, p3)); } function log(bool p0, uint p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,string,bool)", p0, p1, p2, p3)); } function log(bool p0, uint p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,string,address)", p0, p1, p2, p3)); } function log(bool p0, uint p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool,uint)", p0, p1, p2, p3)); } function log(bool p0, uint p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool,string)", p0, p1, p2, p3)); } function log(bool p0, uint p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool,bool)", p0, p1, p2, p3)); } function log(bool p0, uint p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool,address)", p0, p1, p2, p3)); } function log(bool p0, uint p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,address,uint)", p0, p1, p2, p3)); } function log(bool p0, uint p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,address,string)", p0, p1, p2, p3)); } function log(bool p0, uint p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,address,bool)", p0, p1, p2, p3)); } function log(bool p0, uint p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,address,address)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,uint,uint)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,uint,string)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,uint,bool)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,uint,address)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,string,uint)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,string,string)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,string,bool)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,string,address)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,uint)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,string)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,bool)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,address)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,address,uint)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,address,string)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,address,bool)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,address,address)", p0, p1, p2, p3)); } function log(bool p0, bool p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint,uint)", p0, p1, p2, p3)); } function log(bool p0, bool p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint,string)", p0, p1, p2, p3)); } function log(bool p0, bool p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint,bool)", p0, p1, p2, p3)); } function log(bool p0, bool p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint,address)", p0, p1, p2, p3)); } function log(bool p0, bool p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,uint)", p0, p1, p2, p3)); } function log(bool p0, bool p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,string)", p0, p1, p2, p3)); } function log(bool p0, bool p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,bool)", p0, p1, p2, p3)); } function log(bool p0, bool p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,address)", p0, p1, p2, p3)); } function log(bool p0, bool p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,uint)", p0, p1, p2, p3)); } function log(bool p0, bool p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,string)", p0, p1, p2, p3)); } function log(bool p0, bool p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,bool)", p0, p1, p2, p3)); } function log(bool p0, bool p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,address)", p0, p1, p2, p3)); } function log(bool p0, bool p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,uint)", p0, p1, p2, p3)); } function log(bool p0, bool p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,string)", p0, p1, p2, p3)); } function log(bool p0, bool p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,bool)", p0, p1, p2, p3)); } function log(bool p0, bool p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,address)", p0, p1, p2, p3)); } function log(bool p0, address p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,uint,uint)", p0, p1, p2, p3)); } function log(bool p0, address p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,uint,string)", p0, p1, p2, p3)); } function log(bool p0, address p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,uint,bool)", p0, p1, p2, p3)); } function log(bool p0, address p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,uint,address)", p0, p1, p2, p3)); } function log(bool p0, address p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,string,uint)", p0, p1, p2, p3)); } function log(bool p0, address p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,string,string)", p0, p1, p2, p3)); } function log(bool p0, address p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,string,bool)", p0, p1, p2, p3)); } function log(bool p0, address p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,string,address)", p0, p1, p2, p3)); } function log(bool p0, address p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,uint)", p0, p1, p2, p3)); } function log(bool p0, address p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,string)", p0, p1, p2, p3)); } function log(bool p0, address p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,bool)", p0, p1, p2, p3)); } function log(bool p0, address p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,address)", p0, p1, p2, p3)); } function log(bool p0, address p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,address,uint)", p0, p1, p2, p3)); } function log(bool p0, address p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,address,string)", p0, p1, p2, p3)); } function log(bool p0, address p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,address,bool)", p0, p1, p2, p3)); } function log(bool p0, address p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,address,address)", p0, p1, p2, p3)); } function log(address p0, uint p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,uint,uint)", p0, p1, p2, p3)); } function log(address p0, uint p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,uint,string)", p0, p1, p2, p3)); } function log(address p0, uint p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,uint,bool)", p0, p1, p2, p3)); } function log(address p0, uint p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,uint,address)", p0, p1, p2, p3)); } function log(address p0, uint p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,string,uint)", p0, p1, p2, p3)); } function log(address p0, uint p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,string,string)", p0, p1, p2, p3)); } function log(address p0, uint p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,string,bool)", p0, p1, p2, p3)); } function log(address p0, uint p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,string,address)", p0, p1, p2, p3)); } function log(address p0, uint p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,bool,uint)", p0, p1, p2, p3)); } function log(address p0, uint p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,bool,string)", p0, p1, p2, p3)); } function log(address p0, uint p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,bool,bool)", p0, p1, p2, p3)); } function log(address p0, uint p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,bool,address)", p0, p1, p2, p3)); } function log(address p0, uint p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,address,uint)", p0, p1, p2, p3)); } function log(address p0, uint p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,address,string)", p0, p1, p2, p3)); } function log(address p0, uint p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,address,bool)", p0, p1, p2, p3)); } function log(address p0, uint p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,address,address)", p0, p1, p2, p3)); } function log(address p0, string memory p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,uint,uint)", p0, p1, p2, p3)); } function log(address p0, string memory p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,uint,string)", p0, p1, p2, p3)); } function log(address p0, string memory p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,uint,bool)", p0, p1, p2, p3)); } function log(address p0, string memory p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,uint,address)", p0, p1, p2, p3)); } function log(address p0, string memory p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,string,uint)", p0, p1, p2, p3)); } function log(address p0, string memory p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,string,string)", p0, p1, p2, p3)); } function log(address p0, string memory p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,string,bool)", p0, p1, p2, p3)); } function log(address p0, string memory p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,string,address)", p0, p1, p2, p3)); } function log(address p0, string memory p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,bool,uint)", p0, p1, p2, p3)); } function log(address p0, string memory p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,bool,string)", p0, p1, p2, p3)); } function log(address p0, string memory p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,bool,bool)", p0, p1, p2, p3)); } function log(address p0, string memory p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,bool,address)", p0, p1, p2, p3)); } function log(address p0, string memory p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,address,uint)", p0, p1, p2, p3)); } function log(address p0, string memory p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,address,string)", p0, p1, p2, p3)); } function log(address p0, string memory p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,address,bool)", p0, p1, p2, p3)); } function log(address p0, string memory p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,address,address)", p0, p1, p2, p3)); } function log(address p0, bool p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,uint,uint)", p0, p1, p2, p3)); } function log(address p0, bool p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,uint,string)", p0, p1, p2, p3)); } function log(address p0, bool p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,uint,bool)", p0, p1, p2, p3)); } function log(address p0, bool p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,uint,address)", p0, p1, p2, p3)); } function log(address p0, bool p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,string,uint)", p0, p1, p2, p3)); } function log(address p0, bool p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,string,string)", p0, p1, p2, p3)); } function log(address p0, bool p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,string,bool)", p0, p1, p2, p3)); } function log(address p0, bool p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,string,address)", p0, p1, p2, p3)); } function log(address p0, bool p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,uint)", p0, p1, p2, p3)); } function log(address p0, bool p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,string)", p0, p1, p2, p3)); } function log(address p0, bool p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,bool)", p0, p1, p2, p3)); } function log(address p0, bool p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,address)", p0, p1, p2, p3)); } function log(address p0, bool p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,address,uint)", p0, p1, p2, p3)); } function log(address p0, bool p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,address,string)", p0, p1, p2, p3)); } function log(address p0, bool p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,address,bool)", p0, p1, p2, p3)); } function log(address p0, bool p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,address,address)", p0, p1, p2, p3)); } function log(address p0, address p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,uint,uint)", p0, p1, p2, p3)); } function log(address p0, address p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,uint,string)", p0, p1, p2, p3)); } function log(address p0, address p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,uint,bool)", p0, p1, p2, p3)); } function log(address p0, address p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,uint,address)", p0, p1, p2, p3)); } function log(address p0, address p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,string,uint)", p0, p1, p2, p3)); } function log(address p0, address p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,string,string)", p0, p1, p2, p3)); } function log(address p0, address p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,string,bool)", p0, p1, p2, p3)); } function log(address p0, address p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,string,address)", p0, p1, p2, p3)); } function log(address p0, address p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,bool,uint)", p0, p1, p2, p3)); } function log(address p0, address p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,bool,string)", p0, p1, p2, p3)); } function log(address p0, address p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,bool,bool)", p0, p1, p2, p3)); } function log(address p0, address p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,bool,address)", p0, p1, p2, p3)); } function log(address p0, address p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,address,uint)", p0, p1, p2, p3)); } function log(address p0, address p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,address,string)", p0, p1, p2, p3)); } function log(address p0, address p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,address,bool)", p0, p1, p2, p3)); } function log(address p0, address p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,address,address)", p0, p1, p2, p3)); } } // SPDX-License-Identifier: BSD-3-Clause // Copyright 2020 Compound Labs, Inc. pragma solidity ^0.7.6; import "@openzeppelin/contracts/math/SafeMath.sol"; import "hardhat/console.sol"; contract TimeLock { using SafeMath for uint256; event NewAdmin(address indexed newAdmin); event NewPendingAdmin(address indexed newPendingAdmin); event NewDelay(uint256 indexed newDelay); event CancelTransaction( bytes32 indexed txHash, address indexed target, uint256 value, string signature, bytes data, uint256 eta ); event ExecuteTransaction( bytes32 indexed txHash, address indexed target, uint256 value, string signature, bytes data, uint256 eta ); event QueueTransaction( bytes32 indexed txHash, address indexed target, uint256 value, string signature, bytes data, uint256 eta ); uint256 public constant GRACE_PERIOD = 14 days; uint256 public constant MINIMUM_DELAY = 2 days; uint256 public constant MAXIMUM_DELAY = 30 days; address public admin; address public pendingAdmin; uint256 public delay; mapping(bytes32 => bool) public queuedTransactions; constructor(address admin_, uint256 delay_) public { require( delay_ >= MINIMUM_DELAY, "TimeLock::constructor: Delay must exceed minimum delay." ); require( delay_ <= MAXIMUM_DELAY, "TimeLock::constructor: Delay must not exceed maximum delay." ); admin = admin_; delay = delay_; } fallback() external {} function setDelay(uint256 delay_) public { require( msg.sender == address(this), "TimeLock::setDelay: Call must come from TimeLock." ); require( delay_ >= MINIMUM_DELAY, "TimeLock::setDelay: Delay must exceed minimum delay." ); require( delay_ <= MAXIMUM_DELAY, "TimeLock::setDelay: Delay must not exceed maximum delay." ); delay = delay_; emit NewDelay(delay); } function acceptAdmin() public { require( msg.sender == pendingAdmin, "TimeLock::acceptAdmin: Call must come from pendingAdmin." ); admin = msg.sender; pendingAdmin = address(0); emit NewAdmin(admin); } function setPendingAdmin(address pendingAdmin_) public { require( msg.sender == address(this), "TimeLock::setPendingAdmin: Call must come from TimeLock." ); pendingAdmin = pendingAdmin_; emit NewPendingAdmin(pendingAdmin); } function queueTransaction( address target, uint256 value, string memory signature, bytes memory data, uint256 eta ) public returns (bytes32) { require( msg.sender == admin, "TimeLock::queueTransaction: Call must come from admin." ); require( eta >= getBlockTimestamp().add(delay), "TimeLock::queueTransaction: Estimated execution block must satisfy delay." ); bytes32 txHash = keccak256(abi.encode(target, value, signature, data, eta)); queuedTransactions[txHash] = true; emit QueueTransaction(txHash, target, value, signature, data, eta); return txHash; } function cancelTransaction( address target, uint256 value, string memory signature, bytes memory data, uint256 eta ) public { require( msg.sender == admin, "TimeLock::cancelTransaction: Call must come from admin." ); bytes32 txHash = keccak256(abi.encode(target, value, signature, data, eta)); queuedTransactions[txHash] = false; emit CancelTransaction(txHash, target, value, signature, data, eta); } function executeTransaction( address target, uint256 value, string memory signature, bytes memory data, uint256 eta ) public payable returns (bytes memory) { require( msg.sender == admin, "TimeLock::executeTransaction: Call must come from admin." ); bytes32 txHash = keccak256(abi.encode(target, value, signature, data, eta)); require( queuedTransactions[txHash], "TimeLock::executeTransaction: Transaction hasn't been queued." ); require( getBlockTimestamp() >= eta, "TimeLock::executeTransaction: Transaction hasn't surpassed time lock." ); require( getBlockTimestamp() <= eta.add(GRACE_PERIOD), "TimeLock::executeTransaction: Transaction is stale." ); queuedTransactions[txHash] = false; bytes memory callData; if (bytes(signature).length == 0) { callData = data; } else { callData = abi.encodePacked(bytes4(keccak256(bytes(signature))), data); } // solium-disable-next-line security/no-call-value (bool success, bytes memory returnData) = target.call{value: value}(callData); require( success, "TimeLock::executeTransaction: Transaction execution reverted." ); emit ExecuteTransaction(txHash, target, value, signature, data, eta); return returnData; } function getBlockTimestamp() internal view returns (uint256) { // solium-disable-next-line security/no-block-members return block.timestamp; } } // SPDX-License-Identifier: BSD-3-Clause // Copyright 2020 Compound Labs, Inc. pragma solidity ^0.7.6; import "../TimeLock.sol"; contract TimeLockMock is TimeLock { constructor(address admin_, uint256 delay_) TimeLock(admin_, TimeLock.MINIMUM_DELAY) { admin = admin_; delay = delay_; } } // SPDX-License-Identifier: MIT pragma solidity ^0.7.6; import "synthetix/contracts/interfaces/IStakingRewards.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; contract EarnedAggregator { /// @notice The address of the Float Protocol Timelock address public timelock; /// @notice addresses of pools (Staking Rewards Contracts) address[] public pools; constructor(address timelock_, address[] memory pools_) { timelock = timelock_; pools = pools_; } function getPools() public view returns (address[] memory) { address[] memory pls = pools; return pls; } function addPool(address pool) public { // Sanity check for function and no error IStakingRewards(pool).earned(timelock); for (uint256 i = 0; i < pools.length; i++) { require(pools[i] != pool, "already added"); } require(msg.sender == address(timelock), "EarnedAggregator: !timelock"); pools.push(pool); } function removePool(uint256 index) public { require(msg.sender == address(timelock), "EarnedAggregator: !timelock"); if (index >= pools.length) return; if (index != pools.length - 1) { pools[index] = pools[pools.length - 1]; } pools.pop(); } function getCurrentEarned(address account) public view returns (uint256) { uint256 votes = 0; for (uint256 i = 0; i < pools.length; i++) { // get tokens earned for staking votes = SafeMath.add(votes, IStakingRewards(pools[i]).earned(account)); } return votes; } } // SPDX-License-Identifier: MIT pragma solidity =0.7.6; import "../AuctionHouseMath.sol"; contract AuctionHouseMathTest is AuctionHouseMath { function _lerp( uint256 start, uint256 end, uint16 step, uint16 maxStep ) public pure returns (uint256 result) { return lerp(start, end, step, maxStep); } } // SPDX-License-Identifier: MIT pragma solidity =0.7.6; import "@openzeppelin/contracts-upgradeable/access/AccessControlUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/GSN/ContextUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/proxy/Initializable.sol"; import "@openzeppelin/contracts-upgradeable/utils/PausableUpgradeable.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "../external-lib/SafeDecimalMath.sol"; import "./interfaces/IBasket.sol"; import "./BasketMath.sol"; /** * @title Float Protocol Basket * @notice The logic contract for storing underlying ETH (as wETH) */ contract BasketV1 is IBasket, Initializable, AccessControlUpgradeable { using SafeMath for uint256; using SafeDecimalMath for uint256; using SafeERC20 for IERC20; /* ========== CONSTANTS ========== */ bytes32 public constant GOVERNANCE_ROLE = keccak256("GOVERNANCE_ROLE"); bytes32 public constant AUCTION_HOUSE_ROLE = keccak256("AUCTION_HOUSE_ROLE"); /* ========== STATE VARIABLES ========== */ IERC20 public float; IERC20 private weth; /** * @notice The target ratio for "collateralisation" * @dev [e27] Start at 100% */ uint256 public targetRatio; function initialize( address _admin, address _weth, address _float ) external initializer { weth = IERC20(_weth); float = IERC20(_float); targetRatio = SafeDecimalMath.PRECISE_UNIT; _setupRole(DEFAULT_ADMIN_ROLE, _admin); _setupRole(GOVERNANCE_ROLE, _admin); } /* ========== MODIFIERS ========== */ modifier onlyGovernance { require( hasRole(GOVERNANCE_ROLE, _msgSender()), "AuctionHouse/GovernanceRole" ); _; } /* ========== VIEWS ========== */ /// @inheritdoc IBasketReader function underlying() public view override(IBasketReader) returns (address) { return address(weth); } /// @inheritdoc IBasketReader function getBasketFactor(uint256 targetPriceInEth) external view override(IBasketReader) returns (uint256 basketFactor) { uint256 wethInBasket = weth.balanceOf(address(this)); uint256 floatTotalSupply = float.totalSupply(); return basketFactor = BasketMath.calcBasketFactor( targetPriceInEth, wethInBasket, floatTotalSupply, targetRatio ); } /* ========== RESTRICTED FUNCTIONS ========== */ /* ----- onlyGovernance ----- */ /// @inheritdoc IBasketGovernedActions function buildAuctionHouse(address _auctionHouse, uint256 _allowance) external override(IBasketGovernedActions) onlyGovernance { grantRole(AUCTION_HOUSE_ROLE, _auctionHouse); weth.safeApprove(_auctionHouse, 0); weth.safeApprove(_auctionHouse, _allowance); } /// @inheritdoc IBasketGovernedActions function burnAuctionHouse(address _auctionHouse) external override(IBasketGovernedActions) onlyGovernance { revokeRole(AUCTION_HOUSE_ROLE, _auctionHouse); weth.safeApprove(_auctionHouse, 0); } /// @inheritdoc IBasketGovernedActions function setTargetRatio(uint256 _targetRatio) external override(IBasketGovernedActions) onlyGovernance { require( _targetRatio <= BasketMath.MAX_TARGET_RATIO, "BasketV1/RatioTooHigh" ); require( _targetRatio >= BasketMath.MIN_TARGET_RATIO, "BasketV1/RatioTooLow" ); targetRatio = _targetRatio; emit NewTargetRatio(_targetRatio); } } // 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 "../utils/ContextUpgradeable.sol"; // 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.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: MIT pragma solidity ^0.7.6; pragma abicoder v2; import "./basket/IBasketReader.sol"; import "./basket/IBasketGovernedActions.sol"; /** * @title The interface for a Float Protocol Asset Basket * @notice A Basket stores value used to stabilise price and assess the * the movement of the underlying assets we're trying to track. * @dev The Basket interface is broken up into many smaller pieces to allow only * relevant parts to be imported */ interface IBasket is IBasketReader, IBasketGovernedActions { } // SPDX-License-Identifier: MIT pragma solidity =0.7.6; import "../external-lib/SafeDecimalMath.sol"; library BasketMath { using SafeMath for uint256; using SafeDecimalMath for uint256; // SafeDecimalMath.PRECISE_UNIT = 1e27 uint256 internal constant MIN_TARGET_RATIO = 0.1e27; uint256 internal constant MAX_TARGET_RATIO = 2e27; /** * @dev bF = ( eS / (fS * tP) ) / Q * @param targetPriceInEth [e27] target price (tP). * @param ethStored [e18] denoting total eth stored in basket (eS). * @param floatSupply [e18] denoting total floatSupply (fS). * @param targetRatio [e27] target ratio (Q) * @return basketFactor an [e27] decimal (bF) */ function calcBasketFactor( uint256 targetPriceInEth, uint256 ethStored, uint256 floatSupply, uint256 targetRatio ) internal pure returns (uint256 basketFactor) { // Note that targetRatio should already be checked on set assert(targetRatio >= MIN_TARGET_RATIO); assert(targetRatio <= MAX_TARGET_RATIO); uint256 floatValue = floatSupply.multiplyDecimalRoundPrecise(targetPriceInEth); uint256 basketRatio = ethStored.divideDecimalRoundPrecise(floatValue); return basketFactor = basketRatio.divideDecimalRoundPrecise(targetRatio); } } // 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.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 "../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.7.6; pragma abicoder v2; /** * @title Basket Actions with suitable access control * @notice Contains actions which can only be called by governance. */ interface IBasketGovernedActions { event NewTargetRatio(uint256 targetRatio); /** * @notice Sets the basket target factor, initially "1" * @dev Expects an [e27] fixed point decimal value. * Target Ratio is what the basket factor is "aiming for", * i.e. target ratio = 0.8 then an 80% support from the basket * results in a 100% Basket Factor. * @param _targetRatio [e27] The new Target ratio */ function setTargetRatio(uint256 _targetRatio) external; /** * @notice Connect and approve a new auction house to spend from the basket. * @dev Note that any allowance can be set, and even type(uint256).max will * slowly be eroded. * @param _auctionHouse The Auction House address to approve * @param _allowance The amount of the underlying token it can spend */ function buildAuctionHouse(address _auctionHouse, uint256 _allowance) external; /** * @notice Remove an auction house, allows easy upgrades. * @param _auctionHouse The Auction House address to revoke. */ function burnAuctionHouse(address _auctionHouse) external; } // SPDX-License-Identifier: MIT pragma solidity =0.7.6; import "../BasketMath.sol"; contract BasketMathHarness { function _calcBasketFactor( uint256 targetPriceInEth, uint256 ethStored, uint256 floatSupply, uint256 targetRatio ) external pure returns (uint256 basketFactor) { return BasketMath.calcBasketFactor( targetPriceInEth, ethStored, floatSupply, targetRatio ); } } // SPDX-License-Identifier: MIT pragma solidity =0.7.6; import "@openzeppelin/contracts-upgradeable/access/AccessControlUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/token/ERC20/ERC20Upgradeable.sol"; import "@openzeppelin/contracts-upgradeable/utils/PausableUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/proxy/Initializable.sol"; /** * @title {ERC20} Pausable token through the PAUSER_ROLE * * @dev This contract uses OpenZeppelin {AccessControlUpgradeable} to lock permissioned functions using the different roles. */ abstract contract ERC20PausableUpgradeable is Initializable, PausableUpgradeable, AccessControlUpgradeable, ERC20Upgradeable { bytes32 public constant PAUSER_ROLE = keccak256("PAUSER_ROLE"); // solhint-disable-next-line func-name-mixedcase function __ERC20Pausable_init_unchained(address pauser) internal initializer { _setupRole(PAUSER_ROLE, pauser); } /** * @dev Pauses all token transfers. * * See {ERC20Pausable} and {Pausable-_pause}. * * Requirements: * * - the caller must have the `PAUSER_ROLE`. */ function pause() external { require( hasRole(PAUSER_ROLE, _msgSender()), "ERC20Pausable/PauserRoleRequired" ); _pause(); } /** * @dev Unpauses all token transfers. * * See {ERC20Pausable} and {Pausable-_unpause}. * * Requirements: * * - the caller must have the `PAUSER_ROLE`. */ function unpause() external { require( hasRole(PAUSER_ROLE, _msgSender()), "ERC20Pausable/PauserRoleRequired" ); _unpause(); } function _beforeTokenTransfer( address from, address to, uint256 amount ) internal virtual override(ERC20Upgradeable) { super._beforeTokenTransfer(from, to, amount); require(!paused(), "ERC20Pausable/Paused"); } uint256[50] private __gap; } // SPDX-License-Identifier: 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; } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20Upgradeable { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: MIT 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.7.6; import "./ERC20PermitUpgradeable.sol"; import "./ERC20PausableUpgradeable.sol"; import "./ERC20SupplyControlledUpgradeable.sol"; /** * @dev {ERC20} FLOAT token, including: * * - a minter role that allows for token minting (necessary for stabilisation) * - the ability to burn tokens (necessary for stabilisation) * - the use of permits to reduce gas costs * - a pauser role that allows to stop all token transfers * * This contract uses OpenZeppelin {AccessControlUpgradeable} to lock permissioned functions * using the different roles. * This contract is upgradable. */ contract FloatTokenV1 is ERC20PausableUpgradeable, ERC20PermitUpgradeable, ERC20SupplyControlledUpgradeable { /** * @notice Construct a FloatTokenV1 instance * @param governance The default role controller, minter and pauser for the contract. * @param minter An additional minter (useful for quick launches, check this is revoked) * @dev We expect minters to be defined on deploy, e.g. AuctionHouse should get minter role */ function initialize(address governance, address minter) external initializer { __Context_init_unchained(); __ERC20_init_unchained("Float Protocol: FLOAT", "FLOAT"); __ERC20Permit_init_unchained("Float Protocol: FLOAT", "1"); __ERC20Pausable_init_unchained(governance); __ERC20SupplyControlled_init_unchained(governance); _setupRole(DEFAULT_ADMIN_ROLE, governance); // Quick launches _setupRole(MINTER_ROLE, minter); } /// @dev Hint to compiler, that this override has already occured. function _beforeTokenTransfer( address from, address to, uint256 amount ) internal virtual override(ERC20Upgradeable, ERC20PausableUpgradeable) { super._beforeTokenTransfer(from, to, amount); } } // SPDX-License-Identifier: MIT pragma solidity =0.7.6; import "@openzeppelin/contracts-upgradeable/access/AccessControlUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/GSN/ContextUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/token/ERC20/ERC20Upgradeable.sol"; import "@openzeppelin/contracts-upgradeable/utils/PausableUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/proxy/Initializable.sol"; import "../external-lib/Counters.sol"; import "../external-lib/EIP712.sol"; import "./interfaces/IERC20Permit.sol"; /** * @dev Wrapper implementation for ERC20 Permit extension allowing approvals * via signatures, as defined in https://eips.ethereum.org/EIPS/eip-2612. */ contract ERC20PermitUpgradeable is IERC20Permit, Initializable, ERC20Upgradeable { using Counters for Counters.Counter; bytes32 private constant PERMIT_TYPEHASH = keccak256( "Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)" ); bytes32 internal _domainSeparator; mapping(address => Counters.Counter) private _nonces; // solhint-disable-next-line func-name-mixedcase function __ERC20Permit_init_unchained( string memory domainName, string memory version ) internal initializer { _domainSeparator = EIP712.domainSeparatorV4(domainName, version); } /// @inheritdoc IERC20Permit // solhint-disable-next-line func-name-mixedcase function DOMAIN_SEPARATOR() external view override(IERC20Permit) returns (bytes32) { return _domainSeparator; } /** * @dev See {IERC20Permit-permit}. */ function permit( address owner, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) external override(IERC20Permit) { // solhint-disable-next-line not-rely-on-time require(block.timestamp <= deadline, "ERC20Permit/ExpiredDeadline"); bytes32 structHash = keccak256( abi.encode( PERMIT_TYPEHASH, owner, spender, value, _useNonce(owner), deadline ) ); bytes32 hash = EIP712.hashTypedDataV4(_domainSeparator, structHash); address signer = ECDSA.recover(hash, v, r, s); require(signer == owner, "ERC20Permit/InvalidSignature"); _approve(owner, spender, value); } /// @inheritdoc IERC20Permit function nonces(address owner) external view virtual override(IERC20Permit) returns (uint256) { return _nonces[owner].current(); } /** * @dev "Consume a nonce": return the current value and increment. */ function _useNonce(address owner) internal virtual returns (uint256 current) { Counters.Counter storage nonce = _nonces[owner]; current = nonce.current(); nonce.increment(); } uint256[48] private __gap; } // SPDX-License-Identifier: MIT pragma solidity =0.7.6; import "@openzeppelin/contracts-upgradeable/access/AccessControlUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/token/ERC20/ERC20Upgradeable.sol"; import "@openzeppelin/contracts-upgradeable/proxy/Initializable.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; /** * @title {ERC20} Supply Controlled token that allows burning (by all), and minting * by MINTER_ROLE * * @dev This contract uses OpenZeppelin {AccessControlUpgradeable} to lock permissioned functions using the different roles. */ abstract contract ERC20SupplyControlledUpgradeable is Initializable, AccessControlUpgradeable, ERC20Upgradeable { using SafeMath for uint256; bytes32 public constant MINTER_ROLE = keccak256("MINTER_ROLE"); // solhint-disable-next-line func-name-mixedcase function __ERC20SupplyControlled_init_unchained(address minter) internal initializer { _setupRole(MINTER_ROLE, minter); } /** * @dev Creates `amount` new tokens for `to`. * * See {ERC20-_mint}. * * Requirements: * * - the caller must have the `MINTER_ROLE`. */ function mint(address to, uint256 amount) external virtual { require( hasRole(MINTER_ROLE, _msgSender()), "ERC20SupplyControlled/MinterRole" ); _mint(to, amount); } /** * @dev Destroys `amount` tokens from the caller. * * See {ERC20-_burn}. */ function burn(uint256 amount) external 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) external virtual { uint256 decreasedAllowance = allowance(account, _msgSender()).sub( amount, "ERC20SupplyControlled/Overburn" ); _approve(account, _msgSender(), decreasedAllowance); _burn(account, amount); } uint256[50] private __gap; } // SPDX-License-Identifier: MIT pragma solidity ^0.7.6; /** * @title Counters * @author Matt Condon (@shrugs) https://github.com/OpenZeppelin/openzeppelin-contracts * @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;` */ 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 { counter._value += 1; } function decrement(Counter storage counter) internal { uint256 value = counter._value; require(value > 0, "Counter: decrement overflow"); counter._value = value - 1; } } // SPDX-License-Identifier: MIT pragma solidity ^0.7.6; import "./ECDSA.sol"; // Based on OpenZeppelin's draft EIP712, with updates to remove storage variables. /** * @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]. * */ library EIP712 { bytes32 private constant _TYPE_HASH = keccak256( "EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)" ); /** * @dev Returns the domain separator for the current chain. */ function domainSeparatorV4(string memory name, string memory version) internal view returns (bytes32) { return _buildDomainSeparator( _TYPE_HASH, keccak256(bytes(name)), keccak256(bytes(version)) ); } function _buildDomainSeparator( bytes32 typeHash, bytes32 name, bytes32 version ) private view returns (bytes32) { uint256 chainId; // solhint-disable-next-line no-inline-assembly assembly { chainId := chainid() } return keccak256(abi.encode(typeHash, name, version, 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 the given domain. * * This hash can be used together with {ECDSA-recover} to obtain the signer of a message. For example: * * ```solidity * bytes32 digest = EIP712.hashTypedDataV4( * EIP712.domainSeparatorV4("DApp Name", "1"), * keccak256(abi.encode( * keccak256("Mail(address to,string contents)"), * mailTo, * keccak256(bytes(mailContents)) * ))); * address signer = ECDSA.recover(digest, signature); * ``` */ function hashTypedDataV4(bytes32 domainSeparator, bytes32 structHash) internal pure returns (bytes32) { return ECDSA.toTypedDataHash(domainSeparator, structHash); } } // SPDX-License-Identifier: MIT pragma solidity ^0.7.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. */ 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.7.6; /** * @dev Elliptic Curve Digital Signature Algorithm (ECDSA) operations. * * These functions can be used to verify that a message was signed by the holder * of the private keys of a given address. */ library ECDSA { /** * @dev Returns the address that signed a hashed message (`hash`) with * `signature`. This address can then be used for verification purposes. * * The `ecrecover` EVM opcode allows for malleable (non-unique) signatures: * this function rejects them by requiring the `s` value to be in the lower * half order, and the `v` value to be either 27 or 28. * * IMPORTANT: `hash` _must_ be the result of a hash operation for the * verification to be secure: it is possible to craft signatures that * recover to arbitrary addresses for non-hashed data. A safe way to ensure * this is by receiving a hash of the original message (which may otherwise * be too long), and then calling {toEthSignedMessageHash} on it. */ function recover(bytes32 hash, bytes memory signature) internal pure returns (address) { // Divide the signature in r, s and v variables bytes32 r; bytes32 s; uint8 v; // Check the signature length // - case 65: r,s,v signature (standard) // - case 64: r,vs signature (cf https://eips.ethereum.org/EIPS/eip-2098) _Available since v4.1._ if (signature.length == 65) { // ecrecover takes the signature parameters, and the only way to get them // currently is to use assembly. // solhint-disable-next-line no-inline-assembly assembly { r := mload(add(signature, 0x20)) s := mload(add(signature, 0x40)) v := byte(0, mload(add(signature, 0x60))) } } else if (signature.length == 64) { // ecrecover takes the signature parameters, and the only way to get them // currently is to use assembly. // solhint-disable-next-line no-inline-assembly assembly { let vs := mload(add(signature, 0x40)) r := mload(add(signature, 0x20)) s := and( vs, 0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff ) v := add(shr(255, vs), 27) } } else { revert("ECDSA: invalid signature length"); } return recover(hash, v, r, s); } /** * @dev Overload of {ECDSA-recover} that receives the `v`, * `r` and `s` signature fields separately. */ function recover( bytes32 hash, uint8 v, bytes32 r, bytes32 s ) internal pure returns (address) { // EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature // unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines // the valid range for s in (281): 0 < s < secp256k1n ÷ 2 + 1, and for v in (282): v ∈ {27, 28}. Most // signatures from current libraries generate a unique signature with an s-value in the lower half order. // // If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value // with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or // vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept // these malleable signatures as well. require( uint256(s) <= 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0, "ECDSA: invalid signature 's' value" ); require(v == 27 || v == 28, "ECDSA: invalid signature 'v' value"); // If the signature is valid (and not malleable), return the signer address address signer = ecrecover(hash, v, r, s); require(signer != address(0), "ECDSA: invalid signature"); return signer; } /** * @dev Returns an Ethereum Signed Message, created from a `hash`. This * 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.7.6; import "@openzeppelin/contracts-upgradeable/access/AccessControlUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/GSN/ContextUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/token/ERC20/ERC20Upgradeable.sol"; import "@openzeppelin/contracts-upgradeable/utils/PausableUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/proxy/Initializable.sol"; /** * @dev {ERC20} BANK token, including: * * - a minter role that allows for token minting (creation) * - a pauser role that allows to stop all token transfers * * This contract uses OpenZeppelin {AccessControlUpgradeable} to lock permissioned functions * using the different roles. * This contract is upgradable. */ contract BankToken is Initializable, PausableUpgradeable, AccessControlUpgradeable, ERC20Upgradeable { bytes32 public constant MINTER_ROLE = keccak256("MINTER_ROLE"); bytes32 public constant PAUSER_ROLE = keccak256("PAUSER_ROLE"); /** @notice Construct a BankToken instance @param admin The default role controller, minter and pauser for the contract. @param minter An additional minter (for quick launch of epoch 1). */ function initialize(address admin, address minter) public initializer { __ERC20_init("Float Bank", "BANK"); _setupRole(DEFAULT_ADMIN_ROLE, admin); _setupRole(MINTER_ROLE, admin); _setupRole(MINTER_ROLE, minter); _setupRole(PAUSER_ROLE, admin); } /** * @dev Creates `amount` new tokens for `to`. * * See {ERC20-_mint}. * * Requirements: * * - the caller must have the `MINTER_ROLE`. */ function mint(address to, uint256 amount) public virtual { require(hasRole(MINTER_ROLE, _msgSender()), "Bank::mint: must have minter role to mint"); _mint(to, amount); } /** * @dev Pauses all token transfers. * * See {ERC20Pausable} and {Pausable-_pause}. * * Requirements: * * - the caller must have the `PAUSER_ROLE`. */ function pause() public virtual { require(hasRole(PAUSER_ROLE, _msgSender()), "Bank::pause: must have pauser role to pause"); _pause(); } /** * @dev Unpauses all token transfers. * * See {ERC20Pausable} and {Pausable-_unpause}. * * Requirements: * * - the caller must have the `PAUSER_ROLE`. */ function unpause() public virtual { require(hasRole(PAUSER_ROLE, _msgSender()), "Bank::unpause: must have pauser role to unpause"); _unpause(); } function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual override(ERC20Upgradeable) { super._beforeTokenTransfer(from, to, amount); require(!paused(), "ERC20Pausable: token transfer while paused"); } } // SPDX-License-Identifier: MIT pragma solidity =0.7.6; import "../lib/Upgradeable.sol"; import "./ERC20PermitUpgradeable.sol"; import "./ERC20PausableUpgradeable.sol"; import "./ERC20SupplyControlledUpgradeable.sol"; /** * @dev {ERC20} BANK token, including: * * - a minter role that allows for token minting (necessary for stabilisation) * - the ability to burn tokens (necessary for stabilisation) * - the use of permits to reduce gas costs * - a pauser role that allows to stop all token transfers * * This contract uses OpenZeppelin {AccessControlUpgradeable} to lock permissioned functions * using the different roles. * This contract is upgradable. */ contract BankTokenV2 is ERC20PausableUpgradeable, ERC20PermitUpgradeable, ERC20SupplyControlledUpgradeable, Upgradeable { /** * @notice Construct a brand new BankTokenV2 instance * @param governance The default role controller, minter and pauser for the contract. * @dev We expect minters to be defined after deploy, e.g. AuctionHouse should get minter role */ function initialize(address governance) external initializer { _version = 2; __Context_init_unchained(); __ERC20_init_unchained("Float Bank", "BANK"); __ERC20Permit_init_unchained("Float Protocol: BANK", "2"); __ERC20Pausable_init_unchained(governance); __ERC20SupplyControlled_init_unchained(governance); _setupRole(DEFAULT_ADMIN_ROLE, governance); } /** * @notice Upgrade from V1, and initialise the relevant "new" state * @dev Uses upgradeAndCall in the ProxyAdmin, to call upgradeToAndCall, which will delegatecall this function. * _version keeps this single use * onlyProxyAdmin ensures this only occurs on upgrade */ function upgrade() external onlyProxyAdmin { require(_version < 2, "BankTokenV2/AlreadyUpgraded"); _version = 2; _domainSeparator = EIP712.domainSeparatorV4("Float Protocol: BANK", "2"); } /// @dev Hint to compiler that this override has already occured. function _beforeTokenTransfer( address from, address to, uint256 amount ) internal virtual override(ERC20Upgradeable, ERC20PausableUpgradeable) { super._beforeTokenTransfer(from, to, amount); } } // SPDX-License-Identifier: MIT pragma solidity =0.7.6; /** * @title Upgradeable * @dev This contract provides special helper functions when using the upgradeability proxy. */ abstract contract Upgradeable { uint256 internal _version; /** * @dev Storage slot with the admin of the contract. * This is the keccak-256 hash of "eip1967.proxy.admin" subtracted by 1. */ bytes32 internal constant ADMIN_SLOT = 0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103; modifier onlyProxyAdmin() { address proxyAdmin; bytes32 slot = ADMIN_SLOT; // solhint-disable-next-line no-inline-assembly assembly { proxyAdmin := sload(slot) } require(msg.sender == proxyAdmin, "Upgradeable/MustBeProxyAdmin"); _; } } // SPDX-License-Identifier: MIT pragma solidity =0.7.6; import "../BasisMath.sol"; contract BasisMathMock { using BasisMath for uint256; function _splitBy(uint256 value, uint256 percentage) public pure returns (uint256, uint256) { return value.splitBy(percentage); } } // ███████╗░█████╗░██████╗░██████╗░███████╗██████╗░░░░███████╗██╗ // ╚════██║██╔══██╗██╔══██╗██╔══██╗██╔════╝██╔══██╗░░░██╔════╝██║ // ░░███╔═╝███████║██████╔╝██████╔╝█████╗░░██████╔╝░░░█████╗░░██║ // ██╔══╝░░██╔══██║██╔═══╝░██╔═══╝░██╔══╝░░██╔══██╗░░░██╔══╝░░██║ // ███████╗██║░░██║██║░░░░░██║░░░░░███████╗██║░░██║██╗██║░░░░░██║ // ╚══════╝╚═╝░░╚═╝╚═╝░░░░░╚═╝░░░░░╚══════╝╚═╝░░╚═╝╚═╝╚═╝░░░░░╚═╝ // Copyright (C) 2021 zapper // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU Affero General Public License as published by // the Free Software Foundation, either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU Affero General Public License for more details. // ///@author Zapper // SPDX-License-Identifier: GPLv2 // Changes: // - Conversion to 0.7.6 // - library imports throughout // - remove revert fallback as now default import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; pragma solidity ^0.7.6; contract ZapBaseV1 is Ownable { using SafeMath for uint256; using SafeERC20 for IERC20; bool public stopped = false; // if true, goodwill is not deducted mapping(address => bool) public feeWhitelist; uint256 public goodwill; // % share of goodwill (0-100 %) uint256 affiliateSplit; // restrict affiliates mapping(address => bool) public affiliates; // affiliate => token => amount mapping(address => mapping(address => uint256)) public affiliateBalance; // token => amount mapping(address => uint256) public totalAffiliateBalance; address internal constant ETHAddress = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; constructor(uint256 _goodwill, uint256 _affiliateSplit) { goodwill = _goodwill; affiliateSplit = _affiliateSplit; } // circuit breaker modifiers modifier stopInEmergency { if (stopped) { revert("Temporarily Paused"); } else { _; } } function _getBalance(address token) internal view returns (uint256 balance) { if (token == address(0)) { balance = address(this).balance; } else { balance = IERC20(token).balanceOf(address(this)); } } function _approveToken(address token, address spender) internal { IERC20 _token = IERC20(token); if (_token.allowance(address(this), spender) > 0) return; else { _token.safeApprove(spender, uint256(-1)); } } function _approveToken( address token, address spender, uint256 amount ) internal { IERC20 _token = IERC20(token); _token.safeApprove(spender, 0); _token.safeApprove(spender, amount); } // - to Pause the contract function toggleContractActive() public onlyOwner { stopped = !stopped; } function set_feeWhitelist(address zapAddress, bool status) external onlyOwner { feeWhitelist[zapAddress] = status; } function set_new_goodwill(uint256 _new_goodwill) public onlyOwner { require( _new_goodwill >= 0 && _new_goodwill <= 100, "GoodWill Value not allowed" ); goodwill = _new_goodwill; } function set_new_affiliateSplit(uint256 _new_affiliateSplit) external onlyOwner { require(_new_affiliateSplit <= 100, "Affiliate Split Value not allowed"); affiliateSplit = _new_affiliateSplit; } function set_affiliate(address _affiliate, bool _status) external onlyOwner { affiliates[_affiliate] = _status; } ///@notice Withdraw goodwill share, retaining affilliate share function withdrawTokens(address[] calldata tokens) external onlyOwner { for (uint256 i = 0; i < tokens.length; i++) { uint256 qty; if (tokens[i] == ETHAddress) { qty = address(this).balance.sub(totalAffiliateBalance[tokens[i]]); Address.sendValue(payable(owner()), qty); } else { qty = IERC20(tokens[i]).balanceOf(address(this)).sub( totalAffiliateBalance[tokens[i]] ); IERC20(tokens[i]).safeTransfer(owner(), qty); } } } ///@notice Withdraw affilliate share, retaining goodwill share function affilliateWithdraw(address[] calldata tokens) external { uint256 tokenBal; for (uint256 i = 0; i < tokens.length; i++) { tokenBal = affiliateBalance[msg.sender][tokens[i]]; affiliateBalance[msg.sender][tokens[i]] = 0; totalAffiliateBalance[tokens[i]] = totalAffiliateBalance[tokens[i]].sub( tokenBal ); if (tokens[i] == ETHAddress) { Address.sendValue(msg.sender, tokenBal); } else { IERC20(tokens[i]).safeTransfer(msg.sender, tokenBal); } } } } // ███████╗░█████╗░██████╗░██████╗░███████╗██████╗░░░░███████╗██╗ // ╚════██║██╔══██╗██╔══██╗██╔══██╗██╔════╝██╔══██╗░░░██╔════╝██║ // ░░███╔═╝███████║██████╔╝██████╔╝█████╗░░██████╔╝░░░█████╗░░██║ // ██╔══╝░░██╔══██║██╔═══╝░██╔═══╝░██╔══╝░░██╔══██╗░░░██╔══╝░░██║ // ███████╗██║░░██║██║░░░░░██║░░░░░███████╗██║░░██║██╗██║░░░░░██║ // ╚══════╝╚═╝░░╚═╝╚═╝░░░░░╚═╝░░░░░╚══════╝╚═╝░░╚═╝╚═╝╚═╝░░░░░╚═╝ // Copyright (C) 2021 zapper // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU Affero General Public License as published by // the Free Software Foundation, either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU Affero General Public License for more details. // ///@author Zapper // SPDX-License-Identifier: GPLv2 // Changes: // - Conversion to 0.7.6 // - abstract type // - library imports throughout pragma solidity ^0.7.6; import "./ZapBaseV1.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; abstract contract ZapInBaseV2 is ZapBaseV1 { using SafeMath for uint256; using SafeERC20 for IERC20; function _pullTokens( address token, uint256 amount, address affiliate, bool enableGoodwill, bool shouldSellEntireBalance ) internal returns (uint256 value) { uint256 totalGoodwillPortion; if (token == address(0)) { require(msg.value > 0, "No eth sent"); // subtract goodwill totalGoodwillPortion = _subtractGoodwill( ETHAddress, msg.value, affiliate, enableGoodwill ); return msg.value.sub(totalGoodwillPortion); } require(amount > 0, "Invalid token amount"); require(msg.value == 0, "Eth sent with token"); //transfer token if (shouldSellEntireBalance) { require( Address.isContract(msg.sender), "ERR: shouldSellEntireBalance is true for EOA" ); amount = IERC20(token).allowance(msg.sender, address(this)); } IERC20(token).safeTransferFrom(msg.sender, address(this), amount); // subtract goodwill totalGoodwillPortion = _subtractGoodwill( token, amount, affiliate, enableGoodwill ); return amount.sub(totalGoodwillPortion); } function _subtractGoodwill( address token, uint256 amount, address affiliate, bool enableGoodwill ) internal returns (uint256 totalGoodwillPortion) { bool whitelisted = feeWhitelist[msg.sender]; if (enableGoodwill && !whitelisted && goodwill > 0) { totalGoodwillPortion = SafeMath.div( SafeMath.mul(amount, goodwill), 10000 ); if (affiliates[affiliate]) { if (token == address(0)) { token = ETHAddress; } uint256 affiliatePortion = totalGoodwillPortion.mul(affiliateSplit).div(100); affiliateBalance[affiliate][token] = affiliateBalance[affiliate][token] .add(affiliatePortion); totalAffiliateBalance[token] = totalAffiliateBalance[token].add( affiliatePortion ); } } } } // ███████╗░█████╗░██████╗░██████╗░███████╗██████╗░░░░███████╗██╗ // ╚════██║██╔══██╗██╔══██╗██╔══██╗██╔════╝██╔══██╗░░░██╔════╝██║ // ░░███╔═╝███████║██████╔╝██████╔╝█████╗░░██████╔╝░░░█████╗░░██║ // ██╔══╝░░██╔══██║██╔═══╝░██╔═══╝░██╔══╝░░██╔══██╗░░░██╔══╝░░██║ // ███████╗██║░░██║██║░░░░░██║░░░░░███████╗██║░░██║██╗██║░░░░░██║ // ╚══════╝╚═╝░░╚═╝╚═╝░░░░░╚═╝░░░░░╚══════╝╚═╝░░╚═╝╚═╝╚═╝░░░░░╚═╝ // Copyright (C) 2021 zapper // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU Affero General Public License as published by // the Free Software Foundation, either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU Affero General Public License for more details. // ///@author Zapper // SPDX-License-Identifier: GPLv2 // Changes: // - Uses msg.sender / removes the transfer from the zap contract. // - Uses IMintingCeremony over IVault pragma solidity =0.7.6; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "../funds/interfaces/IMintingCeremony.sol"; import "../external-lib/zapper/ZapInBaseV2.sol"; contract FloatMintingCeremonyZapInV1 is ZapInBaseV2 { using SafeMath for uint256; // calldata only accepted for approved zap contracts mapping(address => bool) public approvedTargets; event zapIn(address sender, address pool, uint256 tokensRec); constructor(uint256 _goodwill, uint256 _affiliateSplit) ZapBaseV1(_goodwill, _affiliateSplit) {} /** @notice This function commits to the Float Minting Ceremony with ETH or ERC20 tokens @param fromToken The token used for entry (address(0) if ether) @param amountIn The amount of fromToken to invest @param ceremony Float Protocol: Minting Ceremony address @param minFloatTokens The minimum acceptable quantity Float tokens to receive. Reverts otherwise @param intermediateToken Token to swap fromToken to before entering ceremony @param swapTarget Excecution target for the swap or zap @param swapData DEX or Zap data @param affiliate Affiliate address @return tokensReceived - Quantity of FLOAT that will be received */ function ZapIn( address fromToken, uint256 amountIn, address ceremony, uint256 minFloatTokens, address intermediateToken, address swapTarget, bytes calldata swapData, address affiliate, bool shouldSellEntireBalance ) external payable stopInEmergency returns (uint256 tokensReceived) { require( approvedTargets[swapTarget] || swapTarget == address(0), "Target not Authorized" ); // get incoming tokens uint256 toInvest = _pullTokens( fromToken, amountIn, affiliate, true, shouldSellEntireBalance ); // get intermediate token uint256 intermediateAmt = _fillQuote(fromToken, intermediateToken, toInvest, swapTarget, swapData); // Deposit to Minting Ceremony tokensReceived = _ceremonyCommit(intermediateAmt, ceremony, minFloatTokens); } function _ceremonyCommit( uint256 amount, address toCeremony, uint256 minTokensRec ) internal returns (uint256 tokensReceived) { address underlyingVaultToken = IMintingCeremony(toCeremony).underlying(); _approveToken(underlyingVaultToken, toCeremony); uint256 initialBal = IERC20(toCeremony).balanceOf(msg.sender); IMintingCeremony(toCeremony).commit(msg.sender, amount, minTokensRec); tokensReceived = IERC20(toCeremony).balanceOf(msg.sender).sub(initialBal); require(tokensReceived >= minTokensRec, "Err: High Slippage"); // Note that tokens are gifted directly, so we don't transfer from vault. // IERC20(toCeremony).safeTransfer(msg.sender, tokensReceived); emit zapIn(msg.sender, toCeremony, tokensReceived); } function _fillQuote( address _fromTokenAddress, address toToken, uint256 _amount, address _swapTarget, bytes memory swapCallData ) internal returns (uint256 amtBought) { uint256 valueToSend; if (_fromTokenAddress == toToken) { return _amount; } if (_fromTokenAddress == address(0)) { valueToSend = _amount; } else { _approveToken(_fromTokenAddress, _swapTarget); } uint256 iniBal = _getBalance(toToken); (bool success, ) = _swapTarget.call{value: valueToSend}(swapCallData); require(success, "Error Swapping Tokens 1"); uint256 finalBal = _getBalance(toToken); amtBought = finalBal.sub(iniBal); } function setApprovedTargets( address[] calldata targets, bool[] calldata isApproved ) external onlyOwner { require(targets.length == isApproved.length, "Invalid Input length"); for (uint256 i = 0; i < targets.length; i++) { approvedTargets[targets[i]] = isApproved[i]; } } } // SPDX-License-Identifier: MIT pragma solidity =0.7.6; import "@uniswap/v2-core/contracts/interfaces/IUniswapV2Factory.sol"; import "@uniswap/v2-core/contracts/interfaces/IUniswapV2Pair.sol"; import "@uniswap/lib/contracts/libraries/FixedPoint.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; import "../external-lib/UniswapV2Library.sol"; import "../external-lib/UniswapV2OracleLibrary.sol"; import "../lib/SushiswapLibrary.sol"; import "./interfaces/ITwap.sol"; // As these are "Time"-Weighted Average Price contracts, they necessarily rely on time. // solhint-disable not-rely-on-time /** * @title A sliding window for AMMs (specifically Sushiswap) * @notice Uses observations collected over a window to provide moving price averages in the past * @dev This is a singleton TWAP that only needs to be deployed once per desired parameters. `windowSize` has a precision of `windowSize / granularity` * Errors: * MissingPastObsr - We do not have suffient past observations. * UnexpectedElapsed - We have an unexpected time elapsed. * EarlyUpdate - Tried to update the TWAP before the period has elapsed. * InvalidToken - Cannot consult an invalid token pair. */ contract Twap is ITwap { using FixedPoint for *; using SafeMath for uint256; struct Observation { uint256 timestamp; uint256 price0Cumulative; uint256 price1Cumulative; } /* ========== IMMUTABLE VARIABLES ========== */ /// @notice the Uniswap Factory contract for tracking exchanges address public immutable factory; /// @notice The desired amount of time over which the moving average should be computed, e.g. 24 hours uint256 public immutable windowSize; /// @notice The number of observations stored for each pair, i.e. how many price observations are stored for the window /// @dev As granularity increases from, more frequent updates are needed; but precision increases [`windowSize - (windowSize / granularity) * 2`, `windowSize`] uint8 public immutable granularity; /// @dev Redundant with `granularity` and `windowSize`, but has gas savings & easy read uint256 public immutable periodSize; /* ========== STATE VARIABLES ========== */ /// @notice Mapping from pair address to a list of price observations of that pair mapping(address => Observation[]) public pairObservations; /* ========== EVENTS ========== */ event NewObservation( uint256 timestamp, uint256 price0Cumulative, uint256 price1Cumulative ); /* ========== CONSTRUCTOR ========== */ /** * @notice Construct a new Sliding Window TWAP * @param factory_ The AMM factory * @param windowSize_ The window size for this TWAP * @param granularity_ The granularity required for the TWAP */ constructor( address factory_, uint256 windowSize_, uint8 granularity_ ) { require(factory_ != address(0), "Twap/InvalidFactory"); require(granularity_ > 1, "Twap/Granularity"); require( (periodSize = windowSize_ / granularity_) * granularity_ == windowSize_, "Twap/WindowSize" ); factory = factory_; windowSize = windowSize_; granularity = granularity_; } /* ========== PURE ========== */ /** * @notice Given the cumulative prices of the start and end of a period, and the length of the period, compute the average price in terms of the amount in * @param priceCumulativeStart the cumulative price for the start of the period * @param priceCumulativeEnd the cumulative price for the end of the period * @param timeElapsed the time from now to the first observation * @param amountIn the amount of tokens in * @return amountOut amount out received for the amount in */ function _computeAmountOut( uint256 priceCumulativeStart, uint256 priceCumulativeEnd, uint256 timeElapsed, uint256 amountIn ) private pure returns (uint256 amountOut) { // overflow is desired. FixedPoint.uq112x112 memory priceAverage = FixedPoint.uq112x112( uint224((priceCumulativeEnd - priceCumulativeStart) / timeElapsed) ); amountOut = priceAverage.mul(amountIn).decode144(); } /* ========== VIEWS ========== */ /** * @notice Calculates the index of the observation for the given `timestamp` * @param timestamp the observation for the timestamp * @return index The index of the observation */ function observationIndexOf(uint256 timestamp) public view returns (uint8 index) { uint256 epochPeriod = timestamp / periodSize; return uint8(epochPeriod % granularity); } /// @inheritdoc ITwap function updateable(address tokenA, address tokenB) external view override(ITwap) returns (bool) { address pair = SushiswapLibrary.pairFor(factory, tokenA, tokenB); uint8 observationIndex = observationIndexOf(block.timestamp); Observation storage observation = pairObservations[pair][observationIndex]; // We only want to commit updates once per period (i.e. windowSize / granularity). uint256 timeElapsed = block.timestamp - observation.timestamp; return timeElapsed > periodSize; } /// @inheritdoc ITwap function consult( address tokenIn, uint256 amountIn, address tokenOut ) external view override(ITwap) returns (uint256 amountOut) { address pair = SushiswapLibrary.pairFor(factory, tokenIn, tokenOut); Observation storage firstObservation = _getFirstObservationInWindow(pair); uint256 timeElapsed = block.timestamp - firstObservation.timestamp; require(timeElapsed <= windowSize, "Twap/MissingPastObsr"); require( timeElapsed >= windowSize - periodSize * 2, "Twap/UnexpectedElapsed" ); (uint256 price0Cumulative, uint256 price1Cumulative, ) = UniswapV2OracleLibrary.currentCumulativePrices(pair); (address token0, address token1) = UniswapV2Library.sortTokens(tokenIn, tokenOut); if (token0 == tokenIn) { return _computeAmountOut( firstObservation.price0Cumulative, price0Cumulative, timeElapsed, amountIn ); } require(token1 == tokenIn, "Twap/InvalidToken"); return _computeAmountOut( firstObservation.price1Cumulative, price1Cumulative, timeElapsed, amountIn ); } /** * @notice Observation from the oldest epoch (at the beginning of the window) relative to the current time * @param pair the Uniswap pair address * @return firstObservation The observation from the oldest epoch relative to current time. */ function _getFirstObservationInWindow(address pair) private view returns (Observation storage firstObservation) { uint8 observationIndex = observationIndexOf(block.timestamp); // No overflow issues; if observationIndex + 1 overflows, result is still zero. uint8 firstObservationIndex = (observationIndex + 1) % granularity; firstObservation = pairObservations[pair][firstObservationIndex]; } /* ========== MUTATIVE FUNCTIONS ========== */ /// @inheritdoc ITwap function update(address tokenA, address tokenB) external override(ITwap) returns (bool) { address pair = SushiswapLibrary.pairFor(factory, tokenA, tokenB); // Populate the array with empty observations for the first call. for (uint256 i = pairObservations[pair].length; i < granularity; i++) { pairObservations[pair].push(); } // Get the observation for the current period. uint8 observationIndex = observationIndexOf(block.timestamp); Observation storage observation = pairObservations[pair][observationIndex]; // We only want to commit updates once per period (i.e. windowSize / granularity). uint256 timeElapsed = block.timestamp - observation.timestamp; if (timeElapsed <= periodSize) { // Skip update as we're in the same observation slot. return false; } (uint256 price0Cumulative, uint256 price1Cumulative, ) = UniswapV2OracleLibrary.currentCumulativePrices(pair); observation.timestamp = block.timestamp; observation.price0Cumulative = price0Cumulative; observation.price1Cumulative = price1Cumulative; emit NewObservation( observation.timestamp, observation.price0Cumulative, observation.price1Cumulative ); return true; } } pragma solidity >=0.5.0; interface IUniswapV2Factory { event PairCreated(address indexed token0, address indexed token1, address pair, uint); function feeTo() external view returns (address); function feeToSetter() external view returns (address); function getPair(address tokenA, address tokenB) external view returns (address pair); function allPairs(uint) external view returns (address pair); function allPairsLength() external view returns (uint); function createPair(address tokenA, address tokenB) external returns (address pair); function setFeeTo(address) external; function setFeeToSetter(address) external; } pragma solidity >=0.5.0; interface 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; } pragma solidity >=0.4.0; // 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 { uint _x; } uint8 private constant RESOLUTION = 112; // 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); } // divide a UQ112x112 by a uint112, returning a UQ112x112 function div(uq112x112 memory self, uint112 x) internal pure returns (uq112x112 memory) { require(x != 0, 'FixedPoint: DIV_BY_ZERO'); return uq112x112(self._x / uint224(x)); } // multiply a UQ112x112 by a uint, returning a UQ144x112 // reverts on overflow function mul(uq112x112 memory self, uint y) internal pure returns (uq144x112 memory) { uint z; require(y == 0 || (z = uint(self._x) * y) / y == uint(self._x), "FixedPoint: MULTIPLICATION_OVERFLOW"); return uq144x112(z); } // returns a UQ112x112 which represents the ratio of the numerator to the denominator // equivalent to encode(numerator).div(denominator) function fraction(uint112 numerator, uint112 denominator) internal pure returns (uq112x112 memory) { require(denominator > 0, "FixedPoint: DIV_BY_ZERO"); return uq112x112((uint224(numerator) << RESOLUTION) / denominator); } // 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); } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "@uniswap/v2-core/contracts/interfaces/IUniswapV2Pair.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; library UniswapV2Library { using SafeMath 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"); } // calculates the CREATE2 address for a pair without making any external calls function pairFor( address factory, address tokenA, address tokenB ) internal pure returns (address pair) { (address token0, address token1) = sortTokens(tokenA, tokenB); pair = address( uint256( keccak256( abi.encodePacked( hex"ff", factory, keccak256(abi.encodePacked(token0, token1)), hex"96e8ac4277198ff8b6f785478aa9a39f403cb768dd02cbee326c3e7da348845f" // init code hash ) ) ) ); } // 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: MIT pragma solidity >=0.6.0 <0.8.0; import "@uniswap/v2-core/contracts/interfaces/IUniswapV2Pair.sol"; import "@uniswap/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: MIT pragma solidity >=0.6.0 <0.8.0; import "@uniswap/v2-core/contracts/interfaces/IUniswapV2Pair.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; import "../external-lib/UniswapV2Library.sol"; library SushiswapLibrary { // 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) = UniswapV2Library.sortTokens(tokenA, tokenB); pair = address( uint256( keccak256( abi.encodePacked( hex"ff", factory, keccak256(abi.encodePacked(token0, token1)), hex"e18a34eb0e04b04f7a0ac29a6e80748dca96319b42c54d679cb821dca90c6303" // init code hash ) ) ) ); } } // SPDX-License-Identifier: UNLICENSED pragma solidity =0.7.6; pragma abicoder v2; import "../MonetaryPolicyV1.sol"; contract MonetaryPolicyV1Harness is MonetaryPolicyV1 { uint256 public blockNumber; constructor(address _governance, address _ethUsdOracle) MonetaryPolicyV1(_governance, _ethUsdOracle) {} function _blockNumber() internal view override returns (uint256) { return blockNumber; } function __setBlock(uint256 _number) external { blockNumber = _number; } }
Withdraws `amount` tokens from `account`, reducing the total supply. Emits a {Withdrawn} event. Requirements: - `account` cannot be zero address. - `account` must have at least `amount` staked./
function _withdraw(address account, uint256 amount) internal virtual { require(account != address(0), "BasePool/ZeroAddressW"); _beforeWithdraw(account, amount); _balances[account] = _balances[account].sub( amount, "BasePool/WithdrawExceedsBalance" ); _totalSupply = _totalSupply.sub(amount); emit Withdrawn(account, amount); stakeToken.safeTransfer(account, amount); } Reward should be divisible by duration.
12,841,698
/** *Submitted for verification at Etherscan.io on 2021-10-28 */ //SPDX-License-Identifier: MIT pragma solidity ^0.6.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // File: @openzeppelin/contracts/math/SafeMath.sol pragma solidity ^0.6.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } // File: @openzeppelin/contracts/utils/Address.sol pragma solidity ^0.6.2; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // According to EIP-1052, 0x0 is the value returned for not-yet created accounts // and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned // for accounts without code, i.e. `keccak256('')` bytes32 codehash; bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; // solhint-disable-next-line no-inline-assembly assembly { codehash := extcodehash(account) } return (codehash != accountHash && codehash != 0x0); } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return _functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); return _functionCallWithValue(target, data, value, errorMessage); } function _functionCallWithValue(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) { require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: weiValue }(data); if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // File: @openzeppelin/contracts/token/ERC20/SafeERC20.sol pragma solidity ^0.6.0; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using SafeMath for uint256; using Address for address; function safeTransfer(IERC20 token, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove(IERC20 token, address spender, uint256 value) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' // solhint-disable-next-line max-line-length require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).add(value); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero"); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // File: @openzeppelin/contracts/utils/EnumerableSet.sol pragma solidity ^0.6.0; /** * @dev Library for managing * https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive * types. * * Sets have the following properties: * * - Elements are added, removed, and checked for existence in constant time * (O(1)). * - Elements are enumerated in O(n). No guarantees are made on the ordering. * * ``` * contract Example { * // Add the library methods * using EnumerableSet for EnumerableSet.AddressSet; * * // Declare a set state variable * EnumerableSet.AddressSet private mySet; * } * ``` * * As of v3.0.0, only sets of type `address` (`AddressSet`) and `uint256` * (`UintSet`) are supported. */ library EnumerableSet { // To implement this library for multiple types with as little code // repetition as possible, we write it in terms of a generic Set type with // bytes32 values. // The Set implementation uses private functions, and user-facing // implementations (such as AddressSet) are just wrappers around the // underlying Set. // This means that we can only create new EnumerableSets for types that fit // in bytes32. struct Set { // Storage of set values bytes32[] _values; // Position of the value in the `values` array, plus 1 because index 0 // means a value is not in the set. mapping (bytes32 => uint256) _indexes; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function _add(Set storage set, bytes32 value) private returns (bool) { if (!_contains(set, value)) { set._values.push(value); // The value is stored at length-1, but we add 1 to all indexes // and use 0 as a sentinel value set._indexes[value] = set._values.length; return true; } else { return false; } } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function _remove(Set storage set, bytes32 value) private returns (bool) { // We read and store the value's index to prevent multiple reads from the same storage slot uint256 valueIndex = set._indexes[value]; if (valueIndex != 0) { // Equivalent to contains(set, value) // To delete an element from the _values array in O(1), we swap the element to delete with the last one in // the array, and then remove the last element (sometimes called as 'swap and pop'). // This modifies the order of the array, as noted in {at}. uint256 toDeleteIndex = valueIndex - 1; uint256 lastIndex = set._values.length - 1; // When the value to delete is the last one, the swap operation is unnecessary. However, since this occurs // so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement. bytes32 lastvalue = set._values[lastIndex]; // Move the last value to the index where the value to delete is set._values[toDeleteIndex] = lastvalue; // Update the index for the moved value set._indexes[lastvalue] = toDeleteIndex + 1; // All indexes are 1-based // Delete the slot where the moved value was stored set._values.pop(); // Delete the index for the deleted slot delete set._indexes[value]; return true; } else { return false; } } /** * @dev Returns true if the value is in the set. O(1). */ function _contains(Set storage set, bytes32 value) private view returns (bool) { return set._indexes[value] != 0; } /** * @dev Returns the number of values on the set. O(1). */ function _length(Set storage set) private view returns (uint256) { return set._values.length; } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function _at(Set storage set, uint256 index) private view returns (bytes32) { require(set._values.length > index, "EnumerableSet: index out of bounds"); return set._values[index]; } // AddressSet struct AddressSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(AddressSet storage set, address value) internal returns (bool) { return _add(set._inner, bytes32(uint256(value))); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(AddressSet storage set, address value) internal returns (bool) { return _remove(set._inner, bytes32(uint256(value))); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(AddressSet storage set, address value) internal view returns (bool) { return _contains(set._inner, bytes32(uint256(value))); } /** * @dev Returns the number of values in the set. O(1). */ function length(AddressSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(AddressSet storage set, uint256 index) internal view returns (address) { return address(uint256(_at(set._inner, index))); } // UintSet struct UintSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(UintSet storage set, uint256 value) internal returns (bool) { return _add(set._inner, bytes32(value)); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(UintSet storage set, uint256 value) internal returns (bool) { return _remove(set._inner, bytes32(value)); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(UintSet storage set, uint256 value) internal view returns (bool) { return _contains(set._inner, bytes32(value)); } /** * @dev Returns the number of values on the set. O(1). */ function length(UintSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(UintSet storage set, uint256 index) internal view returns (uint256) { return uint256(_at(set._inner, index)); } } // File: @openzeppelin/contracts/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/token/ERC20/ERC20.sol pragma solidity ^0.6.0; /** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20PresetMinterPauser}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin guidelines: functions revert instead * of returning `false` on failure. This behavior is nonetheless conventional * and does not conflict with the expectations of ERC20 applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */ contract ERC20 is Context, IERC20 { using SafeMath for uint256; using Address for address; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; uint8 private _decimals; /** * @dev Sets the values for {name} and {symbol}, initializes {decimals} with * a default value of 18. * * To select a different value for {decimals}, use {_setupDecimals}. * * All three of these values are immutable: they can only be set once during * construction. */ constructor (string memory name, string memory symbol) public { _name = name; _symbol = symbol; _decimals = 18; } /** * @dev Returns the name of the token. */ function name() public view returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is * called. * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view returns (uint8) { return _decimals; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}; * * Requirements: * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer(address sender, address recipient, uint256 amount) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements * * - `to` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner`s tokens. * * This is internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve(address owner, address spender, uint256 amount) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Sets {decimals} to a value other than the default one of 18. * * WARNING: This function should only be called from the constructor. Most * applications that interact with token contracts will not expect * {decimals} to ever change, and may work incorrectly if it does. */ function _setupDecimals(uint8 decimals_) internal { _decimals = decimals_; } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be to transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { } } // File: contracts/KwikToken.sol pragma solidity 0.6.12; contract KWIK { /// @notice EIP-20 token name for this token string public constant name = "Kwikswap"; /// @notice EIP-20 token symbol for this token string public constant symbol = "KWIK"; /// @notice EIP-20 token decimals for this token uint8 public constant decimals = 18; /// @notice Total number of tokens in circulation uint public totalSupply = 250_000_000e18; // 250,000,000 KWIK /// @notice Address which may mint new tokens address public minter; /// @notice The timestamp after which minting may occur uint public mintingAllowedAfter; /// @notice Minimum time between mints uint32 public constant minimumTimeBetweenMints = 1 days * 365; /// @notice Cap on the percentage of totalSupply that can be minted at each mint uint8 public constant mintCap = 2; mapping (address => mapping (address => uint96)) internal allowances; mapping (address => uint96) internal balances; /// @notice A record of each accounts delegate mapping (address => address) public delegates; /// @notice A checkpoint for marking number of votes from a given block struct Checkpoint { uint32 fromBlock; uint96 votes; } /// @notice A record of votes checkpoints for each account, by index mapping (address => mapping (uint32 => Checkpoint)) public checkpoints; /// @notice The number of checkpoints for each account mapping (address => uint32) public numCheckpoints; /// @notice The EIP-712 typehash for the contract's domain bytes32 public constant DOMAIN_TYPEHASH = keccak256("EIP712Domain(string name,uint256 chainId,address verifyingContract)"); /// @notice The EIP-712 typehash for the delegation struct used by the contract bytes32 public constant DELEGATION_TYPEHASH = keccak256("Delegation(address delegatee,uint256 nonce,uint256 expiry)"); /// @notice The EIP-712 typehash for the permit struct used by the contract bytes32 public constant PERMIT_TYPEHASH = keccak256("Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)"); /// @notice A record of states for signing / validating signatures mapping (address => uint) public nonces; /// @notice An event thats emitted when the minter address is changed event MinterChanged(address minter, address newMinter); /// @notice An event thats emitted when an account changes its delegate event DelegateChanged(address indexed delegator, address indexed fromDelegate, address indexed toDelegate); /// @notice An event thats emitted when a delegate account's vote balance changes event DelegateVotesChanged(address indexed delegate, uint previousBalance, uint newBalance); /// @notice The standard EIP-20 transfer event event Transfer(address indexed from, address indexed to, uint256 amount); /// @notice The standard EIP-20 approval event event Approval(address indexed owner, address indexed spender, uint256 amount); constructor(address account, address minter_, uint mintingAllowedAfter_) public { require(mintingAllowedAfter_ >= block.timestamp, "KWIK::constructor: minting can only begin after deployment"); balances[account] = uint96(totalSupply); emit Transfer(address(0), account, totalSupply); minter = minter_; emit MinterChanged(address(0), minter); mintingAllowedAfter = mintingAllowedAfter_; } function setMinter(address minter_) external { require(msg.sender == minter, "KWIK::setMinter: only the minter can change the minter address"); emit MinterChanged(minter, minter_); minter = minter_; } function mint(address dst, uint rawAmount) external { require(msg.sender == minter, "KWIK::mint: only the minter can mint"); require(block.timestamp >= mintingAllowedAfter, "KWIK::mint: minting not allowed yet"); require(dst != address(0), "KWIK::mint: cannot transfer to the zero address"); // record the mint mintingAllowedAfter = SafeMath.add(block.timestamp, minimumTimeBetweenMints); // mint the amount uint96 amount = safe96(rawAmount, "KWIK::mint: amount exceeds 96 bits"); require(amount <= SafeMath.div(SafeMath.mul(totalSupply, mintCap), 100), "KWIK::mint: exceeded mint cap"); totalSupply = safe96(SafeMath.add(totalSupply, amount), "KWIK::mint: totalSupply exceeds 96 bits"); // transfer the amount to the recipient balances[dst] = add96(balances[dst], amount, "KWIK::mint: transfer amount overflows"); emit Transfer(address(0), dst, amount); // move delegates _moveDelegates(address(0), delegates[dst], amount); } /** * @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]; } function approve(address spender, uint rawAmount) external returns (bool) { uint96 amount; if (rawAmount == uint(-1)) { amount = uint96(-1); } else { amount = safe96(rawAmount, "KWIK::approve: amount exceeds 96 bits"); } allowances[msg.sender][spender] = amount; emit Approval(msg.sender, spender, amount); return true; } function permit(address owner, address spender, uint rawAmount, uint deadline, uint8 v, bytes32 r, bytes32 s) external { uint96 amount; if (rawAmount == uint(-1)) { amount = uint96(-1); } else { amount = safe96(rawAmount, "KWIK::permit: amount exceeds 96 bits"); } bytes32 domainSeparator = keccak256(abi.encode(DOMAIN_TYPEHASH, keccak256(bytes(name)), getChainId(), address(this))); bytes32 structHash = keccak256(abi.encode(PERMIT_TYPEHASH, owner, spender, rawAmount, nonces[owner]++, deadline)); bytes32 digest = keccak256(abi.encodePacked("\x19\x01", domainSeparator, structHash)); address signatory = ecrecover(digest, v, r, s); require(signatory != address(0), "KWIK::permit: invalid signature"); require(signatory == owner, "KWIK::permit: unauthorized"); require(now <= deadline, "KWIK::permit: signature expired"); allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } function transfer(address dst, uint rawAmount) external returns (bool) { uint96 amount = safe96(rawAmount, "KWIK::transfer: amount exceeds 96 bits"); _transferTokens(msg.sender, dst, amount); return true; } function transferFrom(address src, address dst, uint rawAmount) external returns (bool) { address spender = msg.sender; uint96 spenderAllowance = allowances[src][spender]; uint96 amount = safe96(rawAmount, "KWIK::approve: amount exceeds 96 bits"); if (spender != src && spenderAllowance != uint96(-1)) { uint96 newAllowance = sub96(spenderAllowance, amount, "KWIK::transferFrom: transfer amount exceeds spender allowance"); allowances[src][spender] = newAllowance; emit Approval(src, spender, newAllowance); } _transferTokens(src, dst, amount); return true; } function balanceOf(address account) external view returns (uint) { return balances[account]; } function delegate(address delegatee) public { return _delegate(msg.sender, delegatee); } 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), "KWIK::delegateBySig: invalid signature"); require(nonce == nonces[signatory]++, "KWIK::delegateBySig: invalid nonce"); require(now <= expiry, "KWIK::delegateBySig: signature expired"); return _delegate(signatory, delegatee); } function getPriorVotes(address account, uint blockNumber) public view returns (uint96) { require(blockNumber < block.number, "KWIK::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 getCurrentVotes(address account) external view returns (uint96) { uint32 nCheckpoints = numCheckpoints[account]; return nCheckpoints > 0 ? checkpoints[account][nCheckpoints - 1].votes : 0; } function _delegate(address delegator, address delegatee) internal { address currentDelegate = delegates[delegator]; uint96 delegatorBalance = balances[delegator]; delegates[delegator] = delegatee; emit DelegateChanged(delegator, currentDelegate, delegatee); _moveDelegates(currentDelegate, delegatee, delegatorBalance); } function _moveDelegates(address srcRep, address dstRep, uint96 amount) internal { if (srcRep != dstRep && amount > 0) { if (srcRep != address(0)) { uint32 srcRepNum = numCheckpoints[srcRep]; uint96 srcRepOld = srcRepNum > 0 ? checkpoints[srcRep][srcRepNum - 1].votes : 0; uint96 srcRepNew = sub96(srcRepOld, amount, "KWIK::_moveVotes: vote amount underflows"); _writeCheckpoint(srcRep, srcRepNum, srcRepOld, srcRepNew); } if (dstRep != address(0)) { uint32 dstRepNum = numCheckpoints[dstRep]; uint96 dstRepOld = dstRepNum > 0 ? checkpoints[dstRep][dstRepNum - 1].votes : 0; uint96 dstRepNew = add96(dstRepOld, amount, "KWIK::_moveVotes: vote amount overflows"); _writeCheckpoint(dstRep, dstRepNum, dstRepOld, dstRepNew); } } } function _transferTokens(address src, address dst, uint96 amount) internal { require(src != address(0), "KWIK::_transferTokens: cannot transfer from the zero address"); require(dst != address(0), "KWIK::_transferTokens: cannot transfer to the zero address"); balances[src] = sub96(balances[src], amount, "KWIK::_transferTokens: transfer amount exceeds balance"); balances[dst] = add96(balances[dst], amount, "KWIK::_transferTokens: transfer amount overflows"); emit Transfer(src, dst, amount); _moveDelegates(delegates[src], delegates[dst], amount); } function _writeCheckpoint(address delegatee, uint32 nCheckpoints, uint96 oldVotes, uint96 newVotes) internal { uint32 blockNumber = safe32(block.number, "KWIK::_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 safe96(uint n, string memory errorMessage) internal pure returns (uint96) { require(n < 2**96, errorMessage); return uint96(n); } function safe32(uint n, string memory errorMessage) internal pure returns (uint32) { require(n < 2**32, errorMessage); return uint32(n); } function sub96(uint96 a, uint96 b, string memory errorMessage) internal pure returns (uint96) { require(b <= a, errorMessage); return a - b; } function add96(uint96 a, uint96 b, string memory errorMessage) internal pure returns (uint96) { uint96 c = a + b; require(c >= a, errorMessage); return c; } function getChainId() internal pure returns (uint) { uint256 chainId; assembly { chainId := chainid() } return chainId; } } // File: contracts/MasterChef.sol pragma solidity 0.6.12; interface IMigratorChef { // Perform LP token migration from legacy UniswapV2 to KwikSwap. // Take the current LP token address and return the new LP token address. // Migrator should have full access to the caller's LP token. // Return the new LP token address. // // XXX Migrator must have allowance access to UniswapV2 LP tokens. // KwikSwap must mint EXACTLY the same amount of KwikSwap LP tokens or // else something bad will happen. Traditional UniswapV2 does not // do that so be careful! function migrate(IERC20 token) external returns (IERC20); } // MasterChef is the master of Kwik. He can make Kwik and he is a fair guy. // // Note that it's ownable and the owner wields tremendous power. The ownership // will be transferred to a governance smart contract once KWIK is sufficiently // distributed and the community can show to govern itself. // // Have fun reading it. Hopefully it's bug-free. God bless. contract MasterChef is Ownable { using SafeMath for uint256; using SafeERC20 for IERC20; // Info of each user. struct UserInfo { uint256 amount; // How many LP tokens the user has provided. uint256 rewardDebt; // Reward debt. See explanation below. // // We do some fancy math here. Basically, any point in time, the amount of KWIKs // entitled to a user but is pending to be distributed is: // // pending reward = (user.amount * pool.accKwikPerShare) - user.rewardDebt // // Whenever a user deposits or withdraws LP tokens to a pool. Here's what happens: // 1. The pool's `accKwikPerShare` (and `lastRewardBlock`) gets updated. // 2. User receives the pending reward sent to his/her address. // 3. User's `amount` gets updated. // 4. User's `rewardDebt` gets updated. } // Info of each pool. struct PoolInfo { IERC20 lpToken; // Address of LP token contract. uint256 allocPoint; // How many allocation points assigned to this pool. KWIKs to distribute per block. uint256 lastRewardBlock; // Last block number that KWIKs distribution occurs. uint256 accKwikPerShare; // Accumulated KWIKs per share, times 1e12. See below. } // The KWIK TOKEN! KWIK public kwik; // Dev address. address public devaddr; // Block number when bonus KWIK period ends. uint256 public bonusEndBlock; // KWIK tokens created per block. uint256 public kwikPerBlock; // Bonus muliplier for early kwik makers. uint256 public constant BONUS_MULTIPLIER = 10; // The migrator contract. It has a lot of power. Can only be set through governance (owner). IMigratorChef public migrator; // Info of each pool. PoolInfo[] public poolInfo; // Info of each user that stakes LP tokens. mapping (uint256 => mapping (address => UserInfo)) public userInfo; // Total allocation poitns. Must be the sum of all allocation points in all pools. uint256 public totalAllocPoint = 0; // The block number when KWIK mining starts. uint256 public startBlock; event Deposit(address indexed user, uint256 indexed pid, uint256 amount); event Withdraw(address indexed user, uint256 indexed pid, uint256 amount); event EmergencyWithdraw(address indexed user, uint256 indexed pid, uint256 amount); constructor( KWIK _kwik, address _devaddr, uint256 _kwikPerBlock, uint256 _startBlock, uint256 _bonusEndBlock ) public { kwik = _kwik; devaddr = _devaddr; kwikPerBlock = _kwikPerBlock; bonusEndBlock = _bonusEndBlock; startBlock = _startBlock; } function poolLength() external view returns (uint256) { return poolInfo.length; } // Add a new lp to the pool. Can only be called by the owner. // XXX DO NOT add the same LP token more than once. Rewards will be messed up if you do. function add(uint256 _allocPoint, IERC20 _lpToken, bool _withUpdate) public onlyOwner { if (_withUpdate) { massUpdatePools(); } uint256 lastRewardBlock = block.number > startBlock ? block.number : startBlock; totalAllocPoint = totalAllocPoint.add(_allocPoint); poolInfo.push(PoolInfo({ lpToken: _lpToken, allocPoint: _allocPoint, lastRewardBlock: lastRewardBlock, accKwikPerShare: 0 })); } // Update the given pool's KWIK allocation point. Can only be called by the owner. function set(uint256 _pid, uint256 _allocPoint, bool _withUpdate) public { if (_withUpdate) { massUpdatePools(); } totalAllocPoint = totalAllocPoint.sub(poolInfo[_pid].allocPoint).add(_allocPoint); poolInfo[_pid].allocPoint = _allocPoint; } // Set the migrator contract. Can only be called by the owner. function setMigrator(IMigratorChef _migrator) public onlyOwner { migrator = _migrator; } // Migrate lp token to another lp contract. Can be called by anyone. We trust that migrator contract is good. function migrate(uint256 _pid) public { require(address(migrator) != address(0), "migrate: no migrator"); PoolInfo storage pool = poolInfo[_pid]; IERC20 lpToken = pool.lpToken; uint256 bal = lpToken.balanceOf(address(this)); lpToken.safeApprove(address(migrator), bal); IERC20 newLpToken = migrator.migrate(lpToken); require(bal == newLpToken.balanceOf(address(this)), "migrate: bad"); pool.lpToken = newLpToken; } // function to update the last block function updateRewardBlock(uint _blockNumber) public onlyOwner{ bonusEndBlock = _blockNumber; } // function to update the first block function updateRewardFirstBlock(uint _blockNumber) public onlyOwner{ startBlock = _blockNumber; } // function to withdraw the reward token function rewardWithdraw() public onlyOwner{ kwik.transfer(msg.sender, kwik.balanceOf(address(this))); } // Return reward multiplier over the given _from to _to block. function getMultiplier(uint256 _from, uint256 _to) public view returns (uint256) { if (_to <= bonusEndBlock) { return _to.sub(_from).mul(BONUS_MULTIPLIER); } else if (_from >= bonusEndBlock) { return _to.sub(_from); } else { return bonusEndBlock.sub(_from).mul(BONUS_MULTIPLIER).add( _to.sub(bonusEndBlock) ); } } // update the reward per block function setBlockReward(uint _tokens) public onlyOwner { kwikPerBlock = _tokens; } // View function to see pending KWIKs on frontend. function pendingKwik(uint256 _pid, address _user) external view returns (uint256) { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][_user]; uint256 accKwikPerShare = pool.accKwikPerShare; uint256 lpSupply = pool.lpToken.balanceOf(address(this)); if (block.number > pool.lastRewardBlock && lpSupply != 0) { uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number); uint256 kwikReward = multiplier.mul(kwikPerBlock).mul(pool.allocPoint).div(totalAllocPoint); accKwikPerShare = accKwikPerShare.add(kwikReward.mul(1e12).div(lpSupply)); } return user.amount.mul(accKwikPerShare).div(1e12).sub(user.rewardDebt); } // Update reward vairables for all pools. Be careful of gas spending! function massUpdatePools() public { uint256 length = poolInfo.length; for (uint256 pid = 0; pid < length; ++pid) { updatePool(pid); } } // Update reward variables of the given pool to be up-to-date. function updatePool(uint256 _pid) public { PoolInfo storage pool = poolInfo[_pid]; if (block.number <= pool.lastRewardBlock) { return; } uint256 lpSupply = pool.lpToken.balanceOf(address(this)); if (lpSupply == 0) { pool.lastRewardBlock = block.number; return; } uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number); uint256 kwikReward = multiplier.mul(kwikPerBlock).mul(pool.allocPoint).div(totalAllocPoint); kwik.transfer(devaddr, kwikReward.div(10)); kwik.transfer(address(this), kwikReward); pool.accKwikPerShare = pool.accKwikPerShare.add(kwikReward.mul(1e12).div(lpSupply)); pool.lastRewardBlock = block.number; } // Deposit LP tokens to MasterChef for KWIK allocation. function deposit(uint256 _pid, uint256 _amount) public { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; updatePool(_pid); if (user.amount > 0) { uint256 pending = user.amount.mul(pool.accKwikPerShare).div(1e12).sub(user.rewardDebt); safeKwikTransfer(msg.sender, pending); } pool.lpToken.safeTransferFrom(address(msg.sender), address(this), _amount); user.amount = user.amount.add(_amount); user.rewardDebt = user.amount.mul(pool.accKwikPerShare).div(1e12); emit Deposit(msg.sender, _pid, _amount); } // Withdraw LP tokens from MasterChef. function withdraw(uint256 _pid, uint256 _amount) public { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; require(user.amount >= _amount, "withdraw: not good"); updatePool(_pid); uint256 pending = user.amount.mul(pool.accKwikPerShare).div(1e12).sub(user.rewardDebt); safeKwikTransfer(msg.sender, pending); user.amount = user.amount.sub(_amount); user.rewardDebt = user.amount.mul(pool.accKwikPerShare).div(1e12); pool.lpToken.safeTransfer(address(msg.sender), _amount); emit Withdraw(msg.sender, _pid, _amount); } // Withdraw without caring about rewards. EMERGENCY ONLY. function emergencyWithdraw(uint256 _pid) public { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; pool.lpToken.safeTransfer(address(msg.sender), user.amount); emit EmergencyWithdraw(msg.sender, _pid, user.amount); user.amount = 0; user.rewardDebt = 0; } // Safe kwik transfer function, just in case if rounding error causes pool to not have enough KWIKs. function safeKwikTransfer(address _to, uint256 _amount) internal { uint256 kwikBal = kwik.balanceOf(address(this)); if (_amount > kwikBal) { kwik.transfer(_to, kwikBal); } else { kwik.transfer(_to, _amount); } } // Update dev address by the previous dev. function dev(address _devaddr) public { require(msg.sender == devaddr, "dev: wut?"); devaddr = _devaddr; } }
Safe kwik transfer function, just in case if rounding error causes pool to not have enough KWIKs.
function safeKwikTransfer(address _to, uint256 _amount) internal { uint256 kwikBal = kwik.balanceOf(address(this)); if (_amount > kwikBal) { kwik.transfer(_to, kwikBal); kwik.transfer(_to, _amount); } }
1,977,645
./full_match/137/0x9e212e5C60Ec2866464fb167F91e7Ef75094521F/sources/EnglishForIT.sol
internal function that's called before a token is transferred & reverts if the token is not either minted or burned making it soulbound
function _beforeTokenTransfer(address from, address to, uint256) pure override internal { require(from == address(0) || to == address(0), "Not allowed to transfer token"); }
4,717,466
./full_match/1/0xE8Ff7BFEF5DacB57E87bC2d0B6CCFefBE5f546BC/sources/src/Facets/OptimismBridgeFacet.sol
Register token and bridge assetId Address of token bridge Address of bridge for asset
function registerOptimismBridge(address assetId, address bridge) external { LibDiamond.enforceIsContractOwner(); Storage storage s = getStorage(); if (!s.initialized) revert NotInitialized(); if (bridge == address(0)) { revert InvalidConfig(); } s.bridges[assetId] = IL1StandardBridge(bridge); emit OptimismBridgeRegistered(assetId, bridge); }
16,461,220
./partial_match/1/0x397f588Afa6ac70c5B7F742294655f2CEADAf4B5/sources/contracts/CoinDistributor.sol
Ensure the user is claiming for the current version
function claimRewards( uint256 _amount, bytes32[] calldata _merkleProof ) external { require( lastClaimedVersion[msg.sender] < currentVersion, "Already claimed for this version." ); bytes32 leaf = keccak256(abi.encodePacked(msg.sender, _amount)); require( MerkleProof.verify(_merkleProof, merkleRoot, leaf), "Invalid Merkle Proof." ); TOTAL_CLAIMED[msg.sender] += _amount; IERC20(erc20token).transfer(msg.sender, _amount); emit Claimed(msg.sender, _amount); }
3,696,347
//Address: 0xc22407b1f34e494b7f85187fafc2ce5d13871ffb //Contract name: GratitudeCrowdsale //Balance: 0 Ether //Verification Date: 11/1/2017 //Transacion Count: 11 // CODE STARTS HERE pragma solidity ^0.4.11; /** * @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 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; } } /** * @title RefundVault * @dev This contract is used for storing funds while a crowdsale * is in progress. Supports refunding the money if crowdsale fails, * and forwarding it if crowdsale is successful. */ contract RefundVault is Ownable { using SafeMath for uint256; enum State { Active, Refunding, Closed } mapping (address => uint256) public deposited; address public wallet; State public state; event Closed(); event RefundsEnabled(); event Refunded(address indexed beneficiary, uint256 weiAmount); function RefundVault(address _wallet) { require(_wallet != 0x0); wallet = _wallet; state = State.Active; } function deposit(address investor) onlyOwner public payable { require(state == State.Active); deposited[investor] = deposited[investor].add(msg.value); } function close() onlyOwner public { require(state == State.Active); state = State.Closed; Closed(); wallet.transfer(this.balance); } function enableRefunds() onlyOwner public { require(state == State.Active); state = State.Refunding; RefundsEnabled(); } function refund(address investor) public { require(state == State.Refunding); uint256 depositedValue = deposited[investor]; deposited[investor] = 0; investor.transfer(depositedValue); Refunded(investor, depositedValue); } } /** * @title ERC20Basic * @dev Simpler version of ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/179 */ contract ERC20Basic { uint256 public totalSupply; function balanceOf(address who) constant returns (uint256); function transfer(address to, uint256 value) returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); } /** * @title ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/20 */ contract ERC20 is ERC20Basic { function allowance(address owner, address spender) constant returns (uint256); function transferFrom(address from, address to, uint256 value) returns (bool); function approve(address spender, uint256 value) returns (bool); event Approval(address indexed owner, address indexed spender, uint256 value); } /** * @title Basic token * @dev Basic version of StandardToken, with no allowances. */ contract BasicToken is ERC20Basic { using SafeMath for uint256; mapping(address => uint256) balances; /** * @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) returns (bool) { 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) constant returns (uint256 balance) { return balances[_owner]; } } /** * @title Standard ERC20 token * * @dev Implementation of the basic standard token. * @dev https://github.com/ethereum/EIPs/issues/20 * @dev Based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol */ contract StandardToken is ERC20, BasicToken { mapping (address => mapping (address => uint256)) 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 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(0x0, _to, _amount); return true; } /** * @dev Function to stop minting new tokens. * @return True if the operation was successful. */ function finishMinting() onlyOwner public returns (bool) { mintingFinished = true; MintFinished(); return true; } } // Standard token variables contract TokenOfGratitude is MintableToken { string constant public name = "Token Of Gratitude"; string constant public symbol = "ToG"; uint8 constant public decimals = 0; uint256 public expirationDate = 1672531199; address public goldenTicketOwner; // Mappings for easier backchecking mapping (address => uint) redeemed; // ToG redeem event with encrypted message (hopefully a contact info) event tokenRedemption(address indexed supported, string message); // Golden ticket related events event goldenTicketMoved(address indexed newOwner); event goldenTicketUsed(address charlie, string message); function TokenOfGratitude() { goldenTicketOwner = msg.sender; } /** * Function returning the current price of ToG * @dev can be used prior to the donation as a constant function but it is mainly used in the noname function * @param message should contain an encrypted contract info of the redeemer to setup a meeting */ function redeem(string message) { // Check caller has a token require (balances[msg.sender] >= 1); // Check tokens did not expire require (now <= expirationDate); // Lock the token against further transfers balances[msg.sender] -= 1; redeemed[msg.sender] += 1; // Call out tokenRedemption(msg.sender, message); } /** * Function using the Golden ticket - the current holder will be able to get the prize only based on the "goldenTicketUsed" event * @dev First checks the GT owner, then fires the event and then changes the owner to null so GT can't be used again * @param message should contain an encrypted contract info of the redeemer to claim the reward */ function useGoldenTicket(string message){ require(msg.sender == goldenTicketOwner); goldenTicketUsed(msg.sender, message); goldenTicketOwner = 0x0; } /** * Function using the Golden ticket - the current holder will be able to get the prize only based on the "goldenTicketUsed" event * @dev First checks the GT owner, then change the owner and fire an event about the ticket changing owner * @dev The Golden ticket isn't a standard ERC20 token and therefore it needs special handling * @param newOwner should be a valid address of the new owner */ function giveGoldenTicket(address newOwner) { require (msg.sender == goldenTicketOwner); goldenTicketOwner = newOwner; goldenTicketMoved(newOwner); } } // <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. */ pragma solidity ^0.4.0;//please import oraclizeAPI_pre0.4.sol when solidity < 0.4.0 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 Crowdsale * @dev Crowdsale is a base contract for managing a token crowdsale. * Crowdsales have a start and end timestamps, where investors can make * token purchases and the crowdsale will assign them tokens based * on a token per ETH rate. Funds collected are forwarded to a wallet * as they arrive. */ contract Crowdsale { using SafeMath for uint256; // The token being sold TokenOfGratitude public token; // start and end timestamps where investments are allowed (both inclusive) uint256 public startTime; uint256 public endTime; // address where funds are collected //address public wallet; => funds are collected in this contract // amount of raised money in wei uint256 public weiRaised; /** * 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); function Crowdsale(uint256 _startTime, uint256 _endTime) { require(_startTime >= now); require(_endTime >= _startTime); token = createTokenContract(); startTime = _startTime; endTime = _endTime; } // creates the token to be sold. // override this method to have crowdsale of a specific mintable token. function createTokenContract() internal returns (TokenOfGratitude) { return new TokenOfGratitude(); } // fallback function can be used to buy tokens function () payable { buyTokens(msg.sender); } // low level token purchase function function buyTokens(address beneficiary) public payable {} // @return true if the transaction can buy tokens function validPurchase() internal constant returns (bool) { bool withinPeriod = now >= startTime && now <= endTime; bool nonZeroPurchase = msg.value != 0; return withinPeriod && nonZeroPurchase; } // @return true if crowdsale event has ended function hasEnded() public constant returns (bool) { return now > endTime; } } /** * @title FinalizableCrowdsale * @dev Extension of Crowdsale where an owner can do extra work * after finishing. */ contract FinalizableCrowdsale is Crowdsale, Ownable { using SafeMath for uint256; bool public isFinalized = false; event Finalized(); /** * @dev Must be called after crowdsale ends, to do some extra finalization * work. Calls the contract's finalization function. */ function finalize() onlyOwner public { require(!isFinalized); require(hasEnded()); finalization(); Finalized(); isFinalized = true; } /** * @dev Can be overridden to add finalization logic. The overriding function * should call super.finalization() to ensure the chain of finalization is * executed entirely. */ function finalization() internal { } } /** * @title Token of Gratitude fundraiser */ contract GratitudeCrowdsale is FinalizableCrowdsale, usingOraclize { // Utility variables uint256 public tokensLeft; // Defining helper variables to differentiate Oraclize queries bytes32 qID1; bytes32 qID2; // Rate related variables uint256 public rate; bool public hasRate; uint public rateAge; /* * Randomly chosen number for the meal invitation winner * @dev each supporter gets a nonce - the luckyNumber is randomly picked nonce by Oraclize * @dev then points to donorsList[luckyNumber] mapping to get the address of the winner */ bool public hasRandom; uint256 luckyNumber; /* * Medicines sans frontiers (MSF) | Doctors without borders - the public donation address * @dev please check for due diligence: * @notice Link to English site: https://www.lekari-bez-hranic.cz/en/bank-details#cryptocurrencies * @notice Link to Czech site: https://www.lekari-bez-hranic.cz/bankovni-spojeni#kryptomeny * @notice Link to Etherscan: https://etherscan.io/address/0x249f02676d09a41938309447fda33fb533d91dfc */ address constant public addressOfMSF = 0x249F02676D09A41938309447fdA33FB533d91DFC; address constant public communityAddress = 0x008e9392ef82edBA2c45f2B02B9A21ac6B599BCA; // Mapping of supporters for random selection uint256 public donors = 0; mapping (address => bool) donated; mapping (uint256 => address) donorsList; // Fundraising finalization events event finishFundraiser(uint raised); event fundsToMSF(uint value); event fundsToCommunity(uint value); // Special events for a very special golden ticket! event goldenTicketFound(address winner); // Oraclize related events event newOraclizeQuery(string description); event newRate(string price); event newRandom(string price); /** * Constructor * @dev Contract constructor * @param _startTime uint256 is a unix timestamp of when the fundraiser starts * @param _endTime uint256 is a unix timestamp of when the fundraiser ends */ function GratitudeCrowdsale(uint256 _startTime, uint256 _endTime) FinalizableCrowdsale() Crowdsale(_startTime, _endTime) { owner = msg.sender; tokensLeft = 500; } /** * buyTokens override * @dev Implementation of the override to the buy in function for incoming ETH * @param beneficiary address of the participating party */ function buyTokens(address beneficiary) public payable { require(beneficiary != 0x0); require(validPurchase()); // Sign up first-time donors to the list + give them a nonce so they can win the golden ticket! if (!donated[beneficiary]) { donated[beneficiary] = true; donorsList[donors] = beneficiary; donors += 1; } // Check if there are still tokens left (otherwise skipped) if (tokensLeft > 0) { // See how many tokens can the donor get. uint256 toGet = howMany(msg.value); // If some, give the tokens to the donor. if (toGet > 0) { token.mint(beneficiary,toGet); TokenPurchase(msg.sender, beneficiary, msg.value, toGet); } } // update state weiRaised = weiRaised.add(msg.value); } /** * Recursive function that counts amount of tokens to assign (even if a contribution overflows certain price range) * @dev Recalculating tokens to receive based on teh currentPrice(2) function. * @dev Number of recursive entrances is equal to the number of price levels (not counting the initial call) * @return toGet - amount of tokens to receive from the particular price range */ function howMany(uint256 _value) internal returns (uint256){ // Check current price level var (price, canGet) = currentPrice(); uint256 toGet = _value.div(price); // Act based on amount of tokens to get if (canGet == 0) { toGet = 0; } else if (toGet > canGet) { tokensLeft -= canGet; toGet = canGet + howMany(_value - (canGet*price)); } else { tokensLeft -= toGet; } return toGet; } /** * Function returning the current price of ToG and amount of tokens available at that price * @dev can be used prior to the donation as a constant function but it is mainly used in the noname function * @return price - current price range * @return maxAtPrice - maximal amount of tokens available at current price */ function currentPrice() constant returns (uint256 price, uint256 maxAtPrice){ if (tokensLeft > 400) { return (100 finney, tokensLeft - 400); } else if (tokensLeft > 300) { return (200 finney, tokensLeft - 300); } else if (tokensLeft > 200) { return (300 finney, tokensLeft - 200); } else if (tokensLeft > 100) { return (400 finney, tokensLeft - 100); } else { return (500 finney, tokensLeft); } } /** * The pre-finalization requirement - get ETHUSD rate * @dev initiates Oraclize call for ETHUSD rate * @param gasLimit uint256 setting gasLimit of the __callback tx from Oraclize */ function loadRate(uint256 gasLimit) payable { // Owner check require(msg.sender == owner); // Make an Oraclize queriey for ETHUSD rate getRateUSD(gasLimit); } /** * The pre-finalization requirement - get Random number * @dev initiates Oraclize call for random number * @param gasLimit uint256 setting gasLimit of the __callback tx from Oraclize */ function loadRandom(uint256 gasLimit) payable { // Owner check require(msg.sender == owner); // Make an Oraclize query for a random number getRandom(gasLimit); } /** * The finalization override - commented bellow */ function finalization() internal { //Check if the crowdsale has ended require(hasEnded()); // Check the rate was queried less then 1 hour ago require(hasRate); require((now - rateAge) <= 3600); // Check the random number was received require(hasRandom); // Assign GoldenTicket token.giveGoldenTicket(donorsList[luckyNumber]); goldenTicketFound(donorsList[luckyNumber]); // Calling checkResult from PriceChecker contract uint256 funding = checkResult(); uint256 raisedWei = this.balance; uint256 charityShare; uint256 toCharity; // If goal isn't met => send everything to MSF if (funding < 10000) { addressOfMSF.transfer(raisedWei); fundsToMSF(toCharity); } else if (funding < 25000) { // If 2nd goal isn't met => send the rest above the 1st goal to MSF charityShare = toPercentage(funding, funding-10000); toCharity = fromPercentage(raisedWei, charityShare); // Donate to charity first addressOfMSF.transfer(toCharity); fundsToMSF(toCharity); // Send funds to community; communityAddress.transfer(raisedWei - toCharity); fundsToCommunity(raisedWei - toCharity); } else { // If 2nd goal is met => send the rest above the 2nd goal to MSF charityShare = toPercentage(funding, funding-25000); toCharity = fromPercentage(raisedWei, charityShare); // Donate to charity first addressOfMSF.transfer(toCharity); fundsToMSF(toCharity); // Send funds to community; communityAddress.transfer(raisedWei - toCharity); fundsToCommunity(raisedWei - toCharity); } token.finishMinting(); super.finalization(); } /** * @dev Checking results of the fundraiser in USD * @return rated - total funds raised converted to USD */ function checkResult() internal returns (uint256){ uint256 raised = this.balance; // convert wei => usd to perform checks uint256 rated = (raised.mul(rate)).div(10000000000000000000000); return rated; } /** * Helper function to get split funds between the community and charity I * @dev Counts percentage of the total funds that belongs to the charity * @param total funds raised in USD * @param part of the total funds raised that should go to the charity * @return percentage in full expressed as a natural number between 0 and 100 */ function toPercentage (uint256 total, uint256 part) internal returns (uint256) { return (part*100)/total; } /** * Helper function to get split funds between the community and charity II * @dev Counts the exact amount of Wei to get send to the charity * @param value of total funds raised in Wei * @param percentage to be used obtained from the toPercentage(2) function * @return amount of Wei to be send to the charity */ function fromPercentage(uint256 value, uint256 percentage) internal returns (uint256) { return (value*percentage)/100; } // <DATA FEEDS USING ORACLIZE> /** * @dev Create the ETHUSD query to Kraken thorough Oraclize */ function getRateUSD(uint256 _gasLimit) internal { //require(msg.sender == owner); oraclize_setProof(proofType_TLSNotary); if (oraclize.getPrice("URL") > this.balance) { newOraclizeQuery("Oraclize: Insufficient funds!"); } else { newOraclizeQuery("Oraclize was asked for ETHUSD rate."); qID1 = oraclize_query("URL", "json(https://api.kraken.com/0/public/Ticker?pair=ETHUSD).result.XETHZUSD.p.1", _gasLimit); } } /** * @dev Create the random number query to Oraclize */ function getRandom(uint256 _gasLimit) internal { //require (msg.sender == owner); oraclize_setProof(proofType_Ledger); if (oraclize.getPrice("random") > this.balance) { newOraclizeQuery("Oraclize: Insufficient funds!"); } else { newOraclizeQuery("Oraclize was asked for a random number."); // Make query for 4 random bytes to potentially get a number between 0 and 4294967295. // The assumption is that there won't be more then 4294967295 participants. // This may potentially hurt your contract as the "random mod participants" result distribution is unequal. // There creates an incentive to join earlier to have an micro advantage. qID2 = oraclize_newRandomDSQuery(0, 4, _gasLimit); } } /** *Oraclize callback function awaiting for response from the queries * @dev uses qType to handle the last called query type * @dev different querytypes shouldn't be called before callback was received * @dev -> not implementing a query que as "owner" is the only party responsible for creating order */ function __callback(bytes32 myid, string result, bytes proof) { require(msg.sender == oraclize_cbAddress()); if (myid == qID1) { checkQueryA(myid, result, proof); } else if (myid == qID2) { checkQueryB(myid, result, proof); } } /** * A helper function to separate reaction to different Oraclize queries - ETHUSD rate * @dev reaction to ETHUSD rate oraclize callback - getRateUSD() * @dev sets global vars rate to the result and rateAge to current timeStamp * @param _myid 32 bytes identifying the query generated by Oraclize * @param _result string with query result by Oraclize * @param _proof byte array with the proof of source by Oraclize */ function checkQueryA(bytes32 _myid, string _result, bytes _proof) internal { newRate(_result); // calling Oraclize string => uint256 converter for a number with 4 decimals rate = parseInt(_result,4); rateAge = now; hasRate = true; } /** * A helper function to separate reaction to different Oraclize queries - random number * @dev reaction to random number oraclize callback - getRandom(number of participants) * @dev sets global var luckyNumber to the result * @param _myid 32 bytes identifying the query generated by Oraclize * @param _result string with query result by Oraclize * @param _proof byte array with the proof of source by Oraclize */ function checkQueryB(bytes32 _myid, string _result, bytes _proof) internal oraclize_randomDS_proofVerify(_myid, _result, _proof) { newRandom(_result); // Calling Oraclize string => uint converter uint256 someNumber = parseInt(string(bytes(_result)),0); // Getting a luckyNumber between 0 and the number of donors (Random-number modulo number of donors) luckyNumber = someNumber%donors; hasRandom = true; } //Adjusting the hasEnded function to a case where all tokens were sold function hasEnded() public constant returns (bool) { return ((now > endTime) || (tokensLeft <= 0)) ; } }
Function returning the current price of ToG can be used prior to the donation as a constant function but it is mainly used in the noname function message should contain an encrypted contract info of the redeemer to setup a meeting/ Check caller has a token Check tokens did not expire Lock the token against further transfers Call out
function redeem(string message) { require (balances[msg.sender] >= 1); require (now <= expirationDate); balances[msg.sender] -= 1; redeemed[msg.sender] += 1; tokenRedemption(msg.sender, message); }
12,655,504
pragma solidity ^0.4.15; /** * @title Queue * @dev Data structure contract used in `Crowdsale.sol` * Allows buyers to line up on a first-in-first-out basis * See this example: http://interactivepython.org/courselib/static/pythonds/BasicDS/ImplementingaQueueinPython.html */ contract Queue { /* State variables */ uint8 size; uint8 numInside; bool isFull; bool isEmpty; uint8 first; uint8 lastFilled; uint8 nextFree; mapping (address => uint8) addr2place; mapping (uint8 => address) place2addr; uint timeAsFirst; uint maxTimeinQ = 5 minutes; /* Add events */ event timeEject(); /* Add constructor */ function Queue() { size = 5; first = 0; lastFilled = 0; isFull = false; isEmpty = true; numInside = 0; } /* Returns the number of people waiting in line */ function qsize() constant returns(uint8) { return numInside; } /* Returns whether the queue is empty or not */ function empty() constant returns(bool) { return isEmpty; } /* Returns the address of the person in the front of the queue */ function getFirst() constant returns(address) { return place2addr[0]; } /* Allows `msg.sender` to check their position in the queue */ function checkPlace() constant returns(uint8) { if (addr2place[msg.sender] == 0) { if (place2addr[0] != msg.sender) { return 6; } else { return 0; } } return addr2place[msg.sender]; } /* Allows anyone to expel the first person in line if their time * limit is up */ function checkTime() { if (timeAsFirst + maxTimeinQ >= now) { timeEject(); dequeue(); } } /* Removes the first person in line; either when their time is up or when * they are done with their purchase */ function dequeue() { address firstInLine = getFirst(); uint8 firstPlace = addr2place[firstInLine]; delete addr2place[firstInLine]; delete place2addr[firstPlace]; first = (first + 1) % size; timeAsFirst = now; numInside-=1; if (numInside == 0) { isEmpty = true; } } /* Places `addr` in the first empty position in the queue */ function enqueue(address addr) { if (isFull) { revert(); } addr2place[addr] = nextFree; place2addr[nextFree] = addr; lastFilled = nextFree; nextFree = (lastFilled+1) % size; numInside+=1; if (nextFree >= first) { isFull = true; } if (numInside == 1) { timeAsFirst = now; } } }
Returns the number of people waiting in line /
function qsize() constant returns(uint8) { return numInside; }
1,801,930
// SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "../access/MultiOwnable.sol"; import "openzeppelin-solidity/contracts/token/ERC20/ERC20.sol"; /** * @title CVT * @dev Inheritance of the {ERC20} implementation and Using some * features of {ERC20Burnable} and {ERC20Mintable} . */ contract CVT is MultiOwnable, ERC20 { uint8 private constant OWNERBLE = 7; uint8 private constant MINTABLE = 6; uint8 private constant BURNABLE = 5; /** * @dev Sets the values for {name} and {symbol}, initializes * {decimals} with a value of 0. * * The formal two of these values are immutable: they can only * be set once during construction. */ constructor ( string memory name, string memory symbol ) public payable ERC20(name, symbol) { _setupDecimals(0); } /** * @dev Mints `amount` tokens to `account`. * * See {ERC20-_mint}. */ function mint( address account, uint256 amount ) public onlyOwner(MINTABLE) returns (bool) { _mint(account, amount); return true; } /** * @dev Burns `amount` tokens from the caller. * * See {ERC20Burnable-burn}. */ function burn( uint256 amount ) public returns (bool) { _burn(_msgSender(), amount); return true; } /** * @dev Burns `amount` tokens from `account`. * * See {ERC20Burnable-burnFrom}. */ function burnFrom( address account, uint256 amount ) public onlyOwner(BURNABLE) returns (bool) { // uint256 decreasedAllowance = allowance(account, _msgSender()).sub(amount, "ERC20: burn amount exceeds allowance"); // _approve(account, _msgSender(), decreasedAllowance); _burn(account, amount); return true; } /** * @dev Calls {_addOwnership}. */ function addOwnership( address account, uint8 level ) public virtual onlyOwner(OWNERBLE) returns (bool) { _addOwnership(account, level); return true; } /** * @dev Calls {_deleteOwnership}. */ function deleteOwnership( address account ) public virtual onlyOwner(OWNERBLE) returns (bool) { _deleteOwnership(account); return true; } /** * @dev Calls {_transferOwnership}. */ function transferOwnership( address oldOwner, address newOwner ) public virtual onlyOwner(OWNERBLE) returns (bool) { _transferOwnership(oldOwner, newOwner); return true; } /** * @dev Calls {_changeOwnershipLevel}. */ function changeOwnershipLevel( address account, uint8 level ) public virtual onlyOwner(OWNERBLE) returns (bool) { _changeOwnershipLevel(account, level); return true; } }
Calls {_deleteOwnership}./
function deleteOwnership( address account ) public virtual onlyOwner(OWNERBLE) returns (bool) { _deleteOwnership(account); return true; }
5,475,433
pragma solidity 0.4.25; /* ▒ █ ▀ ▀ ▀ █  ▒ █ ▀ ▀ █  ░ █ ▀ ▀ █  ▒ █ ▀ ▀ █  ▒ █ ░ ▄ ▀  ▒ █ ░ ░ ░  ▒ █ ▀ ▀ ▀   ░ ▀ ▀ ▀ ▄ ▄  ▒ █ ▄ ▄ █  ▒ █ ▄ ▄ █  ▒ █ ▄ ▄ ▀  ▒ █ ▀ ▄ ░  ▒ █ ░ ░ ░  ▒ █ ▀ ▀ ▀   ▒ █ ▄ ▄ ▄ █  ▒ █ ░ ░ ░  ▒ █ ░ ▒ █  ▒ █ ░ ▒ █  ▒ █ ░ ▒ █  ▒ █ ▄ ▄ █  ▒ █ ▄ ▄ ▄   ░ █ ▀ ▀ █  ▀ █ ▀  ▒ █ ▀ ▀ █  ▒ █ ▀ ▀ ▄  ▒ █ ▀ ▀ █  ▒ █ ▀ ▀ ▀ █  ▒ █ ▀ ▀ █   ▒ █ ▄ ▄ █  ▒ █ ░  ▒ █ ▄ ▄ ▀  ▒ █ ░ ▒ █  ▒ █ ▄ ▄ ▀  ▒ █ ░ ░ ▒ █  ▒ █ ▄ ▄ █   ▒ █ ░ ▒ █  ▄ █ ▄  ▒ █ ░ ▒ █  ▒ █ ▄ ▄ ▀  ▒ █ ░ ▒ █  ▒ █ ▄ ▄ ▄ █  ▒ █ ░ ░ ░   https://sparklemobile.io/ Contract can be paused and resumed, but that could also load/reload for later dates* NOTES: ,_, _ In order to "claim tokens" you must first add our token contract address "0x4b7aD3a56810032782Afce12d7d27122bDb96efF" [0,0] |)__) -”-”- ,_, _ Did you hear FREE Sparkle! [0,0] |)__) -”-”- 1) Opposed to setting max number of airdrop winners I changed it to just give out the default airdrod reward to any added address to the airdrop list(see note 3 below). When the tokens run out then the contract will not honor any airdrop awards but can still be run and tokens added to continue using the contract for other giveaways. ,_, _ Follow us on Twitter! [0,0] |)__) -”-”- 2) Added functions to allow adding address(es) with a different token reward than the standard 30 for those cases where some addresses we may want them to have more of an airdrop than the default ,_, _ Like us on Facebook [0,0] |)__) -”-”- 3) I tried to make sure that the general cases of people senting eth to the contract is reverted and not accepted however I am not positive this can stop someone that is determined. With that said I did not add anything to withdraw that potential eth so it would be stuck in this contract if someone happens to send the contract ETH... ,_, _ Join our Telegram and Discord! [0,0] |)__) -”-”- 4)Contract was built with the intention of security in mind, all contracts are built with OpenZeppelin 2.0 latest release https://github.com/OpenZeppelin/openzeppelin-solidity/releases */ contract Ownable { address public ownerField; constructor() public { ownerField = msg.sender; } modifier onlyOwner() { require(msg.sender == ownerField, "Calling address not an owner"); _; } function transferOwnership(address newOwner) public onlyOwner { ownerField = newOwner; } function owner() public view returns(address) { return ownerField; } } /** * @title SafeMath * @dev Math operations with safety checks that revert on error */ library SafeMath { /** * @dev Multiplies two numbers, reverts on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b); return c; } /** * @dev Integer division of two numbers truncating the quotient, reverts on division by zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0); // Solidity only automatically asserts when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Subtracts two numbers, reverts on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a); uint256 c = a - b; return c; } /** * @dev Adds two numbers, reverts on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a); return c; } /** * @dev Divides two numbers and returns the remainder (unsigned integer modulo), * reverts when dividing by zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b != 0); return a % b; } } 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 ); } 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 * @param from address The address which you want to send tokens from * @param to address The address which you want to transfer to * @param value uint256 the amount of tokens to be transferred */ function transferFrom( address from, address to, uint256 value ) public returns (bool) { require(value <= _allowed[from][msg.sender]); _allowed[from][msg.sender] = _allowed[from][msg.sender].sub(value); _transfer(from, to, value); return true; } /** * @dev Increase the amount of tokens that an owner allowed to a spender. * approve should be called when allowed_[_spender] == 0. To increment * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param spender The address which will spend the funds. * @param addedValue The amount of tokens to increase the allowance by. */ function increaseAllowance( address spender, uint256 addedValue ) public returns (bool) { require(spender != address(0)); _allowed[msg.sender][spender] = ( _allowed[msg.sender][spender].add(addedValue)); emit Approval(msg.sender, spender, _allowed[msg.sender][spender]); return true; } /** * @dev Decrease the amount of tokens that an owner allowed to a spender. * approve should be called when allowed_[_spender] == 0. To decrement * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param spender The address which will spend the funds. * @param subtractedValue The amount of tokens to decrease the allowance by. */ function decreaseAllowance( address spender, uint256 subtractedValue ) public returns (bool) { require(spender != address(0)); _allowed[msg.sender][spender] = ( _allowed[msg.sender][spender].sub(subtractedValue)); emit Approval(msg.sender, spender, _allowed[msg.sender][spender]); return true; } /** * @dev Transfer token for a specified addresses * @param from The address to transfer from. * @param to The address to transfer to. * @param value The amount to be transferred. */ function _transfer(address from, address to, uint256 value) internal { require(value <= _balances[from], "Insignificant balance in from address"); require(to != address(0), "Invalid to address specified [0x0]"); _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 != 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 != 0); require(value <= _balances[account]); _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. * @param account The account whose tokens will be burnt. * @param value The amount that will be burnt. */ function _burnFrom(address account, uint256 value) internal { require(value <= _allowed[account][msg.sender]); // Should https://github.com/OpenZeppelin/zeppelin-solidity/issues/707 be accepted, // this function needs to emit an event with the updated approval. _allowed[account][msg.sender] = _allowed[account][msg.sender].sub( value); _burn(account, value); } } contract Pausable is Ownable { bool public paused; modifier ifNotPaused { require(!paused, "Contract is paused"); _; } modifier ifPaused { require(paused, "Contract is not paused"); _; } // Called by the owner on emergency, triggers paused state function pause() external onlyOwner { paused = true; } // Called by the owner on end of emergency, returns to normal state function resume() external onlyOwner ifPaused { paused = false; } } contract AirDropWinners is Ownable, Pausable { using SafeMath for uint256; struct Contribution { uint256 tokenAmount; bool wasClaimed; bool isValid; } address public tokenAddress; //Smartcontract Address uint256 public totalTokensClaimed; // Totaltokens claimed by winners (you do not set this the contract does as tokens are claimed) uint256 public startTime; // airDrop Start time mapping (address => Contribution) contributions; constructor (address _token) Ownable() public { tokenAddress = _token; startTime = now; } /** * @dev getTotalTokensRemaining() provides the function of returning the number of * tokens currently left in the airdrop balance */ function getTotalTokensRemaining() ifNotPaused public view returns (uint256) { return ERC20(tokenAddress).balanceOf(this); } /** * @dev isAddressInAirdropList() provides the function of testing if the * specified address is in fact valid in the airdrop list */ function isAddressInAirdropList(address _addressToLookUp) ifNotPaused public view returns (bool) { Contribution storage contrib = contributions[_addressToLookUp]; return contrib.isValid; } /** * @dev _bulkAddAddressesToAirdrop provides the function of adding addresses * to the airdrop list with the default of 30 sparkle */ function bulkAddAddressesToAirDrop(address[] _addressesToAdd) ifNotPaused public { require(_addressesToAdd.length > 0); for (uint i = 0; i < _addressesToAdd.length; i++) { _addAddressToAirDrop(_addressesToAdd[i]); } } /** * @dev _bulkAddAddressesToAirdropWithAward provides the function of adding addresses * to the airdrop list with a specific number of tokens */ function bulkAddAddressesToAirDropWithAward(address[] _addressesToAdd, uint256 _tokenAward) ifNotPaused public { require(_addressesToAdd.length > 0); require(_tokenAward > 0); for (uint i = 0; i < _addressesToAdd.length; i++) { _addAddressToAirdropWithAward(_addressesToAdd[i], _tokenAward); } } /** * @dev _addAddressToAirdropWithAward provides the function of adding an address to the * airdrop list with a specific number of tokens opposed to the default of * 30 Sparkle * @dev NOTE: _tokenAward will be converted so value only needs to be whole number * Ex: 30 opposed to 30 * (10e7) */ function _addAddressToAirdropWithAward(address _addressToAdd, uint256 _tokenAward) onlyOwner internal { require(_addressToAdd != 0); require(!isAddressInAirdropList(_addressToAdd)); require(_tokenAward > 0); Contribution storage contrib = contributions[_addressToAdd]; contrib.tokenAmount = _tokenAward.mul(10e7); contrib.wasClaimed = false; contrib.isValid = true; } /** * @dev _addAddressToAirdrop provides the function of adding an address to the * airdrop list with the default of 30 sparkle */ function _addAddressToAirDrop(address _addressToAdd) onlyOwner internal { require(_addressToAdd != 0); require(!isAddressInAirdropList(_addressToAdd)); Contribution storage contrib = contributions[_addressToAdd]; contrib.tokenAmount = 30 * 10e7; contrib.wasClaimed = false; contrib.isValid = true; } /** * @dev bulkRemoveAddressesFromAirDrop provides the function of removing airdrop * addresses from the airdrop list */ function bulkRemoveAddressesFromAirDrop(address[] _addressesToRemove) ifNotPaused public { require(_addressesToRemove.length > 0); for (uint i = 0; i < _addressesToRemove.length; i++) { _removeAddressFromAirDrop(_addressesToRemove[i]); } } /** * @dev _removeAddressFromAirDrop provides the function of removing an address from * the airdrop */ function _removeAddressFromAirDrop(address _addressToRemove) onlyOwner internal { require(_addressToRemove != 0); require(isAddressInAirdropList(_addressToRemove)); Contribution storage contrib = contributions[_addressToRemove]; contrib.tokenAmount = 0; contrib.wasClaimed = false; contrib.isValid = false; } function setAirdropAddressWasClaimed(address _addressToChange, bool _newWasClaimedValue) ifNotPaused onlyOwner public { require(_addressToChange != 0); require(isAddressInAirdropList(_addressToChange)); Contribution storage contrib = contributions[ _addressToChange]; require(contrib.isValid); contrib.wasClaimed = _newWasClaimedValue; } /** * @dev claimTokens() provides airdrop winners the function of collecting their tokens */ function claimTokens() ifNotPaused public { Contribution storage contrib = contributions[msg.sender]; require(contrib.isValid, "Address not found in airdrop list"); require(contrib.tokenAmount > 0, "There are currently no tokens to claim."); uint256 tempPendingTokens = contrib.tokenAmount; contrib.tokenAmount = 0; totalTokensClaimed = totalTokensClaimed.add(tempPendingTokens); contrib.wasClaimed = true; ERC20(tokenAddress).transfer(msg.sender, tempPendingTokens); } /** * @dev () is the default payable function. Since this contract should not accept * revert the transaction best as possible. */ function() payable public { revert("ETH not accepted"); } } contract SparkleAirDrop is AirDropWinners { using SafeMath for uint256; address initTokenContractAddress = 0x4b7aD3a56810032782Afce12d7d27122bDb96efF; constructor() AirDropWinners(initTokenContractAddress) public {} }
_removeAddressFromAirDrop provides the function of removing an address from the airdrop/
function _removeAddressFromAirDrop(address _addressToRemove) onlyOwner internal { require(_addressToRemove != 0); require(isAddressInAirdropList(_addressToRemove)); Contribution storage contrib = contributions[_addressToRemove]; contrib.tokenAmount = 0; contrib.wasClaimed = false; contrib.isValid = false; }
986,623
./partial_match/1/0x56a72f85d077a21001823668767bd4556715aAD7/sources/contracts-eth/SmartChef.sol
Deposit staked tokens and collect reward tokens (if any) _amount: amount to withdraw (in rewardToken)/
function deposit(uint256 _amount) external nonReentrant { UserInfo storage user = userInfo[msg.sender]; if (hasUserLimit) { require(_amount.add(user.amount) <= poolLimitPerUser, "User amount above limit"); } _updatePool(); if (user.amount > 0) { uint256 pending = user.amount.mul(accTokenPerShare).div(PRECISION_FACTOR).sub(user.rewardDebt); if (pending > 0) { rewardToken.safeTransfer(address(msg.sender), pending); } } if (_amount > 0) { user.amount = user.amount.add(_amount); stakedToken.safeTransferFrom(address(msg.sender), address(this), _amount); user.depositTime = block.timestamp; } user.rewardDebt = user.amount.mul(accTokenPerShare).div(PRECISION_FACTOR); emit Deposit(msg.sender, _amount); }
16,150,912
./partial_match/1313161554/0x548A76388D5A11C37a34f24be3560eFFf7289267/sources/_contracts/ReaperStrategyCompoundLeverage.sol
Configure variables for the dual reward/
function configureDualReward( bool _isDualRewardActive, address _dualRewardToken, uint8 _dualRewardIndex, address[] calldata _newDualRewardToNativeRoute ) external { _atLeastRole(STRATEGIST); require(_newDualRewardToNativeRoute[0] == _dualRewardToken); require(_newDualRewardToNativeRoute[_newDualRewardToNativeRoute.length - 1] == nativeToken); isDualRewardActive = _isDualRewardActive; dualRewardToken = _dualRewardToken; dualRewardIndex = _dualRewardIndex; delete dualRewardToNativeRoute; dualRewardToNativeRoute = _newDualRewardToNativeRoute; }
16,915,198
// SPDX-License-Identifier: MIT pragma solidity 0.7.6; pragma abicoder v2; import {Address} from "@openzeppelin/contracts/utils/Address.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; import "./interfaces/IConjureFactory.sol"; import "./interfaces/IConjureRouter.sol"; contract OpenOracleFramework { // using Openzeppelin contracts for SafeMath and Address using SafeMath for uint256; using Address for address; // the address of the collateral contract factory address public factoryContract; // address used for pay out address payable public payoutAddress; // number of signers uint256 public signerLength; // addresses of the signers address[] public signers; // threshold which has to be reached uint256 public signerThreshold; // struct to keep the values for each individual round struct feedRoundStruct { uint256 value; uint256 timestamp; } // stores historical values of feeds mapping(uint256 => mapping(uint256 => uint256)) private historicalFeeds; // indicates if sender is a signer mapping(address => bool) private isSigner; // mapping to store the actual submitted values per FeedId, per round number mapping(uint256 => mapping(uint256 => mapping(address => feedRoundStruct))) private feedRoundNumberToStructMapping; // indicates support of feeds mapping(uint256 => uint256) public feedSupport; // indicates if address si subscribed to a feed mapping(address => mapping(uint256 => uint256)) private subscribedTo; struct oracleStruct { string feedName; uint256 feedDecimals; uint256 feedTimeslot; uint256 latestPrice; uint256 latestPriceUpdate; // 0... donation, 1... subscription uint256 revenueMode; uint256 feedCost; } oracleStruct[] private feedList; // indicates if oracle subscription is turned on. 0 indicates no pass uint256 public subscriptionPassPrice; mapping(address => uint256) private hasPass; struct proposalStruct { uint256 uintValue; address addressValue; address proposer; // 0 ... pricePass // 1 ... threshold // 2 ... add signer // 3 ... remove signer // 4 ... payoutAddress // 5 ... revenueMode // 6 ... feedCost uint256 proposalType; uint256 proposalFeedId; uint256 proposalActive; } proposalStruct[] public proposalList; mapping(uint256 => mapping(address => bool)) private hasSignedProposal; event contractSetup(address[] signers, uint256 signerThreshold, address payout); event feedAdded(string name, string description, uint256 decimal, uint256 timeslot, uint256 feedId, uint256 mode, uint256 price); event feedSigned(uint256 feedId, uint256 roundId, uint256 value, uint256 timestamp, address signer); event routerFeeTaken(uint256 value, address sender); event feedSupported(uint256 feedId, uint256 supportvalue); event newProposal(uint256 proposalId, uint256 uintValue, address addressValue, uint256 oracleType, address proposer); event proposalSigned(uint256 proposalId, address signer); event newFee(uint256 value); event newThreshold(uint256 value); event newSigner(address signer); event signerRemoved(address signer); event newPayoutAddress(address payout); event newRevenueMode(uint256 mode, uint256 feed); event newFeedCost(uint256 cost, uint256 feed); event subscriptionPassPriceUpdated(uint256 newPass); // only Signer modifier modifier onlySigner { _onlySigner(); _; } // only Signer view function _onlySigner() private view { require(isSigner[msg.sender], "Only a signer can perform this action"); } constructor() { // Don't allow implementation to be initialized. factoryContract = address(1); } function initialize( address[] memory signers_, uint256 signerThreshold_, address payable payoutAddress_, uint256 subscriptionPassPrice_, address factoryContract_ ) external { require(factoryContract == address(0), "already initialized"); require(factoryContract_ != address(0), "factory can not be null"); require(signerThreshold_ != 0, "Threshold cant be 0"); require(signerThreshold_ <= signers_.length, "Threshold cant be more then signer count"); factoryContract = factoryContract_; signerThreshold = signerThreshold_; signers = signers_; for(uint i=0; i< signers.length; i++) { require(signers[i] != address(0), "Not zero address"); isSigner[signers[i]] = true; } signerLength = signers_.length; payoutAddress = payoutAddress_; subscriptionPassPrice = subscriptionPassPrice_; emit contractSetup(signers_, signerThreshold, payoutAddress); } //---------------------------helper functions--------------------------- /** * @dev implementation of a quicksort algorithm * * @param arr the array to be sorted * @param left the left outer bound element to start the sort * @param right the right outer bound element to stop the sort */ function quickSort(uint[] memory arr, int left, int right) private pure { int i = left; int j = right; if (i == j) return; uint pivot = arr[uint(left + (right - left) / 2)]; while (i <= j) { while (arr[uint(i)] < pivot) i++; while (pivot < arr[uint(j)]) j--; if (i <= j) { (arr[uint(i)], arr[uint(j)]) = (arr[uint(j)], arr[uint(i)]); i++; j--; } } if (left < j) quickSort(arr, left, j); if (i < right) quickSort(arr, i, right); } /** * @dev sort implementation which calls the quickSort function * * @param data the array to be sorted * @return the sorted array */ function sort(uint[] memory data) private pure returns (uint[] memory) { quickSort(data, int(0), int(data.length - 1)); return data; } //---------------------------view functions --------------------------- function getHistoricalFeeds(uint256[] memory feedIDs, uint256[] memory timestamps) external view returns (uint256[] memory) { uint256 feedLen = feedIDs.length; uint256[] memory returnPrices = new uint256[](feedLen); require(feedIDs.length == timestamps.length, "Feeds and Timestamps must match"); for (uint i = 0; i < feedIDs.length; i++) { if (subscriptionPassPrice > 0) { if (hasPass[msg.sender] <= block.timestamp) { if (feedList[feedIDs[i]].revenueMode == 1 && subscribedTo[msg.sender][feedIDs[i]] < block.timestamp) { revert("No subscription to feed"); } } } else { if (feedList[feedIDs[i]].revenueMode == 1 && subscribedTo[msg.sender][feedIDs[i]] < block.timestamp) { revert("No subscription to feed"); } } uint256 roundNumber = timestamps[i] / feedList[feedIDs[i]].feedTimeslot; returnPrices[i] = historicalFeeds[feedIDs[i]][roundNumber]; } return (returnPrices); } /** * @dev getFeeds function lets anyone call the oracle to receive data (maybe pay an optional fee) * * @param feedIDs the array of feedIds */ function getFeeds(uint256[] memory feedIDs) external view returns (uint256[] memory, uint256[] memory, uint256[] memory) { uint256 feedLen = feedIDs.length; uint256[] memory returnPrices = new uint256[](feedLen); uint256[] memory returnTimestamps = new uint256[](feedLen); uint256[] memory returnDecimals = new uint256[](feedLen); for (uint i = 0; i < feedIDs.length; i++) { (returnPrices[i] ,returnTimestamps[i], returnDecimals[i]) = getFeed(feedIDs[i]); } return (returnPrices, returnTimestamps, returnDecimals); } /** * @dev getFeed function lets anyone call the oracle to receive data (maybe pay an optional fee) * * @param feedID the array of feedId */ function getFeed(uint256 feedID) public view returns (uint256, uint256, uint256) { uint256 returnPrice; uint256 returnTimestamp; uint256 returnDecimals; if (subscriptionPassPrice > 0) { if (hasPass[msg.sender] <= block.timestamp) { if (feedList[feedID].revenueMode == 1 && subscribedTo[msg.sender][feedID] < block.timestamp) { revert("No subscription to feed"); } } } else { if (feedList[feedID].revenueMode == 1 && subscribedTo[msg.sender][feedID] < block.timestamp) { revert("No subscription to feed"); } } returnPrice = feedList[feedID].latestPrice; returnTimestamp = feedList[feedID].latestPriceUpdate; returnDecimals = feedList[feedID].feedDecimals; return (returnPrice, returnTimestamp, returnDecimals); } function getFeedLength() external view returns(uint256){ return feedList.length; } function getFeedList(uint256[] memory feedIDs) external view returns(string[] memory, uint256[] memory, uint256[] memory, uint256[] memory, uint256[] memory) { uint256 feedLen = feedIDs.length; string[] memory returnNames = new string[](feedLen); uint256[] memory returnDecimals = new uint256[](feedLen); uint256[] memory returnTimeslot = new uint256[](feedLen); uint256[] memory returnRevenueMode = new uint256[](feedLen); uint256[] memory returnCost = new uint256[](feedLen); for (uint i = 0; i < feedIDs.length; i++) { returnNames[i] = feedList[feedIDs[i]].feedName; returnDecimals[i] = feedList[feedIDs[i]].feedDecimals; returnTimeslot[i] = feedList[feedIDs[i]].feedTimeslot; returnRevenueMode[i] = feedList[feedIDs[i]].revenueMode; returnCost[i] = feedList[feedIDs[i]].feedCost; } return (returnNames, returnDecimals, returnTimeslot, returnRevenueMode, returnCost); } //---------------------------oracle management functions --------------------------- // function to withdraw funds function withdrawFunds() external { if (payoutAddress == address(0)) { for (uint n = 0; n < signers.length; n++){ payable(signers[n]).transfer(address(this).balance/signers.length); } } else { payoutAddress.transfer(address(this).balance); } } function createNewFeeds(string[] memory names, string[] memory descriptions, uint256[] memory decimals, uint256[] memory timeslots, uint256[] memory feedCosts, uint256[] memory revenueModes) onlySigner external { require(names.length == descriptions.length, "Length mismatch"); require(descriptions.length == decimals.length, "Length mismatch"); require(decimals.length == timeslots.length, "Length mismatch"); require(timeslots.length == feedCosts.length, "Length mismatch"); require(feedCosts.length == revenueModes.length, "Length mismatch"); for(uint i = 0; i < names.length; i++) { require(decimals[i] <= 18, "Decimal places too high"); require(timeslots[i] > 0, "Timeslot cannot be 0"); require(revenueModes[i] <= 1, "Wrong revenueMode parameter"); feedList.push(oracleStruct({ feedName: names[i], feedDecimals: decimals[i], feedTimeslot: timeslots[i], latestPrice: 0, latestPriceUpdate: 0, revenueMode: revenueModes[i], feedCost: feedCosts[i] })); emit feedAdded(names[i], descriptions[i], decimals[i], timeslots[i], feedList.length - 1, revenueModes[i], feedCosts[i]); } } /** * @dev submitFeed function lets a signer submit as many feeds as they want to * * @param values the array of values * @param feedIDs the array of feedIds */ function submitFeed(uint256[] memory feedIDs, uint256[] memory values) onlySigner external { require(values.length == feedIDs.length, "Value length and feedID length do not match"); // process feeds for (uint i = 0; i < values.length; i++) { // get current round number for feed uint256 roundNumber = block.timestamp / feedList[feedIDs[i]].feedTimeslot; // check if the signer already pushed an update for the given period if (feedRoundNumberToStructMapping[feedIDs[i]][roundNumber][msg.sender].timestamp != 0) { delete feedRoundNumberToStructMapping[feedIDs[i]][roundNumber][msg.sender]; } // feed - number and push value feedRoundNumberToStructMapping[feedIDs[i]][roundNumber][msg.sender] = feedRoundStruct({ value: values[i], timestamp: block.timestamp }); emit feedSigned(feedIDs[i], roundNumber, values[i], block.timestamp, msg.sender); // check if threshold was met uint256 signedFeedsLen; uint256[] memory prices = new uint256[](signers.length); uint256 k; for (uint j = 0; j < signers.length; j++) { if (feedRoundNumberToStructMapping[feedIDs[i]][roundNumber][signers[j]].timestamp != 0) { signedFeedsLen++; prices[k++] = feedRoundNumberToStructMapping[feedIDs[i]][roundNumber][signers[j]].value; } } // Change the list size of the array in place assembly { mstore(prices, k) } // if threshold is met process price if (signedFeedsLen >= signerThreshold) { uint[] memory sorted = sort(prices); uint returnPrice; // uneven so we can take the middle if (sorted.length % 2 == 1) { uint sizer = (sorted.length + 1) / 2; returnPrice = sorted[sizer-1]; // take average of the 2 most inner numbers } else { uint size1 = (sorted.length) / 2; returnPrice = (sorted[size1-1]+sorted[size1])/2; } // process the struct for storing if (block.timestamp / feedList[feedIDs[i]].feedTimeslot > feedList[feedIDs[i]].latestPriceUpdate / feedList[feedIDs[i]].feedTimeslot) { historicalFeeds[feedIDs[i]][feedList[feedIDs[i]].latestPriceUpdate / feedList[feedIDs[i]].feedTimeslot] = feedList[feedIDs[i]].latestPrice; } feedList[feedIDs[i]].latestPriceUpdate = block.timestamp; feedList[feedIDs[i]].latestPrice = returnPrice; } } } function signProposal(uint256 proposalId) onlySigner external { require(proposalList[proposalId].proposalActive != 0, "Proposal not active"); hasSignedProposal[proposalId][msg.sender] = true; emit proposalSigned(proposalId, msg.sender); uint256 signedProposalLen; for(uint i = 0; i < signers.length; i++) { if (hasSignedProposal[proposalId][signers[i]]) { signedProposalLen++; } } // execute proposal if (signedProposalLen >= signerThreshold) { if (proposalList[proposalId].proposalType == 0) { updatePricePass(proposalList[proposalId].uintValue); } else if (proposalList[proposalId].proposalType == 1) { updateThreshold(proposalList[proposalId].uintValue); } else if (proposalList[proposalId].proposalType == 2) { addSigners(proposalList[proposalId].addressValue); } else if (proposalList[proposalId].proposalType == 3) { removeSigner(proposalList[proposalId].addressValue); } else if (proposalList[proposalId].proposalType == 4) { updatePayoutAddress(proposalList[proposalId].addressValue); } else if (proposalList[proposalId].proposalType == 5) { updateRevenueMode(proposalList[proposalId].uintValue, proposalList[proposalId].proposalFeedId); } else { updateFeedCost(proposalList[proposalId].uintValue, proposalList[proposalId].proposalFeedId); } // lock proposal proposalList[proposalId].proposalActive = 0; } } function createProposal(uint256 uintValue, address addressValue, uint256 proposalType, uint256 feedId) onlySigner external { uint256 proposalArrayLen = proposalList.length; // fee or threshold if (proposalType == 0 || proposalType == 1 || proposalType == 7) { proposalList.push(proposalStruct({ uintValue: uintValue, addressValue: address(0), proposer: msg.sender, proposalType: proposalType, proposalFeedId: 0, proposalActive: 1 })); } else if (proposalType == 5 || proposalType == 6) { proposalList.push(proposalStruct({ uintValue: uintValue, addressValue: address(0), proposer: msg.sender, proposalType: proposalType, proposalFeedId : feedId, proposalActive: 1 })); } else { proposalList.push(proposalStruct({ uintValue: 0, addressValue: addressValue, proposer: msg.sender, proposalType: proposalType, proposalFeedId : 0, proposalActive: 1 })); } hasSignedProposal[proposalArrayLen][msg.sender] = true; emit newProposal(proposalArrayLen, uintValue, addressValue, proposalType, msg.sender); emit proposalSigned(proposalArrayLen, msg.sender); } function updatePricePass(uint256 newPricePass) private { subscriptionPassPrice = newPricePass; emit subscriptionPassPriceUpdated(newPricePass); } function updateRevenueMode(uint256 newRevenueModeValue, uint256 feedId ) private { require(newRevenueModeValue <= 1, "Invalid argument for revenue Mode"); feedList[feedId].revenueMode = newRevenueModeValue; emit newRevenueMode(newRevenueModeValue, feedId); } function updateFeedCost(uint256 feedCost, uint256 feedId) private { require(feedCost > 0, "Feed price cant be 0"); feedList[feedId].feedCost = feedCost; emit newFeedCost(feedCost, feedId); } function updateThreshold(uint256 newThresholdValue) private { require(newThresholdValue != 0, "Threshold cant be 0"); require(newThresholdValue <= signerLength, "Threshold cant be bigger then length of signers"); signerThreshold = newThresholdValue; emit newThreshold(newThresholdValue); } function addSigners(address newSignerValue) private { // check for duplicate signer for (uint i=0; i < signers.length; i++) { if (signers[i] == newSignerValue) { revert("Signer already exists"); } } signers.push(newSignerValue); signerLength++; isSigner[newSignerValue] = true; emit newSigner(newSignerValue); } function updatePayoutAddress(address newPayoutAddressValue) private { payoutAddress = payable(newPayoutAddressValue); emit newPayoutAddress(newPayoutAddressValue); } function removeSigner(address toRemove) internal { require(isSigner[toRemove], "Address to remove has to be a signer"); require(signers.length -1 >= signerThreshold, "Less signers than threshold"); for (uint i = 0; i < signers.length; i++) { if (signers[i] == toRemove) { delete signers[i]; signerLength --; isSigner[toRemove] = false; emit signerRemoved(toRemove); } } } //---------------------------subscription functions--------------------------- function subscribeToFeed(uint256[] memory feedIDs, uint256[] memory durations, address buyer) payable external { require(feedIDs.length == durations.length, "Length mismatch"); uint256 total; for (uint i = 0; i < feedIDs.length; i++) { require(feedList[feedIDs[i]].revenueMode == 1, "Donation mode turned on"); require(durations[i] >= 3600, "Minimum subscription is 1h"); if (subscribedTo[buyer][feedIDs[i]] <=block.timestamp) { subscribedTo[buyer][feedIDs[i]] = block.timestamp.add(durations[i]); } else { subscribedTo[buyer][feedIDs[i]] = subscribedTo[buyer][feedIDs[i]].add(durations[i]); } total += feedList[feedIDs[i]].feedCost * durations[i] / 3600; } // check if enough payment was sent require(msg.value >= total, "Not enough funds sent to cover oracle fees"); // send feeds to router address payable conjureRouter = IConjureFactory(factoryContract).getConjureRouter(); IConjureRouter(conjureRouter).deposit{value:msg.value/50}(); emit routerFeeTaken(msg.value/50, msg.sender); } function buyPass(address buyer, uint256 duration) payable external { require(subscriptionPassPrice != 0, "Subscription Pass turned off"); require(duration >= 3600, "Minimum subscription is 1h"); require(msg.value >= subscriptionPassPrice * duration / 86400, "Not enough payment"); if (hasPass[buyer] <=block.timestamp) { hasPass[buyer] = block.timestamp.add(duration); } else { hasPass[buyer] = hasPass[buyer].add(duration); } address payable conjureRouter = IConjureFactory(factoryContract).getConjureRouter(); IConjureRouter(conjureRouter).deposit{value:msg.value/50}(); emit routerFeeTaken(msg.value/50, msg.sender); } function supportFeeds(uint256[] memory feedIds, uint256[] memory values) payable external { require(feedIds.length == values.length, "Length mismatch"); uint256 total; for (uint i = 0; i < feedIds.length; i++) { require(feedList[feedIds[i]].revenueMode == 0, "Subscription mode turned on"); feedSupport[feedIds[i]] = feedSupport[feedIds[i]].add(values[i]); total += values[i]; emit feedSupported(feedIds[i], values[i]); } require(msg.value >= total, "Msg.value does not meet support values"); address payable conjureRouter = IConjureFactory(factoryContract).getConjureRouter(); IConjureRouter(conjureRouter).deposit{value:total/100}(); emit routerFeeTaken(total/100, msg.sender); } }
implementation of a quicksort algorithm arr the array to be sorted left the left outer bound element to start the sort right the right outer bound element to stop the sort/
function quickSort(uint[] memory arr, int left, int right) private pure { int i = left; int j = right; if (i == j) return; uint pivot = arr[uint(left + (right - left) / 2)]; while (i <= j) { while (arr[uint(i)] < pivot) i++; while (pivot < arr[uint(j)]) j--; if (i <= j) { (arr[uint(i)], arr[uint(j)]) = (arr[uint(j)], arr[uint(i)]); i++; j--; } } if (left < j) quickSort(arr, left, j); if (i < right) quickSort(arr, i, right); }
1,071,876
/** *Submitted for verification at Etherscan.io on 2021-05-17 */ // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; contract OwnerHelper { address public owner; address public manager; event ChangeOwner(address indexed _from, address indexed _to); event ChangeManager(address indexed _from, address indexed _to); modifier onlyOwner { require(msg.sender == owner, "ERROR: Not owner"); _; } modifier onlyManager { require(msg.sender == manager, "ERROR: Not manager"); _; } constructor() { owner = msg.sender; } function transferOwnership(address _to) onlyOwner public { require(_to != owner); require(_to != manager); require(_to != address(0x0)); address from = owner; owner = _to; emit ChangeOwner(from, _to); } function transferManager(address _to) onlyOwner public { require(_to != owner); require(_to != manager); require(_to != address(0x0)); address from = manager; manager = _to; emit ChangeManager(from, _to); } } abstract contract ERC20Interface { event Transfer( address indexed _from, address indexed _to, uint _value); event Approval( address indexed _owner, address indexed _spender, uint _value); function totalSupply() view virtual public returns (uint _supply); function balanceOf( address _who ) virtual public view returns (uint _value); function transfer( address _to, uint _value) virtual public returns (bool _success); function approve( address _spender, uint _value ) virtual public returns (bool _success); function allowance( address _owner, address _spender ) virtual public view returns (uint _allowance); function transferFrom( address _from, address _to, uint _value) virtual public returns (bool _success); } contract TRADY is ERC20Interface, OwnerHelper { string public name; uint public decimals; string public symbol; uint constant private E18 = 1000000000000000000; uint constant private month = 2592000; // Total 1,000,000,000 uint constant public maxTotalSupply = 1000000000 * E18; // Sale 150,000,000 (15%) uint constant public maxSaleSupply = 150000000 * E18; // Marketing 100,000,000 (10%) uint constant public maxMktSupply = 100000000 * E18; // Development 100,000,000 (10%) uint constant public maxDevSupply = 100000000 * E18; // EcoSystem 150,000,000 (15%) uint constant public maxEcoSupply = 150000000 * E18; // Business 100,000,000 (10%) uint constant public maxBusinessSupply = 100000000 * E18; // Team 100,000,000 (10%) uint constant public maxTeamSupply = 100000000 * E18; // Advisors 50,000,000 (5%) uint constant public maxAdvisorSupply = 50000000 * E18; // Reserve 250,000,000 (25%) uint constant public maxReserveSupply = 250000000 * E18; // Lock uint constant public teamVestingSupply = 5000000 * E18; uint constant public teamVestingLockDate = 24 * month; uint constant public teamVestingTime = 20; uint constant public advisorVestingSupply = 2500000 * E18; uint constant public advisorVestingLockDate = 12 * month; uint constant public advisorVestingTime = 20; uint public totalTokenSupply; uint public tokenIssuedSale; uint public tokenIssuedMkt; uint public tokenIssuedDev; uint public tokenIssuedEco; uint public tokenIssuedBusiness; uint public tokenIssuedTeam; uint public tokenIssuedAdv; uint public tokenIssuedRsv; uint public burnTokenSupply; mapping (address => uint) public balances; mapping (address => mapping ( address => uint )) public approvals; mapping (uint => uint) public tmVestingTimer; mapping (uint => uint) public tmVestingBalances; mapping (uint => uint) public advVestingTimer; mapping (uint => uint) public advVestingBalances; bool public tokenLock = true; bool public saleTime = true; uint public endSaleTime = 0; event Issue(address indexed _to, uint _tokens, string _type); event TeamIssue(address indexed _to1, address indexed _to2, uint _tokens); event Burn(address indexed _from, uint _tokens); event TokenUnlock(address indexed _to, uint _tokens); event EndSale(uint _date); constructor() { name = "TRADY"; decimals = 18; symbol = "TRADY"; totalTokenSupply = maxTotalSupply; balances[owner] = totalTokenSupply; tokenIssuedSale = 0; tokenIssuedDev = 0; tokenIssuedEco = 0; tokenIssuedBusiness = 0; tokenIssuedMkt = 0; tokenIssuedRsv = 0; tokenIssuedTeam = 0; tokenIssuedAdv = 0; burnTokenSupply = 0; require(maxTeamSupply == teamVestingSupply * teamVestingTime, "ERROR: MaxTeamSupply"); require(maxAdvisorSupply == advisorVestingSupply * advisorVestingTime, "ERROR: MaxAdvisorSupply"); require(maxTotalSupply == maxSaleSupply + maxDevSupply + maxEcoSupply + maxMktSupply + maxReserveSupply + maxTeamSupply + maxAdvisorSupply + maxBusinessSupply, "ERROR: MaxTotalSupply"); } function totalSupply() view override public returns (uint) { return totalTokenSupply; } function balanceOf(address _who) view override public returns (uint) { return balances[_who]; } function transfer(address _to, uint _value) override public returns (bool) { require(isTransferable() == true); require(balances[msg.sender] >= _value); balances[msg.sender] = balances[msg.sender] - _value; balances[_to] = balances[_to] + _value; emit Transfer(msg.sender, _to, _value); return true; } function approve(address _spender, uint _value) override public returns (bool) { require(isTransferable() == true); require(balances[msg.sender] >= _value); approvals[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } function allowance(address _owner, address _spender) view override public returns (uint) { return approvals[_owner][_spender]; } function transferFrom(address _from, address _to, uint _value) override public returns (bool) { require(isTransferable() == true); require(balances[_from] >= _value); require(approvals[_from][msg.sender] >= _value); approvals[_from][msg.sender] = approvals[_from][msg.sender] - _value; balances[_from] = balances[_from] - _value; balances[_to] = balances[_to] + _value; emit Transfer(_from, _to, _value); return true; } function saleIssue(address _to) onlyOwner public { require(saleTime == true); require(tokenIssuedSale == 0); _transfer(msg.sender, _to, maxSaleSupply); tokenIssuedSale = maxSaleSupply; emit Issue(_to, maxSaleSupply, "Sale"); } function devIssue(address _to) onlyOwner public { require(saleTime == false); require(tokenIssuedDev == 0); _transfer(msg.sender, _to, maxDevSupply); tokenIssuedDev = maxDevSupply; emit Issue(_to, maxDevSupply, "Development"); } function ecoIssue(address _to) onlyOwner public { require(saleTime == false); require(tokenIssuedEco == 0); _transfer(msg.sender, _to, maxEcoSupply); tokenIssuedEco = maxEcoSupply; emit Issue(_to, maxEcoSupply, "Ecosystem"); } function mktIssue(address _to) onlyOwner public { require(saleTime == false); require(tokenIssuedMkt == 0); _transfer(msg.sender, _to, maxMktSupply); tokenIssuedMkt = maxMktSupply; emit Issue(_to, maxMktSupply, "Marketing"); } function bizIssue(address _to) onlyOwner public { require(saleTime == false); require(tokenIssuedBusiness == 0); _transfer(msg.sender, _to, maxBusinessSupply); tokenIssuedBusiness = maxBusinessSupply; emit Issue(_to, maxBusinessSupply, "Business"); } function rsvIssue(address _to) onlyOwner public { require(saleTime == false); require(tokenIssuedRsv == 0); _transfer(msg.sender, _to, maxReserveSupply); tokenIssuedRsv = maxReserveSupply; emit Issue(_to, maxReserveSupply, "Reserve"); } function teamIssue(address _to1, address _to2, uint _time) onlyOwner public { require(saleTime == false, "ERROR: It's sale time"); require(_time < teamVestingTime, "ERROR: Over vesting"); uint nowTime = block.timestamp; require(nowTime > tmVestingTimer[_time], "ERROR: Now locking"); uint tokens = teamVestingSupply; require(tokens == tmVestingBalances[_time]); require(maxTeamSupply >= tokenIssuedTeam + tokens); require(balances[msg.sender] >= tokens); balances[msg.sender] = balances[msg.sender] - tokens; uint half = tokens / 2; balances[_to1] = balances[_to1] + half; balances[_to2] = balances[_to2] + half; tmVestingBalances[_time] = 0; tokenIssuedTeam = tokenIssuedTeam + tokens; emit TeamIssue(_to1, _to2, half); } function advisorIssue(address _to, uint _time) onlyOwner public { require(saleTime == false, "ERROR: It's sale time"); require( _time < advisorVestingTime, "ERROR: Over vesting"); uint nowTime = block.timestamp; require( nowTime > advVestingTimer[_time] ); uint tokens = advisorVestingSupply; require(tokens == advVestingBalances[_time]); require(maxAdvisorSupply >= tokenIssuedAdv + tokens); require(balances[msg.sender] >= tokens); balances[msg.sender] = balances[msg.sender] - tokens; balances[_to] = balances[_to] + tokens; advVestingBalances[_time] = 0; tokenIssuedAdv = tokenIssuedAdv + tokens; emit Issue(_to, tokens, "Advisor"); } function isTransferable() private view returns (bool) { if(tokenLock == false) { return true; } else if(msg.sender == owner) { return true; } return false; } function setTokenUnlock() onlyManager public { require(tokenLock == true); require(saleTime == false); tokenLock = false; } function setTokenLock() onlyManager public { require(tokenLock == false); tokenLock = true; } function endSale() onlyOwner public { require(saleTime == true); require(maxSaleSupply == tokenIssuedSale); saleTime = false; uint nowTime = block.timestamp; endSaleTime = nowTime; for(uint i = 0; i < teamVestingTime; i++) { tmVestingTimer[i] = endSaleTime + teamVestingLockDate + (i * month); tmVestingBalances[i] = teamVestingSupply; } for(uint i = 0; i < advisorVestingTime; i++) { advVestingTimer[i] = endSaleTime + advisorVestingLockDate + (i * month); advVestingBalances[i] = advisorVestingSupply; } emit EndSale(endSaleTime); } function burnToken(uint _value) onlyManager public { uint tokens = _value * E18; require(balances[msg.sender] >= tokens); balances[msg.sender] = balances[msg.sender] - tokens; burnTokenSupply = burnTokenSupply + tokens; totalTokenSupply = totalTokenSupply - tokens; emit Burn(msg.sender, tokens); } function close() onlyOwner public { selfdestruct(payable(msg.sender)); } function _transfer(address _from, address _to, uint _value) internal { require(balances[_from] >= _value); balances[_from] = balances[_from] - _value; balances[_to] = balances[_to] + _value; } }
Total 1,000,000,000 Sale 150,000,000 (15%) Marketing 100,000,000 (10%) Development 100,000,000 (10%) EcoSystem 150,000,000 (15%) Business 100,000,000 (10%) Team 100,000,000 (10%) Advisors 50,000,000 (5%) Reserve 250,000,000 (25%) Lock
{ string public name; uint public decimals; string public symbol; uint constant private E18 = 1000000000000000000; uint constant private month = 2592000; uint constant public maxTotalSupply = 1000000000 * E18; uint constant public maxSaleSupply = 150000000 * E18; uint constant public maxMktSupply = 100000000 * E18; uint constant public maxDevSupply = 100000000 * E18; uint constant public maxEcoSupply = 150000000 * E18; uint constant public maxBusinessSupply = 100000000 * E18; uint constant public maxTeamSupply = 100000000 * E18; uint constant public maxAdvisorSupply = 50000000 * E18; uint constant public maxReserveSupply = 250000000 * E18; uint constant public teamVestingSupply = 5000000 * E18; uint constant public teamVestingLockDate = 24 * month; uint constant public teamVestingTime = 20; uint constant public advisorVestingSupply = 2500000 * E18; uint constant public advisorVestingLockDate = 12 * month; uint constant public advisorVestingTime = 20; uint public totalTokenSupply; uint public tokenIssuedSale; uint public tokenIssuedMkt; uint public tokenIssuedDev; uint public tokenIssuedEco; uint public tokenIssuedBusiness; uint public tokenIssuedTeam; uint public tokenIssuedAdv; uint public tokenIssuedRsv; uint public burnTokenSupply; mapping (address => uint) public balances; mapping (address => mapping ( address => uint )) public approvals; mapping (uint => uint) public tmVestingTimer; mapping (uint => uint) public tmVestingBalances; mapping (uint => uint) public advVestingTimer; mapping (uint => uint) public advVestingBalances; bool public tokenLock = true; bool public saleTime = true; uint public endSaleTime = 0; event Issue(address indexed _to, uint _tokens, string _type); event TeamIssue(address indexed _to1, address indexed _to2, uint _tokens); event Burn(address indexed _from, uint _tokens); event TokenUnlock(address indexed _to, uint _tokens); event EndSale(uint _date); constructor() { name = "TRADY"; decimals = 18; symbol = "TRADY"; totalTokenSupply = maxTotalSupply; balances[owner] = totalTokenSupply; tokenIssuedSale = 0; tokenIssuedDev = 0; tokenIssuedEco = 0; tokenIssuedBusiness = 0; tokenIssuedMkt = 0; tokenIssuedRsv = 0; tokenIssuedTeam = 0; tokenIssuedAdv = 0; burnTokenSupply = 0; require(maxTeamSupply == teamVestingSupply * teamVestingTime, "ERROR: MaxTeamSupply"); require(maxAdvisorSupply == advisorVestingSupply * advisorVestingTime, "ERROR: MaxAdvisorSupply"); require(maxTotalSupply == maxSaleSupply + maxDevSupply + maxEcoSupply + maxMktSupply + maxReserveSupply + maxTeamSupply + maxAdvisorSupply + maxBusinessSupply, "ERROR: MaxTotalSupply"); } function totalSupply() view override public returns (uint) { return totalTokenSupply; } function balanceOf(address _who) view override public returns (uint) { return balances[_who]; } function transfer(address _to, uint _value) override public returns (bool) { require(isTransferable() == true); require(balances[msg.sender] >= _value); balances[msg.sender] = balances[msg.sender] - _value; balances[_to] = balances[_to] + _value; emit Transfer(msg.sender, _to, _value); return true; } function approve(address _spender, uint _value) override public returns (bool) { require(isTransferable() == true); require(balances[msg.sender] >= _value); approvals[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } function allowance(address _owner, address _spender) view override public returns (uint) { return approvals[_owner][_spender]; } function transferFrom(address _from, address _to, uint _value) override public returns (bool) { require(isTransferable() == true); require(balances[_from] >= _value); require(approvals[_from][msg.sender] >= _value); approvals[_from][msg.sender] = approvals[_from][msg.sender] - _value; balances[_from] = balances[_from] - _value; balances[_to] = balances[_to] + _value; emit Transfer(_from, _to, _value); return true; } function saleIssue(address _to) onlyOwner public { require(saleTime == true); require(tokenIssuedSale == 0); _transfer(msg.sender, _to, maxSaleSupply); tokenIssuedSale = maxSaleSupply; emit Issue(_to, maxSaleSupply, "Sale"); } function devIssue(address _to) onlyOwner public { require(saleTime == false); require(tokenIssuedDev == 0); _transfer(msg.sender, _to, maxDevSupply); tokenIssuedDev = maxDevSupply; emit Issue(_to, maxDevSupply, "Development"); } function ecoIssue(address _to) onlyOwner public { require(saleTime == false); require(tokenIssuedEco == 0); _transfer(msg.sender, _to, maxEcoSupply); tokenIssuedEco = maxEcoSupply; emit Issue(_to, maxEcoSupply, "Ecosystem"); } function mktIssue(address _to) onlyOwner public { require(saleTime == false); require(tokenIssuedMkt == 0); _transfer(msg.sender, _to, maxMktSupply); tokenIssuedMkt = maxMktSupply; emit Issue(_to, maxMktSupply, "Marketing"); } function bizIssue(address _to) onlyOwner public { require(saleTime == false); require(tokenIssuedBusiness == 0); _transfer(msg.sender, _to, maxBusinessSupply); tokenIssuedBusiness = maxBusinessSupply; emit Issue(_to, maxBusinessSupply, "Business"); } function rsvIssue(address _to) onlyOwner public { require(saleTime == false); require(tokenIssuedRsv == 0); _transfer(msg.sender, _to, maxReserveSupply); tokenIssuedRsv = maxReserveSupply; emit Issue(_to, maxReserveSupply, "Reserve"); } function teamIssue(address _to1, address _to2, uint _time) onlyOwner public { require(saleTime == false, "ERROR: It's sale time"); require(_time < teamVestingTime, "ERROR: Over vesting"); uint nowTime = block.timestamp; require(nowTime > tmVestingTimer[_time], "ERROR: Now locking"); uint tokens = teamVestingSupply; require(tokens == tmVestingBalances[_time]); require(maxTeamSupply >= tokenIssuedTeam + tokens); require(balances[msg.sender] >= tokens); balances[msg.sender] = balances[msg.sender] - tokens; uint half = tokens / 2; balances[_to1] = balances[_to1] + half; balances[_to2] = balances[_to2] + half; tmVestingBalances[_time] = 0; tokenIssuedTeam = tokenIssuedTeam + tokens; emit TeamIssue(_to1, _to2, half); } function advisorIssue(address _to, uint _time) onlyOwner public { require(saleTime == false, "ERROR: It's sale time"); require( _time < advisorVestingTime, "ERROR: Over vesting"); uint nowTime = block.timestamp; require( nowTime > advVestingTimer[_time] ); uint tokens = advisorVestingSupply; require(tokens == advVestingBalances[_time]); require(maxAdvisorSupply >= tokenIssuedAdv + tokens); require(balances[msg.sender] >= tokens); balances[msg.sender] = balances[msg.sender] - tokens; balances[_to] = balances[_to] + tokens; advVestingBalances[_time] = 0; tokenIssuedAdv = tokenIssuedAdv + tokens; emit Issue(_to, tokens, "Advisor"); } function isTransferable() private view returns (bool) { if(tokenLock == false) { return true; } else if(msg.sender == owner) { return true; } return false; } function isTransferable() private view returns (bool) { if(tokenLock == false) { return true; } else if(msg.sender == owner) { return true; } return false; } function isTransferable() private view returns (bool) { if(tokenLock == false) { return true; } else if(msg.sender == owner) { return true; } return false; } function setTokenUnlock() onlyManager public { require(tokenLock == true); require(saleTime == false); tokenLock = false; } function setTokenLock() onlyManager public { require(tokenLock == false); tokenLock = true; } function endSale() onlyOwner public { require(saleTime == true); require(maxSaleSupply == tokenIssuedSale); saleTime = false; uint nowTime = block.timestamp; endSaleTime = nowTime; for(uint i = 0; i < teamVestingTime; i++) { tmVestingTimer[i] = endSaleTime + teamVestingLockDate + (i * month); tmVestingBalances[i] = teamVestingSupply; } for(uint i = 0; i < advisorVestingTime; i++) { advVestingTimer[i] = endSaleTime + advisorVestingLockDate + (i * month); advVestingBalances[i] = advisorVestingSupply; } emit EndSale(endSaleTime); } function endSale() onlyOwner public { require(saleTime == true); require(maxSaleSupply == tokenIssuedSale); saleTime = false; uint nowTime = block.timestamp; endSaleTime = nowTime; for(uint i = 0; i < teamVestingTime; i++) { tmVestingTimer[i] = endSaleTime + teamVestingLockDate + (i * month); tmVestingBalances[i] = teamVestingSupply; } for(uint i = 0; i < advisorVestingTime; i++) { advVestingTimer[i] = endSaleTime + advisorVestingLockDate + (i * month); advVestingBalances[i] = advisorVestingSupply; } emit EndSale(endSaleTime); } function endSale() onlyOwner public { require(saleTime == true); require(maxSaleSupply == tokenIssuedSale); saleTime = false; uint nowTime = block.timestamp; endSaleTime = nowTime; for(uint i = 0; i < teamVestingTime; i++) { tmVestingTimer[i] = endSaleTime + teamVestingLockDate + (i * month); tmVestingBalances[i] = teamVestingSupply; } for(uint i = 0; i < advisorVestingTime; i++) { advVestingTimer[i] = endSaleTime + advisorVestingLockDate + (i * month); advVestingBalances[i] = advisorVestingSupply; } emit EndSale(endSaleTime); } function burnToken(uint _value) onlyManager public { uint tokens = _value * E18; require(balances[msg.sender] >= tokens); balances[msg.sender] = balances[msg.sender] - tokens; burnTokenSupply = burnTokenSupply + tokens; totalTokenSupply = totalTokenSupply - tokens; emit Burn(msg.sender, tokens); } function close() onlyOwner public { selfdestruct(payable(msg.sender)); } function _transfer(address _from, address _to, uint _value) internal { require(balances[_from] >= _value); balances[_from] = balances[_from] - _value; balances[_to] = balances[_to] + _value; } }
6,339,602
./partial_match/1/0x005112454E4fAA73EDf28493BCb4c8De1E4276e1/sources/ERC721X.sol
See {IEnumerableERC721-tokenOfOwnerByIndex}./
function tokenOfOwnerByIndex(address owner, uint256 index) override external view returns (uint256) { require(owner != address(0), "ERC721X: balance query for the zero address"); uint256 count = 0; uint256 i = 1; for(; _exists(i) && count < index + 1; i++) { if(_owners[i] == owner) { count++; if(_owners[i + 1] == address(0) && count < index + 1 && _exists(i + 1)) { count++; i++; } } } if(count == index + 1) return i - 1; else revert("ERC721X: owner index out of bounds"); }
16,100,535
pragma solidity ^0.4.19; // <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&#39;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&#39;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; // Convert from seconds to ledger timer ticks _delay *= 10; bytes memory nbytes = new bytes(1); nbytes[0] = byte(_nbytes); bytes memory unonce = new bytes(32); bytes memory sessionKeyHash = new bytes(32); bytes32 sessionKeyHash_bytes32 = oraclize_randomDS_getSessionPubKeyHash(); assembly { mstore(unonce, 0x20) mstore(add(unonce, 0x20), xor(blockhash(sub(number, 1)), xor(coinbase, timestamp))) mstore(sessionKeyHash, 0x20) mstore(add(sessionKeyHash, 0x20), sessionKeyHash_bytes32) } bytes memory delay = new bytes(32); assembly { mstore(add(delay, 0x20), _delay) } bytes memory delay_bytes8 = new bytes(8); copyBytes(delay, 24, 8, delay_bytes8, 0); bytes[4] memory args = [unonce, nbytes, sessionKeyHash, delay]; bytes32 queryId = oraclize_query("random", args, _customGasLimit); bytes memory delay_bytes8_left = new bytes(8); assembly { let x := mload(add(delay_bytes8, 0x20)) mstore8(add(delay_bytes8_left, 0x27), div(x, 0x100000000000000000000000000000000000000000000000000000000000000)) mstore8(add(delay_bytes8_left, 0x26), div(x, 0x1000000000000000000000000000000000000000000000000000000000000)) mstore8(add(delay_bytes8_left, 0x25), div(x, 0x10000000000000000000000000000000000000000000000000000000000)) mstore8(add(delay_bytes8_left, 0x24), div(x, 0x100000000000000000000000000000000000000000000000000000000)) mstore8(add(delay_bytes8_left, 0x23), div(x, 0x1000000000000000000000000000000000000000000000000000000)) mstore8(add(delay_bytes8_left, 0x22), div(x, 0x10000000000000000000000000000000000000000000000000000)) mstore8(add(delay_bytes8_left, 0x21), div(x, 0x100000000000000000000000000000000000000000000000000)) mstore8(add(delay_bytes8_left, 0x20), div(x, 0x1000000000000000000000000000000000000000000000000)) } oraclize_randomDS_setCommitment(queryId, sha3(delay_bytes8_left, args[1], sha256(args[0]), args[2])); return queryId; } function oraclize_randomDS_setCommitment(bytes32 queryId, bytes32 commitment) internal { oraclize_randomDS_args[queryId] = commitment; } mapping(bytes32=>bytes32) oraclize_randomDS_args; mapping(bytes32=>bool) oraclize_randomDS_sessionKeysHashVerified; function verifySig(bytes32 tosignh, bytes dersig, bytes pubkey) internal returns (bool){ bool sigok; address signer; bytes32 sigr; bytes32 sigs; bytes memory sigr_ = new bytes(32); uint offset = 4+(uint(dersig[3]) - 0x20); sigr_ = copyBytes(dersig, offset, 32, sigr_, 0); bytes memory sigs_ = new bytes(32); offset += 32 + 2; sigs_ = copyBytes(dersig, offset+(uint(dersig[offset-1]) - 0x20), 32, sigs_, 0); assembly { sigr := mload(add(sigr_, 32)) sigs := mload(add(sigs_, 32)) } (sigok, signer) = safer_ecrecover(tosignh, 27, sigr, sigs); if (address(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 &#39;LP\x01&#39; (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 &#39;LP\x01&#39; (Ledger Proof version 1) if ((_proof[0] != "L")||(_proof[1] != "P")||(_proof[2] != 1)) return 1; bool proofVerified = oraclize_randomDS_proofVerify__main(_proof, _queryId, bytes(_result), oraclize_getNetworkName()); if (proofVerified == false) return 2; return 0; } function matchBytes32Prefix(bytes32 content, bytes prefix, uint n_random_bytes) internal returns (bool){ bool match_ = true; if (prefix.length != n_random_bytes) throw; for (uint256 i=0; i< n_random_bytes; i++) { if (content[i] != prefix[i]) match_ = false; } return match_; } function oraclize_randomDS_proofVerify__main(bytes proof, bytes32 queryId, bytes result, string context_name) internal returns (bool){ // Step 2: the unique keyhash has to match with the sha256 of (context name + queryId) uint ledgerProofLength = 3+65+(uint(proof[3+65+1])+2)+32; bytes memory keyhash = new bytes(32); copyBytes(proof, ledgerProofLength, 32, keyhash, 0); if (!(sha3(keyhash) == sha3(sha256(context_name, queryId)))) return false; bytes memory sig1 = new bytes(uint(proof[ledgerProofLength+(32+8+1+32)+1])+2); copyBytes(proof, ledgerProofLength+(32+8+1+32), sig1.length, sig1, 0); // Step 3: we assume sig1 is valid (it will be verified during step 5) and we verify if &#39;result&#39; is the prefix of sha256(sig1) if (!matchBytes32Prefix(sha256(sig1), result, uint(proof[ledgerProofLength+32+8]))) 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); if (!verifySig(sha256(tosign1), sig1, sessionPubkey)) return false; // verify if sessionPubkeyHash was verified already, if not.. let&#39;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&#39;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&#39;t update the offset so // Solidity will reuse it. The memory used here is only needed for // this context. // FIXME: inline assembly can&#39;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 // &#39;mload&#39; will pad with zeroes if we overread. // There is no &#39;mload8&#39; to do this, but that would be nicer. v := byte(0, mload(add(sig, 96))) // Alternative solution: // &#39;byte&#39; is not working due to the Solidity parser, so lets // use the second best option, &#39;and&#39; // 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 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 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; } } /* * Copyright (c) 2018, DEurovision.eu */ contract Eurovision is usingOraclize { // Use SafeMath library to avoid overflows/underflows using SafeMath for uint256; // List of participating countries. NONE is used for an initial state. enum Countries { NONE, Albania, Armenia, Australia, Austria, Azerbaijan, Belarus, Belgium, Bulgaria, Croatia, Cyprus, Czech_Republic, Denmark, Estonia, Macedonia, Finland, France, Georgia, Germany, Greece, Hungary, Iceland, Ireland, Israel, Italy, Latvia, Lithuania, Malta, Moldova, Montenegro, Norway, Poland, Portugal, Romania, Russia, San_Marino, Serbia, Slovenia, Spain, Sweden, Switzerland, The_Netherlands, Ukraine, United_Kingdom } // Number of participating countries. uint256 public constant NUMBER_OF_COUNTRIES = uint256(Countries.United_Kingdom); // Country that won the contest. uint256 public countryWinnerID; // Staker address -> country ID -> amount. mapping (address => mapping (uint256 => uint256)) public stakes; // Staker address -> total amount of wei received from that address. mapping (address => uint256) public weiReceived; // Reward/Refund claimed? mapping (address => bool) public claimed; // Statistics of each country (stakes amount + number of stakers). Statistics[44] public countryStats; // Country statistics (how many stakers and how much is placed on a specific country). struct Statistics { uint256 amount; uint256 numberOfStakers; } // Deadline to stake is the start of the 1st semi-final: May 8th, 7 pm GMT. uint256 public constant STAKE_DEADLINE = 1525806000; // Winner should be announced until: May 18th, 7 pm GMT. uint256 public constant ANNOUNCE_WINNER_DEADLINE = 1526670000; // Rewards/Refunds should be claimed until: June 8th, 7 pm GMT. uint256 public constant CLAIM_DEADLINE = 1528484400; // If the winner was queried at least 3 times < 24 hours before the deadline but // no result received from the callback, allow announcing it manually. uint256 private attemptsToQueryInLast24Hours = 0; uint256 private MIN_NUMBER_OF_ATTEMPTS_TO_WAIT = 3; // Time when the last query was sent to Oraclize. uint256 private lastQueryTime; // Wait the callback for at least 30 mins. uint256 private constant MIN_CALLBACK_WAIT_TIME = 30 minutes; // Only 0.002 Ether or more is allowed. uint256 public constant MIN_STAKE = 0.002 ether; // The sum of all amounts of stakes. uint256 public totalPot = 0; // If the winner is confirmed, participants can start claiming their winnings. bool public winnerConfirmed = false; // Participants can retrieve their Ether back once refunds are enabled. bool public refundsEnabled = false; // Owner of the contract. address public owner; // 4% fee for the development. uint256 public constant DEVELOPER_FEE_PERCENTAGE = 4; // Total number of collected fees. uint256 public collectedFees = 0; // Constant representing 100%. uint256 private constant PERCENTAGE_100 = 100; // Events to notify frontend. event Stake(address indexed staker, uint256 indexed countryID, uint256 amount); event WinnerAnnounced(uint256 winnerID); event WinnerConfirmed(uint256 winnerID); event Claim(address indexed staker, uint256 stakeAmount, uint256 claimAmount); event RefundsEnabled(); event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); // Initialize fields in the constructor. function Eurovision() public { owner = msg.sender; countryWinnerID = uint256(Countries.NONE); } // Stake on a specific country. function stake(uint256 countryID) external validCountry(countryID) payable { require(now <= STAKE_DEADLINE); require(!refundsEnabled); require(msg.value >= MIN_STAKE); address staker = msg.sender; uint256 weiAmount = msg.value; uint256 fee = weiAmount.mul(DEVELOPER_FEE_PERCENTAGE) / PERCENTAGE_100; uint256 actualStake = weiAmount.sub(fee); weiReceived[staker] = weiReceived[staker].add(actualStake); stakes[staker][countryID] = stakes[staker][countryID].add(actualStake); countryStats[countryID].amount = countryStats[countryID].amount.add(actualStake); if (stakes[staker][countryID] == actualStake) { countryStats[countryID].numberOfStakers++; } collectedFees = collectedFees.add(fee); totalPot = totalPot.add(actualStake); Stake(staker, countryID, actualStake); } // Get back all your Ether (fees are also refunded). function refund() external { require(canRefund()); require(!claimed[msg.sender]); address refunder = msg.sender; uint256 refundAmount = weiReceived[refunder].mul(PERCENTAGE_100) / (PERCENTAGE_100.sub(DEVELOPER_FEE_PERCENTAGE)) ; claimed[refunder] = true; if (collectedFees > 0) { collectedFees = 0; } refunder.transfer(refundAmount); Claim(refunder, refundAmount, refundAmount); } // Claim your reward if you guessed the winner correctly. function claimWinnings() external { require(winnerConfirmed); require(now <= CLAIM_DEADLINE); require(!refundsEnabled); require(!claimed[msg.sender]); address claimer = msg.sender; uint256 myStakesOnWinner = myStakesOnCountry(countryWinnerID); uint256 totalStakesOnWinner = countryStats[countryWinnerID].amount; uint256 reward = myStakesOnWinner.mul(totalPot) / totalStakesOnWinner; claimed[claimer] = true; claimer.transfer(reward); Claim(claimer, myStakesOnWinner, reward); } // Send the query to Oraclize to retrieve the winner ID. function queryWinner(string apiKey) external possibleToAnnounceWinner onlyOwner { require(now > STAKE_DEADLINE); if (now.add(24 hours) >= ANNOUNCE_WINNER_DEADLINE && countryWinnerID == uint256(Countries.NONE)) { attemptsToQueryInLast24Hours.add(1); lastQueryTime = now; } oraclize_query("computation", ["QmQ9PvNoKSRpbGduSbvyBHwVZQ97Pw7JYEnbTiLfcKHapE", apiKey]); } // Oraclize callback. Returns result from the computation datasource. function __callback(bytes32 myid, string result) { require(msg.sender == oraclize_cbAddress()); uint256 winnerID = parseInt(result); require(winnerID > 0); require(winnerID <= NUMBER_OF_COUNTRIES); countryWinnerID = winnerID; WinnerAnnounced(countryWinnerID); } // If the Oraclize didn&#39;t return the result in 30 mins during the last 24 hours, owner can announce the winner manually. function announceWinnerManually(uint256 winnerID) external validCountry(winnerID) possibleToAnnounceWinner onlyOwner { require(attemptsToQueryInLast24Hours >= MIN_NUMBER_OF_ATTEMPTS_TO_WAIT); require(now >= lastQueryTime.add(MIN_CALLBACK_WAIT_TIME)); countryWinnerID = winnerID; WinnerAnnounced(countryWinnerID); } // 2-step verification that the right winner was announced (minimize the probability of error). function confirmWinner() external possibleToAnnounceWinner onlyOwner { require(countryWinnerID != uint256(Countries.NONE)); winnerConfirmed = true; WinnerConfirmed(countryWinnerID); } // Fallback function. Owner can send some Ether to the contract. Ether is needed to call the Oraclize. function () external payable onlyOwner { } // Get total stakes amount and number of stakers for specific country. function getCountryStats(uint256 countryID) external view validCountry(countryID) returns(uint256 amount, uint256 numberOfStakers) { return (countryStats[countryID].amount, countryStats[countryID].numberOfStakers); } // Get my amount of stakes for a specific country. function myStakesOnCountry(uint256 countryID) public view validCountry(countryID) returns(uint256 myStake) { return stakes[msg.sender][countryID]; } // Get my total amount of Ether staked on all countries. function myTotalStakeAmount() public view returns(uint256 myStake) { return weiReceived[msg.sender]; } // Indicated if an address has already claimed the winnings/refunds. function alreadyClaimed() public view returns(bool hasClaimed) { return claimed[msg.sender]; } // Check if refunds are possible. function canRefund() public view returns(bool) { bool winnerNotAnnouncedInTime = (now > ANNOUNCE_WINNER_DEADLINE) && !winnerConfirmed; bool notExpired = (now <= CLAIM_DEADLINE); return (refundsEnabled || winnerNotAnnouncedInTime) && notExpired; } // In case of an emergency situation or other unexpected event an owner of the contract can explicitly enable refunds. function enableRefunds() external onlyOwner { require(!refundsEnabled); require(!winnerConfirmed); refundsEnabled = true; RefundsEnabled(); } // Only when all the winnings are supposed to be claimed, owner can receive the fees. function claimFees() external onlyOwner { require(now > CLAIM_DEADLINE); require(collectedFees > 0); uint256 amount = collectedFees; collectedFees = 0; owner.transfer(amount); } // Transfer ownership of the contract to the new address. function transferOwnership(address newOwner) external onlyOwner { require(newOwner != address(0)); owner = newOwner; OwnershipTransferred(owner, newOwner); } // Free the memory when the contest ends and all the winnings/refunds are supposed to be claimed. function kill() external onlyOwner { require(now > CLAIM_DEADLINE); selfdestruct(owner); } // ID belongs to the list. modifier validCountry(uint256 countryID) { require(countryID > 0); require(countryID <= NUMBER_OF_COUNTRIES); _; } // Valid state to announce/confirm the winner. modifier possibleToAnnounceWinner() { require(now <= ANNOUNCE_WINNER_DEADLINE); require(!refundsEnabled); require(!winnerConfirmed); _; } // Only executable by an owner of the contract. modifier onlyOwner() { require(msg.sender == owner); _; } }
If the Oraclize didn&39;t return the result in 30 mins during the last 24 hours, owner can announce the winner manually.
function announceWinnerManually(uint256 winnerID) external validCountry(winnerID) possibleToAnnounceWinner onlyOwner { require(attemptsToQueryInLast24Hours >= MIN_NUMBER_OF_ATTEMPTS_TO_WAIT); require(now >= lastQueryTime.add(MIN_CALLBACK_WAIT_TIME)); countryWinnerID = winnerID; WinnerAnnounced(countryWinnerID); }
7,835,884
./partial_match/1/0x91d42CB9883AFCaef2ed79637291dFe30Dea431f/sources/contracts/pendle/PendleStakingBaseUpg.sol
pause Pendle staking, restricting certain operations/
function pause() external nonReentrant onlyOwner { _pause(); }
4,002,263
./full_match/1/0x5ab0A812327aD959dE664AEC8408Ef8c6ABe7184/sources/contracts/SpokePool.sol
Verifies inclusion proof of leaf in root, sends relayer their refund, and sends to HubPool any rebalance transfers. Check integrity of leaf structure: Check that inclusionProof proves that relayerRefundLeaf is contained within the relayer refund root. Note: This should revert if the relayerRefundRoot is uninitialized. Verify the leafId in the leaf has not yet been claimed. Set leaf as claimed in bitmap. This is passed by reference to the storage rootBundle. Send each relayer refund address the associated refundAmount for the L2 token address. Note: Even if the L2 token is not enabled on this spoke pool, we should still refund relayers. OK because we assume refund array length won't be > types(uint256).max. Based on the stress test results in /test/gas-analytics/SpokePool.RelayerRefundLeaf.ts, the UMIP should limit the refund count in valid proposals to be ~800 so any RelayerRefundLeaves with > 800 refunds should not make it to this stage. If leaf's amountToReturn is positive, then send L2 --> L1 message to bridge tokens back via chain-specific bridging method.
function _executeRelayerRefundLeaf( uint32 rootBundleId, SpokePoolInterface.RelayerRefundLeaf memory relayerRefundLeaf, bytes32[] memory proof ) internal { require(relayerRefundLeaf.chainId == chainId(), "Invalid chainId"); require(relayerRefundLeaf.refundAddresses.length == relayerRefundLeaf.refundAmounts.length, "invalid leaf"); RootBundle storage rootBundle = rootBundles[rootBundleId]; require(MerkleLib.verifyRelayerRefund(rootBundle.relayerRefundRoot, relayerRefundLeaf, proof), "Bad Proof"); require(!MerkleLib.isClaimed(rootBundle.claimedBitmap, relayerRefundLeaf.leafId), "Already claimed"); MerkleLib.setClaimed(rootBundle.claimedBitmap, relayerRefundLeaf.leafId); uint256 length = relayerRefundLeaf.refundAmounts.length; for (uint256 i = 0; i < length; ) { uint256 amount = relayerRefundLeaf.refundAmounts[i]; if (amount > 0) IERC20Upgradeable(relayerRefundLeaf.l2TokenAddress).safeTransfer( relayerRefundLeaf.refundAddresses[i], amount ); unchecked { ++i; } } if (relayerRefundLeaf.amountToReturn > 0) { _bridgeTokensToHubPool(relayerRefundLeaf); emit TokensBridged( relayerRefundLeaf.amountToReturn, relayerRefundLeaf.chainId, relayerRefundLeaf.leafId, relayerRefundLeaf.l2TokenAddress, msg.sender ); } emit ExecutedRelayerRefundRoot( relayerRefundLeaf.amountToReturn, relayerRefundLeaf.chainId, relayerRefundLeaf.refundAmounts, rootBundleId, relayerRefundLeaf.leafId, relayerRefundLeaf.l2TokenAddress, relayerRefundLeaf.refundAddresses, msg.sender ); }
4,977,117
pragma solidity ^0.4.11; contract Owned { address public owner; function Owned() { owner = msg.sender; } modifier onlyOwner() { require(msg.sender == owner); _; } function setOwner(address _newOwner) onlyOwner { if(_newOwner == 0x0)revert(); owner = _newOwner; } } /** * @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&#39;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; } function toUINT112(uint256 a) internal constant returns(uint112) { assert(uint112(a) == a); return uint112(a); } function toUINT120(uint256 a) internal constant returns(uint120) { assert(uint120(a) == a); return uint120(a); } function toUINT128(uint256 a) internal constant returns(uint128) { assert(uint128(a) == a); return uint128(a); } } // Abstract contract for the full ERC 20 Token standard // https://github.com/ethereum/EIPs/issues/20 contract Token { function totalSupply() public returns (uint256 supply); function transfer(address _to, uint256 _value) returns (bool success); function transferFrom(address _from, address _to, uint256 _value) returns (bool success); function approve(address _spender, uint256 _value) returns (bool success); function allowance(address _owner, address _spender) constant returns (uint256 remaining); function burn( uint256 _value) public returns (bool success); event Transfer(address indexed _from, address indexed _to, uint256 _value); event Approval(address indexed _owner, address indexed _spender, uint256 _value); event Burn(address indexed from, uint256 value); } contract HealthyCoins is Token, Owned { using SafeMath for uint256; uint public _totalSupply; string public name; //The Token&#39;s name uint8 public constant decimals = 4; //Number of decimals of the smallest unit string public symbol; //The Token&#39;s symbol uint256 public mintCount; uint256 public deleteToken; uint256 public soldToken; mapping (address => uint256) public balanceOf; // Owner of account approves the transfer of an amount to another account mapping(address => mapping(address => uint256)) allowed; // Constructor function HealthyCoins(string coinName,string coinSymbol,uint initialSupply) { _totalSupply = initialSupply *10**uint256(decimals); // Update total supply balanceOf[msg.sender] = _totalSupply; name = coinName; // Set the name for display purposes symbol =coinSymbol; } function totalSupply() public returns (uint256 totalSupply) { return _totalSupply; } // Send back ether sent to me function () { revert(); } // Transfer the balance from owner&#39;s account to another account function transfer(address _to, uint256 _amount) returns (bool success) { // according to AssetToken&#39;s total supply, never overflow here if (balanceOf[msg.sender] >= _amount && _amount > 0) { balanceOf[msg.sender] -= uint112(_amount); balanceOf[_to] = _amount.add(balanceOf[_to]).toUINT112(); soldToken = _amount.add(soldToken).toUINT112(); Transfer(msg.sender, _to, _amount); return true; } else { return false; } } function transferFrom( address _from, address _to, uint256 _amount ) returns (bool success) { // according to AssetToken&#39;s total supply, never overflow here if (balanceOf[_from] >= _amount && allowed[_from][msg.sender] >= _amount && _amount > 0) { balanceOf[_from] = balanceOf[_from].sub(_amount).toUINT112(); allowed[_from][msg.sender] -= _amount; balanceOf[_to] = _amount.add(balanceOf[_to]).toUINT112(); Transfer(_from, _to, _amount); return true; } else { return false; } } function approve(address _spender, uint256 _amount) returns (bool success) { allowed[msg.sender][_spender] = _amount; Approval(msg.sender, _spender, _amount); return true; } function allowance(address _owner, address _spender) constant returns (uint256 remaining) { return allowed[_owner][_spender]; } //Mint tokens and assign to some one function mint(address _owner, uint256 _amount) onlyOwner{ balanceOf[_owner] = _amount.add(balanceOf[_owner]).toUINT112(); mintCount = _amount.add(mintCount).toUINT112(); _totalSupply = _totalSupply.add(_amount).toUINT112(); } //Burn tokens from owner account function burn(uint256 _count) public returns (bool success) { balanceOf[msg.sender] -=uint112( _count); deleteToken = _count.add(deleteToken).toUINT112(); _totalSupply = _totalSupply.sub(_count).toUINT112(); Burn(msg.sender, _count); return true; } }
according to AssetToken&39;s total supply, never overflow here
function transferFrom( address _from, address _to, uint256 _amount ) returns (bool success) { if (balanceOf[_from] >= _amount && allowed[_from][msg.sender] >= _amount && _amount > 0) { balanceOf[_from] = balanceOf[_from].sub(_amount).toUINT112(); allowed[_from][msg.sender] -= _amount; balanceOf[_to] = _amount.add(balanceOf[_to]).toUINT112(); Transfer(_from, _to, _amount); return true; return false; } }
7,956,645
./full_match/1/0x467439207d53530505E5Eb40eDD6deBBAfF3e063/sources/Users/mario/Development/MarsGenesis/Contract/contracts/MarsGenesisCore.sol
Mints a new land The method includes a signature that was provided by the MarsGenesis backend, to ensure data integrity isPromo Flag that indicates if the land is created for a promotion (callable only by contract admins) topLeftLatLong The lat long pair of the top left corner of the rectangle that defines a land bottomRightLatLong The lat long pair of the bottom right corner of the rectangle that defines a land signature The signature provided by the backend to ensure data integrity ipfsHash The hash on the IPFS of this land card metadataURI The URI of the IPFS where the metadata of this land card is recorded cardId The ID of this card on the MarsGenesis backend, for internal use (dont confuse it with tokenId, the one in the backend) return uint, the tokenId of the minted land
function mintLand(bool isPromo, string memory topLeftLatLong, string memory bottomRightLatLong, bytes memory signature, string memory ipfsHash, string memory metadataURI, uint cardId, address promoOwner) external payable returns (uint) { if (isPromo == true) { require(hasRole(DEFAULT_ADMIN_ROLE, _msgSender()), "INVALID_ROLE"); require(hashes[ipfsHash] != 1, "HASH_EXISTS"); require(_promoTokenIdTracker.current() < MAX_PROMO_LANDS, "LIMIT_REACHED"); _promoTokenIdTracker.increment(); require(msg.value >= _currentPrice(), "PAYMENT_TOO_LOW"); require(hashes[ipfsHash] != 1, "HASH_EXISTS"); bytes32 hash = keccak256(abi.encodePacked(topLeftLatLong, bottomRightLatLong, address(this), cardId)); address signer = _recoverSigner(hash, signature); require(signer == _deployerAddress, "INVALID_SIGNATURE"); } address landOwner; if (isPromo == true) { landOwner = promoOwner; landOwner = _msgSender(); } uint newTokenId = _mintLand(landOwner, topLeftLatLong, bottomRightLatLong, ipfsHash, metadataURI, cardId); return newTokenId; }
2,992,069
// SPDX-License-Identifier: ECLv2 /** * @title TokenHook (THK). * @author Currently ANONYMOUS. * @notice You may use this code under ECLv2. * @dev For new token deployment: * 1- Install MetaMask (Chrome/Firefox extension). * 2- Connect to Rinkeby (or other private/public chains). * 3- Run RemixIDE and set environment as "Injected Web3". * 4- Copy and past this code in RemixIDE. * 5- Deploy the token contract (ERC20). * @dev The code is compatible with version 0.5.x of Solidity complier. * Version 0.5.11 has been selected for compatibility with the following auditing tools: * 1- EY Review Tool by Ernst & Young Global Limited. * 2- SmartCheck by SmartDec. * 3- Securify by ChainSecurity. * 4- ContractGuard by GuardStrike. * 5- MythX by ConsenSys. * 6- Slither Analyzer by Crytic. * 7- Odin by Sooho. */ pragma solidity 0.5.11; /** * @title ERC20 Interface * @author Fabian Vogelsteller, Vitalik Buterin * @dev https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20.md */ interface IERC20 { /// Transfers tokens and fires the Transfer event. function transfer(address to, uint256 tokens) external returns (bool); /// Allows to withdraw from your account multiple times, up to the approved tokens. function approve(address spender, uint256 tokens) external returns (bool); /// Transfers approved tokens and fires the Transfer event function transferFrom(address from, address to, uint256 tokens) external returns (bool); /// Returns the total token supply function totalSupply() external view returns (uint256); /// Returns token balance of an account function balanceOf(address account) external view returns (uint256); /// Returns the allowed tokens to withdraw from an account function allowance(address account, address spender) external view returns (uint256); /// Events event Transfer(address indexed from, address indexed to, uint256 tokens); event Approval(address indexed tokenOwner, address indexed spender, uint256 tokens); } /** * @title Wrappers over Solidity's arithmetic operations with added overflow checks. * @author OpenZeppelin * @dev https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/math/SafeMath.sol * * 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; } } /** * @title ERC20 Token contract * @dev When verify the code in EtherScan and if you used the default initialSupply, * set this value as "Constructor Arguments": * 0000000000000000000000000000000000000000000000000000000000000000 * @dev The token will be created with 18 decimal places, * so it takes a balance of 10 ** 18 token units to equal one token. * In other word, if we want to have x initial tokens, we need to pass in, * x * 10 ** 18 to the constructor. */ contract ERC20 is IERC20 { using SafeMath for uint256; /// Attach SafeMath functions with uint256 to mitigate integer overflow string public constant name = "TokenHook"; /// Token name string public constant symbol = "THK"; /// Token symbol uint8 public constant decimals = 18; /// Divisible to 18 decimal places address payable private owner; /// Token owner uint256 public exchangeRate = 100; /// 100 tokens per 1ETH, default exchange rate uint256 private initialSupply = 200e6; /// Controls economy of the token by limiting initial supply to 200M bool private locked; /// Mutex variable to mitigate re-entrancy attack bool private paused; /// Boolean variable to support Fail-Safe mode //uint256 private contractBalance = 0; /// Can be used for integrity check mapping(address => mapping (address => uint256)) private allowances; /// Allowed token to transfer by spenders mapping(address => mapping (address => uint256)) private transferred; /// Transferred tokens by spenders mapping(address => uint256) public balances; /// Balance of token holders /** * @dev Token constructor that runs only once upon contract creation. The final code of the contract is deployed to the blockchain, * after the constructor has run. */ constructor(uint256 supply) public { owner = msg.sender; /// Owner of the token initialSupply = (supply != 0) ? supply : /// Initialize token supply initialSupply.mul(10 ** uint256(decimals)); /// With 18 zero balances[owner] = initialSupply; /// Owner gets all initial tokens emit Transfer(address(0), owner, initialSupply); /// Logs transferred tokens to the owner } /** * @dev Fallback function to accept ETH. It is compatible with 2300 gas for receiving funds via send or transfer methods. */ function() external payable{ //require(msg.data.length == 0, "Only plain Ether"); /// Checks for only calls without data //contractBalance = contractBalance.add(msg.value); /// Adjusting contract balance emit Received(msg.sender, msg.value); /// Logs received ETH } /** * @dev Transfers `tokens` amount of tokens to address `to`, and fires Transfer event. Transferring zero tokens is also allowed. */ function transfer(address to, uint256 tokens) external notPaused validAddress(to) noReentrancy returns (bool success) { require(balances[msg.sender] >= tokens, "Not enough balance"); /// Checks the sender's balance require(balances[to].add(tokens) >= balances[to], "Overflow error"); /// Checks overflows balances[msg.sender] = balances[msg.sender].sub(tokens); /// Subtracts from the sender balances[to] = balances[to].add(tokens); /// Adds to the recipient emit Transfer(msg.sender, to, tokens); /// Logs transferred tokens return true; } /** * @dev Special type of Transfer that makes it possible to give permission to another address for spending tokens on your behalf. * It sends `tokens` from address `from` to address `to`. The `transferFrom` method is used for a withdraw work-flow, allowing * contracts to send tokens on your behalf, for example to deposit to a contract address and/or to charge fees in sub-currencies. * The function call fails unless the `from` account has deliberately authorized the sender of the message via `approve` function. */ function transferFrom(address from, address to, uint256 tokens) external notPaused validAddress(to) noReentrancy returns (bool success) { require(balances[from] >= tokens, "Not enough tokens"); /// Checks the sender's balance require(tokens <= ( /// Prevent token transfer more than allowed (allowances[from][msg.sender] > transferred[from][msg.sender]) ? allowances[from][msg.sender].sub(transferred[from][msg.sender]) : 0) , "Transfer more than allowed"); balances[from] = balances[from].sub(tokens); /// Decreases balance of approver balances[to] = balances[to].add(tokens); /// Increases balance of spender transferred[from][msg.sender] = transferred[from][msg.sender].add(tokens); /// Tracks transferred tokens emit Transfer(from, to, tokens); /// Logs transferred tokens return true; } /** * @dev It approves another address to spend tokens on your behalf. It allows `spender` to withdraw from your account, multiple times, * up to the `tokens` amount. If this function is called again, it overwrites the current allowance with `tokens`. */ function approve(address spender, uint256 tokens) external notPaused validAddress(spender) noReentrancy returns (bool success) { require(spender != msg.sender, "Approver is spender"); /// Spender cannot approve himself require(balances[msg.sender] >= tokens, "Not enough balance"); /// Checks the approver's balance allowances[msg.sender][spender] = tokens; /// Sets allowance of the spender emit Approval(msg.sender, spender, tokens); /// Logs approved tokens return true; } /** * @dev Implements another way of approving tokens by increasing current approval. It is not defined in the standard. * https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/token/ERC20/ERC20.sol */ function increaseAllowance(address spender, uint256 addedTokens) external notPaused validAddress(spender) noReentrancy returns (bool success) { require(balances[msg.sender] >= addedTokens, "Not enough token"); /// Checks the approver's balance allowances[msg.sender][spender] = allowances[msg.sender][spender].add(addedTokens); /// Adds allowance of the spender emit Approval(msg.sender, spender, addedTokens); /// Logs approved tokens return true; } /** * @dev Implements another way of approving tokens by decreasing current approval. It is not defined in the standard. * https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/token/ERC20/ERC20.sol */ function decreaseAllowance(address spender, uint256 subtractedTokens) external notPaused validAddress(spender) noReentrancy returns (bool success) { require(allowances[msg.sender][spender] >= subtractedTokens, "Not enough token"); /// Checks the spenders's allowance allowances[msg.sender][spender] = allowances[msg.sender][spender].sub(subtractedTokens);/// Adds allowance of the spender emit Approval(msg.sender, spender, subtractedTokens); /// Logs approved tokens return true; } /** * @dev Supports selling tokens to the contract. It uses msg.sender.call.value() mrthod to be compatible with EIP-1884. * In addition to CEI, Mutex (noReentrancy modifier is also used to mitigate cross-function re-entrancy attack (along with same-function re-entrancy). */ function sell(uint256 tokens) external notPaused noReentrancy returns(bool success) { require(tokens > 0, "No token to sell"); /// Selling zero token is not allowed require(balances[msg.sender] >= tokens, "Not enough token"); /// Checks the seller's balance uint256 _wei = tokens.div(exchangeRate); /// Calculates equivalent of tokens in Wei require(address(this).balance >= _wei, "Not enough wei"); /// Checks the contract's ETH balance //require(contractBalance >= _wei, "Not enough wei"); /// Contract does not have enough Wei /// Using Checks-Effects-Interactions (CEI) pattern to mitigate re-entrancy attack balances[msg.sender] = balances[msg.sender].sub(tokens); /// Decreases tokens of seller balances[owner] = balances[owner].add(tokens); /// Increases tokens of owner //contractBalance = contractBalance.sub(_wei); /// Adjusts contract balance emit Sell(msg.sender, tokens, address(this), _wei, owner); /// Logs sell event (success, ) = msg.sender.call.value(_wei)(""); /// Transfers Wei to the seller require(success, "Ether transfer failed"); /// Checks successful transfer } /** * @dev Supports buying token by transferring Ether */ function buy() external payable notPaused noReentrancy returns(bool success){ require(msg.sender != owner, "Called by the Owner"); /// The owner cannot be seller/buyer uint256 _tokens = msg.value.mul(exchangeRate); /// Calculates token equivalents require(balances[owner] >= _tokens, "Not enough tokens"); /// Checks owner's balance balances[msg.sender] = balances[msg.sender].add(_tokens); /// Increases token balance of buyer balances[owner] = balances[owner].sub(_tokens); /// Decreases token balance of owner //contractBalance = contractBalance.add(msg.value); /// Adjustes contract balance emit Buy(msg.sender, msg.value, owner, _tokens); /// Logs Buy event return true; } /** * @dev Withdraw Ether from the contract and send it to the address that is specified by the owner. It can be called only by the owner. */ function withdraw(uint256 amount) external onlyOwner returns(bool success){ require(address(this).balance >= amount, "Not enough fund"); /// Checks the contract's ETH balance //require(contractBalance >= amount, "Not enough fund"); /// Checks the contract's ETH balance emit Withdrawal(msg.sender, address(this), amount); /// Logs withdrawal event (success, ) = msg.sender.call.value(amount)(""); /// Transfers amount (EIP-1884 compatible) require(success, "Ether transfer failed"); /// Checks successful transfer } /** * @dev Returns balance of the Contract * function getContractBalance() public view onlyOwner returns(uint256, uint256){ return (address(this).balance, contractBalance); } /** * @dev Checks for unexpected received Ether (forced to the contract without using payable functions) * function unexpectedEther() public view onlyOwner returns(bool){ return (contractBalance != address(this).balance); } */ /** /* @dev Creates new tokens and assigns them to the owner, increases the total supply as well. */ function mint(uint256 newTokens) external onlyOwner { initialSupply = initialSupply.add(newTokens); /// Increases token supply balances[owner] = balances[owner].add(newTokens); /// Increases balance of the owner emit Mint(msg.sender, newTokens); /// Logs Mint event } /** * @dev Burns tokens from the owner, decreases the total supply as well. */ function burn(uint256 tokens) external onlyOwner { require(balances[owner] >= tokens, "Not enough tokens"); /// Checks owner's balance balances[owner] = balances[owner].sub(tokens); /// Decreases balance of the owner initialSupply = initialSupply.sub(tokens); /// Decreases token supply emit Burn(msg.sender, tokens); /// Logs Burn event } /** * @dev Sets new exchange rate. It can be called only by the owner. */ function setExchangeRate(uint256 newRate) external onlyOwner returns(bool success) { uint256 _currentRate = exchangeRate; exchangeRate = newRate; /// Sets new exchange rate emit Change(_currentRate, exchangeRate); /// Logs Change event return true; } /** * @dev Changes owner of the contract */ function changeOwner(address payable newOwner) external onlyOwner validAddress(newOwner) { address _current = owner; owner = newOwner; emit ChangeOwner(_current, owner); } /** * @dev Pause the contract as result of self-checks (off-chain computations). */ function pause() external onlyOwner { paused = true; emit Pause(msg.sender, paused); } /** * @dev Unpause the contract after self-checks. */ function unpause() external onlyOwner { paused = false; emit Pause(msg.sender, paused); } /** * @dev Returns the total token supply. */ function totalSupply() external view returns (uint256 tokens) { return initialSupply; /// Total supply of the token. } /** * @dev Returns the account balance of another account with address `tokenHolder`. */ function balanceOf(address tokenHolder) external view returns (uint256 tokens) { return balances[tokenHolder]; /// Balance of token holder. } /** * @dev Returns the amount of tokens approved by the owner that can be transferred to the spender's account. */ function allowance(address tokenHolder, address spender) external view notPaused returns (uint256 tokens) { uint256 _transferred = transferred[tokenHolder][spender]; /// Already transferred tokens by `spender`. return allowances[tokenHolder][spender].sub(_transferred); /// Remained tokens to transfer by `spender`. } /** * @dev Returns the amount of transferred tokens by spender's account. */ function transfers(address tokenHolder, address spender) external view notPaused returns (uint256 tokens) { return transferred[tokenHolder][spender]; /// Transfers by `spender` (approved by `tokenHolder`). } /** * @dev Checks whether the caller is the owner. */ modifier onlyOwner() { require(msg.sender == owner, "Not the owner"); _; } /** * @dev Checks validity of the address. */ modifier validAddress(address addr){ require(addr != address(0x0), "Zero address"); require(addr != address(this), "Contract address"); _; } /** * @author https://solidity.readthedocs.io/en/latest/contracts.html#function-modifiers * @dev Mutex modifier to mitigate Re-entrancy Attack. Operation will succeed if and only if the locking thread is the one that already holds the lock. */ modifier noReentrancy() { require(!locked, "Reentrant call"); locked = true; _; locked = false; } /** * @dev Modifier to support Fail-Safe Mode. In case, it disables most of the toekn features, hands off control to the owner. */ modifier notPaused() { require(!paused, "Fail-Safe mode"); _; } /// Events event Buy(address indexed _buyer, uint256 _wei, address indexed _owner, uint256 _tokens); event Sell(address indexed _seller, uint256 _tokens, address indexed _contract, uint256 _wei, address indexed _owner); event Received(address indexed _sender, uint256 _wei); event Withdrawal(address indexed _by, address indexed _contract, uint256 _wei); event Change(uint256 _current, uint256 _new); event ChangeOwner(address indexed _current, address indexed _new); event Pause(address indexed _owner, bool _state); event Mint(address indexed _owner, uint256 _tokens); event Burn(address indexed _owner, uint256 _tokens); }
Transfers `tokens` amount of tokens to address `to`, and fires Transfer event. Transferring zero tokens is also allowed./
function transfer(address to, uint256 tokens) external notPaused validAddress(to) noReentrancy returns (bool success) { return true; }
6,253,481
./full_match/43114/0x21499643B1Dd73168807eb1eDfa0b43b50b8F30F/sources/cache/solpp-generated-contracts/StakingV1.sol
Validates unstaking period _unstakingPeriod specified unstaking period
function _assertProperUnstakingPeriod(uint256 _unstakingPeriod) private view { require( _unstakingPeriod >= minUnstakingPeriod && _unstakingPeriod <= maxUnstakingPeriod, "Invalid unstaking period" ); }
4,625,002
./full_match/80001/0x20f4B1793bb81FFa357E1705AD954BdC232Edc00/sources/project_/contracts/interfaces/IERC1633.sol
EIP-1633: Re-Fungible ERC721Token Standard (RFT) https://eips.ethereum.org/EIPS/eip-1633
interface IERC1633 /* is ERC20, ERC165 */ { function parentToken() external view returns(address _parentToken); function parentTokenId() external view returns(uint256 _parentTokenId); pragma solidity >=0.7.0 <0.9.0; }
5,590,380
pragma solidity ^0.4.23; /** * @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; } } 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); } contract Ownable { address public owner; event OwnershipRenounced(address indexed previousOwner); event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ constructor() public { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Allows the current owner to 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; } /** * @dev Allows the current owner to relinquish control of the contract. */ function renounceOwnership() public onlyOwner { emit OwnershipRenounced(owner); owner = address(0); } } /** * @title Standard ERC20 token * * @dev Implementation of the basic standard token. * @dev https://github.com/ethereum/EIPs/issues/20 * @dev Based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol */ contract StandardToken is ERC20, BasicToken { mapping (address => mapping (address => uint256)) internal allowed; /** * @dev Transfer tokens from one address to another * @param _from address The address which you want to send tokens from * @param _to address The address which you want to transfer to * @param _value uint256 the amount of tokens to be transferred */ function transferFrom(address _from, address _to, uint256 _value) public returns (bool) { require(_to != address(0)); require(_value <= balances[_from]); require(_value <= allowed[_from][msg.sender]); balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); emit Transfer(_from, _to, _value); return true; } /** * @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender. * * Beware that changing an allowance with this method brings the risk that someone may use both the old * and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this * race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * @param _spender The address which will spend the funds. * @param _value The amount of tokens to be spent. */ function approve(address _spender, uint256 _value) public returns (bool) { allowed[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } /** * @dev Function to check the amount of tokens that an owner allowed to a spender. * @param _owner address The address which owns the funds. * @param _spender address The address which will spend the funds. * @return A uint256 specifying the amount of tokens still available for the spender. */ function allowance(address _owner, address _spender) public view returns (uint256) { return allowed[_owner][_spender]; } /** * @dev Increase the amount of tokens that an owner allowed to a spender. * * approve should be called when allowed[_spender] == 0. To increment * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param _spender The address which will spend the funds. * @param _addedValue The amount of tokens to increase the allowance by. */ function increaseApproval(address _spender, uint _addedValue) public returns (bool) { allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue); emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } /** * @dev Decrease the amount of tokens that an owner allowed to a spender. * * approve should be called when allowed[_spender] == 0. To decrement * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param _spender The address which will spend the funds. * @param _subtractedValue The amount of tokens to decrease the allowance by. */ function decreaseApproval(address _spender, uint _subtractedValue) public returns (bool) { uint oldValue = allowed[msg.sender][_spender]; if (_subtractedValue > oldValue) { allowed[msg.sender][_spender] = 0; } else { allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue); } emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } } /** * @title Mintable token * @dev Simple ERC20 Token example, with mintable token creation * @dev Issue: * https://github.com/OpenZeppelin/openzeppelin-solidity/issues/120 * Based on code by TokenMarketNet: https://github.com/TokenMarketNet/ico/blob/master/contracts/MintableToken.sol */ contract MintableToken is StandardToken, Ownable { event Mint(address indexed to, uint256 amount); event MintFinished(); bool public mintingFinished = false; modifier canMint() { require(!mintingFinished); _; } modifier hasMintPermission() { require(msg.sender == owner); _; } /** * @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) hasMintPermission canMint public returns (bool) { totalSupply_ = totalSupply_.add(_amount); balances[_to] = balances[_to].add(_amount); emit Mint(_to, _amount); emit Transfer(address(0), _to, _amount); return true; } /** * @dev Function to stop minting new tokens. * @return True if the operation was successful. */ function finishMinting() onlyOwner canMint public returns (bool) { mintingFinished = true; emit MintFinished(); return true; } } contract InspiriumToken is MintableToken { string public name = "INSPIRIUM"; string public symbol = "INSPIRIUM"; uint8 public decimals = 0; }
Function to check the amount of tokens that an owner allowed to a spender. _owner address The address which owns the funds. _spender address The address which will spend the funds. return A uint256 specifying the amount of tokens still available for the spender./
function allowance(address _owner, address _spender) public view returns (uint256) { return allowed[_owner][_spender]; }
1,258,676
pragma solidity 0.5.8; /// @title S Curve Reward provider /// @notice Provides the appropriate block author rewards /// based on points of a discrete, inverse S curve contract SCurveProvider { /// Required length of the discrete S curve uint256 public constant REQUIRED_CURVE_LENGTH = 120; /// Discrete points of the curve uint256[] public sCurve; /// Discrete step size uint256 public blockStepSize; /// End of the reward period (both block- and community reward) /// expressed in block number uint256 public rewardPeriodEnd; constructor() public { _initCurve(); // This check is for protecting against some tampering // for chainspec deployment require(sCurve.length == REQUIRED_CURVE_LENGTH, "Reward curve is not the required length"); } /// @notice Returns the block reward amount based on the block number /// and points of the S curve /// @param _currentBlock The block number to calculate the reward to /// @return The block reward amount in wei function getBlockReward(uint256 _currentBlock) public view returns (uint256) { if (_checkRewardPeriodEnded(_currentBlock)) { return 0; } return sCurve[_currentBlock / blockStepSize]; } /// @notice Checks whether the reward period is over or not (block and community) /// @return True if the reward period has ended, false otherwise function checkRewardPeriodEnded() public view returns (bool) { return _checkRewardPeriodEnded(block.number); } /// @notice Checks whether the block reward period is over or not /// @param _currentBlock The block number to check on /// @return True if the block reward period has ended, false otherwise function _checkRewardPeriodEnded(uint256 _currentBlock) internal view returns (bool) { return (_currentBlock >= rewardPeriodEnd); } // solhint-disable function-max-lines /// @dev Inits the S curve. Values are hardcoded, /// everyhting is calculated beforehand function _initCurve() private { sCurve = [ uint256(304418979390926464), 304418979390926464, 304418979390926464, 304418979390926464, 304418979390926464, 304418979390926464, 304418979390926464, 304369560376526464, 304221303333326464, 303974208261326464, 303628275160526464, 303183504030926464, 302639894872526464, 301997447685326464, 301256162469326464, 300416039224526464, 299477077950926464, 298439278648526464, 297302641317326464, 296067165957326464, 294732852568526464, 293299701150926464, 291767711704526464, 290136884229326464, 288407218725326464, 286578715192526464, 284651373630926464, 282625194040526464, 280500176421326464, 278276320773326464, 275953627096526464, 273532095390926464, 271011725656526464, 268392517893326464, 265674472101326464, 262857588280526464, 259941866430926464, 256927306552526464, 253813908645326464, 250601672709326464, 247290598744526464, 243880686750926464, 240371936728526464, 236764348677326464, 233057922597326464, 229252658488526464, 225348556350926464, 221345616184526464, 217243837989326464, 213043221765326464, 208743767512526464, 204345475230926464, 199848344920526464, 195252376581326464, 190557570213326464, 185763925816526464, 180871443390926464, 175880122936526464, 170789964453326464, 165600967941326464, 160117606656000000, 154824830213760000, 149621007997440000, 144506140007040000, 139480226242560000, 134543266704000000, 129695261391360000, 124936210304640000, 120266113443840000, 115684970808960000, 111192782400000000, 106789548216960000, 102475268259840000, 98249942528640000, 94113571023360000, 90066153744000000, 86107690690560000, 82238181863040000, 78457627261440000, 74766026885760000, 71163380736000000, 67649688812160000, 64224951114240000, 60889167642240000, 57642338396160000, 54484463376000000, 51415542581760000, 48435576013440000, 45544563671040000, 42742505554560000, 40029401664000000, 37405251999360000, 34870056560640000, 32423815347840000, 30066528360960000, 27798195600000000, 25618817064960000, 23528392755840000, 21526922672640000, 19614406815360000, 17790845184000000, 16056237778560000, 14410584599040000, 12853885645440000, 11386140917760000, 10007350416000000, 8717514140160000, 7516632090240000, 6404704266240000, 5381730668160000, 4447711296000000, 3602646149760000, 2846535229440000, 2179378535040000, 1601176066560000, 1111927824000000, 711633807360000, 400294016640000, 177908451840000, 44477112960000 ]; // roughly 1 month with a 5 sec step size blockStepSize = 525600; //roughly 10 years with a 5 sec step size rewardPeriodEnd = blockStepSize * REQUIRED_CURVE_LENGTH; } // solhint-enable function-max-lines }
Checks whether the block reward period is over or not _currentBlock The block number to check on return True if the block reward period has ended, false otherwise
function _checkRewardPeriodEnded(uint256 _currentBlock) internal view returns (bool) { return (_currentBlock >= rewardPeriodEnd); }
6,355,995
// SPDX-License-Identifier: MIT pragma solidity 0.8.7; // Part: OpenZeppelin/[email protected]/Address /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); (bool success, bytes memory returndata) = target.delegatecall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // Part: OpenZeppelin/[email protected]/Context /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } // Part: OpenZeppelin/[email protected]/IERC165 /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // Part: OpenZeppelin/[email protected]/IERC721Receiver /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ interface IERC721Receiver { /** * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom} * by `operator` from `from`, this function is called. * * It must return its Solidity selector to confirm the token transfer. * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted. * * The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`. */ function onERC721Received( address operator, address from, uint256 tokenId, bytes calldata data ) external returns (bytes4); } // Part: OpenZeppelin/[email protected]/Strings /** * @dev String operations. */ library Strings { bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef"; /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0x00"; } uint256 temp = value; uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return toHexString(value, length); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = _HEX_SYMBOLS[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } } // Part: OpenZeppelin/[email protected]/ERC165 /** * @dev Implementation of the {IERC165} interface. * * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check * for the additional interface id that will be supported. For example: * * ```solidity * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId); * } * ``` * * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation. */ abstract contract ERC165 is IERC165 { /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165).interfaceId; } } // Part: OpenZeppelin/[email protected]/IERC721 /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721 is IERC165 { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes calldata data ) external; } // Part: OpenZeppelin/[email protected]/Ownable /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() { _setOwner(_msgSender()); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { _setOwner(address(0)); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); _setOwner(newOwner); } function _setOwner(address newOwner) private { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } } // Part: OpenZeppelin/[email protected]/IERC721Enumerable /** * @title ERC-721 Non-Fungible Token Standard, optional enumeration extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Enumerable is IERC721 { /** * @dev Returns the total amount of tokens stored by the contract. */ function totalSupply() external view returns (uint256); /** * @dev Returns a token ID owned by `owner` at a given `index` of its token list. * Use along with {balanceOf} to enumerate all of ``owner``'s tokens. */ function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 tokenId); /** * @dev Returns a token ID at a given `index` of all the tokens stored by the contract. * Use along with {totalSupply} to enumerate all tokens. */ function tokenByIndex(uint256 index) external view returns (uint256); } // Part: OpenZeppelin/[email protected]/IERC721Metadata /** * @title ERC-721 Non-Fungible Token Standard, optional metadata extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Metadata is IERC721 { /** * @dev Returns the token collection name. */ function name() external view returns (string memory); /** * @dev Returns the token collection symbol. */ function symbol() external view returns (string memory); /** * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token. */ function tokenURI(uint256 tokenId) external view returns (string memory); } // Part: OpenZeppelin/[email protected]/ERC721 /** * @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including * the Metadata extension, but not including the Enumerable extension, which is available separately as * {ERC721Enumerable}. */ contract ERC721 is Context, ERC165, IERC721, IERC721Metadata { using Address for address; using Strings for uint256; // Token name string private _name; // Token symbol string private _symbol; // Mapping from token ID to owner address mapping(uint256 => address) private _owners; // Mapping owner address to token count mapping(address => uint256) private _balances; // Mapping from token ID to approved address mapping(uint256 => address) private _tokenApprovals; // Mapping from owner to operator approvals mapping(address => mapping(address => bool)) private _operatorApprovals; /** * @dev Initializes the contract by setting a `name` and a `symbol` to the token collection. */ constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { return interfaceId == type(IERC721).interfaceId || interfaceId == type(IERC721Metadata).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) public view virtual override returns (uint256) { require(owner != address(0), "ERC721: balance query for the zero address"); return _balances[owner]; } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view virtual override returns (address) { address owner = _owners[tokenId]; require(owner != address(0), "ERC721: owner query for nonexistent token"); return owner; } /** * @dev See {IERC721Metadata-name}. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev See {IERC721Metadata-symbol}. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); string memory baseURI = _baseURI(); return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : ""; } /** * @dev Base URI for computing {tokenURI}. If set, the resulting URI for each * token will be the concatenation of the `baseURI` and the `tokenId`. Empty * by default, can be overriden in child contracts. */ function _baseURI() internal view virtual returns (string memory) { return ""; } /** * @dev See {IERC721-approve}. */ function approve(address to, uint256 tokenId) public virtual override { address owner = ERC721.ownerOf(tokenId); require(to != owner, "ERC721: approval to current owner"); require( _msgSender() == owner || isApprovedForAll(owner, _msgSender()), "ERC721: approve caller is not owner nor approved for all" ); _approve(to, tokenId); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view virtual override returns (address) { require(_exists(tokenId), "ERC721: approved query for nonexistent token"); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { require(operator != _msgSender(), "ERC721: approve to caller"); _operatorApprovals[_msgSender()][operator] = approved; emit ApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC721-isApprovedForAll}. */ function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev See {IERC721-transferFrom}. */ function transferFrom( address from, address to, uint256 tokenId ) public virtual override { //solhint-disable-next-line max-line-length require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _transfer(from, to, tokenId); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId ) public virtual override { safeTransferFrom(from, to, tokenId, ""); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory _data ) public virtual override { require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _safeTransfer(from, to, tokenId, _data); } /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * `_data` is additional data, it has no specified format and it is sent in call to `to`. * * This internal function is equivalent to {safeTransferFrom}, and can be used to e.g. * implement alternative mechanisms to perform token transfer, such as signature-based. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeTransfer( address from, address to, uint256 tokenId, bytes memory _data ) internal virtual { _transfer(from, to, tokenId); require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); } /** * @dev Returns whether `tokenId` exists. * * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}. * * Tokens start existing when they are minted (`_mint`), * and stop existing when they are burned (`_burn`). */ function _exists(uint256 tokenId) internal view virtual returns (bool) { return _owners[tokenId] != address(0); } /** * @dev Returns whether `spender` is allowed to manage `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) { require(_exists(tokenId), "ERC721: operator query for nonexistent token"); address owner = ERC721.ownerOf(tokenId); return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender)); } /** * @dev Safely mints `tokenId` and transfers it to `to`. * * Requirements: * * - `tokenId` must not exist. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeMint(address to, uint256 tokenId) internal virtual { _safeMint(to, tokenId, ""); } /** * @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is * forwarded in {IERC721Receiver-onERC721Received} to contract recipients. */ function _safeMint( address to, uint256 tokenId, bytes memory _data ) internal virtual { _mint(to, tokenId); require( _checkOnERC721Received(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer" ); } /** * @dev Mints `tokenId` and transfers it to `to`. * * WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible * * Requirements: * * - `tokenId` must not exist. * - `to` cannot be the zero address. * * Emits a {Transfer} event. */ function _mint(address to, uint256 tokenId) internal virtual { require(to != address(0), "ERC721: mint to the zero address"); require(!_exists(tokenId), "ERC721: token already minted"); _beforeTokenTransfer(address(0), to, tokenId); _balances[to] += 1; _owners[tokenId] = to; emit Transfer(address(0), to, tokenId); } /** * @dev Destroys `tokenId`. * The approval is cleared when the token is burned. * * Requirements: * * - `tokenId` must exist. * * Emits a {Transfer} event. */ function _burn(uint256 tokenId) internal virtual { address owner = ERC721.ownerOf(tokenId); _beforeTokenTransfer(owner, address(0), tokenId); // Clear approvals _approve(address(0), tokenId); _balances[owner] -= 1; delete _owners[tokenId]; emit Transfer(owner, address(0), tokenId); } /** * @dev Transfers `tokenId` from `from` to `to`. * As opposed to {transferFrom}, this imposes no restrictions on msg.sender. * * Requirements: * * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * * Emits a {Transfer} event. */ function _transfer( address from, address to, uint256 tokenId ) internal virtual { require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own"); require(to != address(0), "ERC721: transfer to the zero address"); _beforeTokenTransfer(from, to, tokenId); // Clear approvals from the previous owner _approve(address(0), tokenId); _balances[from] -= 1; _balances[to] += 1; _owners[tokenId] = to; emit Transfer(from, to, tokenId); } /** * @dev Approve `to` to operate on `tokenId` * * Emits a {Approval} event. */ function _approve(address to, uint256 tokenId) internal virtual { _tokenApprovals[tokenId] = to; emit Approval(ERC721.ownerOf(tokenId), to, tokenId); } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address. * The call is not executed if the target address is not a contract. * * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function _checkOnERC721Received( address from, address to, uint256 tokenId, bytes memory _data ) private returns (bool) { if (to.isContract()) { try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) { return retval == IERC721Receiver.onERC721Received.selector; } catch (bytes memory reason) { if (reason.length == 0) { revert("ERC721: transfer to non ERC721Receiver implementer"); } else { assembly { revert(add(32, reason), mload(reason)) } } } } else { return true; } } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual {} } // Part: OpenZeppelin/[email protected]/ERC721Enumerable /** * @dev This implements an optional extension of {ERC721} defined in the EIP that adds * enumerability of all the token ids in the contract as well as all token ids owned by each * account. */ abstract contract ERC721Enumerable is ERC721, IERC721Enumerable { // Mapping from owner to list of owned token IDs mapping(address => mapping(uint256 => uint256)) private _ownedTokens; // Mapping from token ID to index of the owner tokens list mapping(uint256 => uint256) private _ownedTokensIndex; // Array with all token ids, used for enumeration uint256[] private _allTokens; // Mapping from token id to position in the allTokens array mapping(uint256 => uint256) private _allTokensIndex; /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(IERC165, ERC721) returns (bool) { return interfaceId == type(IERC721Enumerable).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721Enumerable-tokenOfOwnerByIndex}. */ function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual override returns (uint256) { require(index < ERC721.balanceOf(owner), "ERC721Enumerable: owner index out of bounds"); return _ownedTokens[owner][index]; } /** * @dev See {IERC721Enumerable-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _allTokens.length; } /** * @dev See {IERC721Enumerable-tokenByIndex}. */ function tokenByIndex(uint256 index) public view virtual override returns (uint256) { require(index < ERC721Enumerable.totalSupply(), "ERC721Enumerable: global index out of bounds"); return _allTokens[index]; } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` cannot be the zero address. * - `to` cannot be the zero address. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual override { super._beforeTokenTransfer(from, to, tokenId); if (from == address(0)) { _addTokenToAllTokensEnumeration(tokenId); } else if (from != to) { _removeTokenFromOwnerEnumeration(from, tokenId); } if (to == address(0)) { _removeTokenFromAllTokensEnumeration(tokenId); } else if (to != from) { _addTokenToOwnerEnumeration(to, tokenId); } } /** * @dev Private function to add a token to this extension's ownership-tracking data structures. * @param to address representing the new owner of the given token ID * @param tokenId uint256 ID of the token to be added to the tokens list of the given address */ function _addTokenToOwnerEnumeration(address to, uint256 tokenId) private { uint256 length = ERC721.balanceOf(to); _ownedTokens[to][length] = tokenId; _ownedTokensIndex[tokenId] = length; } /** * @dev Private function to add a token to this extension's token tracking data structures. * @param tokenId uint256 ID of the token to be added to the tokens list */ function _addTokenToAllTokensEnumeration(uint256 tokenId) private { _allTokensIndex[tokenId] = _allTokens.length; _allTokens.push(tokenId); } /** * @dev Private function to remove a token from this extension's ownership-tracking data structures. Note that * while the token is not assigned a new owner, the `_ownedTokensIndex` mapping is _not_ updated: this allows for * gas optimizations e.g. when performing a transfer operation (avoiding double writes). * This has O(1) time complexity, but alters the order of the _ownedTokens array. * @param from address representing the previous owner of the given token ID * @param tokenId uint256 ID of the token to be removed from the tokens list of the given address */ function _removeTokenFromOwnerEnumeration(address from, uint256 tokenId) private { // To prevent a gap in from's tokens array, we store the last token in the index of the token to delete, and // then delete the last slot (swap and pop). uint256 lastTokenIndex = ERC721.balanceOf(from) - 1; uint256 tokenIndex = _ownedTokensIndex[tokenId]; // When the token to delete is the last token, the swap operation is unnecessary if (tokenIndex != lastTokenIndex) { uint256 lastTokenId = _ownedTokens[from][lastTokenIndex]; _ownedTokens[from][tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token _ownedTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index } // This also deletes the contents at the last position of the array delete _ownedTokensIndex[tokenId]; delete _ownedTokens[from][lastTokenIndex]; } /** * @dev Private function to remove a token from this extension's token tracking data structures. * This has O(1) time complexity, but alters the order of the _allTokens array. * @param tokenId uint256 ID of the token to be removed from the tokens list */ function _removeTokenFromAllTokensEnumeration(uint256 tokenId) private { // To prevent a gap in the tokens array, we store the last token in the index of the token to delete, and // then delete the last slot (swap and pop). uint256 lastTokenIndex = _allTokens.length - 1; uint256 tokenIndex = _allTokensIndex[tokenId]; // When the token to delete is the last token, the swap operation is unnecessary. However, since this occurs so // rarely (when the last minted token is burnt) that we still do the swap here to avoid the gas cost of adding // an 'if' statement (like in _removeTokenFromOwnerEnumeration) uint256 lastTokenId = _allTokens[lastTokenIndex]; _allTokens[tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token _allTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index // This also deletes the contents at the last position of the array delete _allTokensIndex[tokenId]; _allTokens.pop(); } } // File: Marnotaur721.sol contract Marnotaurs is ERC721Enumerable, Ownable { struct Partners { uint256 limit; uint256 nftMinted; } struct Upgrade { uint256 priceETH; uint256 limit; // 0 - unlimited uint256 count; // How much upgraded uint256 tokenIdShift; //used for gen newTokenId, add to old tokenId bool enabled; } struct Beneficiary { address bAddress; uint256 bPercent; } uint256 constant public MAX_TOTAL_SUPPLY = 9990; uint256 constant public MAX_MINT_PER_TX = 10; uint256 constant public MAX_BUY_PER_TX = 10; uint256 public mintPrice = 5e16; uint256 public stopMintAfter = 2775; //5*555 uint256 public reservedForPartners; uint256 public enableBuyAfterTimestamp; mapping (address => Partners) public partnersLimit; Upgrade[] public upgradeTypes; Beneficiary[2] public beneficiaries; //Event for track mint channel: // 1 - MagicBox - depricated // 2 - With Ethere // 3 - Partners White List // 4 - With ERC20 - depricated event MintSource(uint256 tokenId, uint8 channel); event PartnesChanged(address partner, uint256 limit); event Upgraded(address indexed holder, uint256 upgradeIndex, uint256 oldTokenId, uint256 newTokenId); /** * @dev Set _mintMagicBox to true for enable this feature * */ //constructor() ERC721("MÆRⴼTΩR NFT Collection", "MÆRⴼTΩR") { constructor(string memory _name, string memory _symbol) ERC721(_name, _symbol) { //1630353600 - 2021-08-30 20:00 UTC enableBuyAfterTimestamp = 1630353600; beneficiaries[0] = Beneficiary(msg.sender, 6650); beneficiaries[1] = Beneficiary(msg.sender, 3350); } /** * @dev Mint new NFTs with ether or free for partners. * */ function multiMint() external payable { uint256 mintAmount = _availableFreeMint(msg.sender); if(mintAmount > 0) { require(msg.value == 0, "No need Ether"); mintAmount = _multiMint(msg.sender, mintAmount, 3); partnersLimit[msg.sender].nftMinted += mintAmount; reservedForPartners -= mintAmount; } else { require(enableBuyAfterTimestamp <= block.timestamp, "To early"); require(msg.value >= mintPrice, "Less ether for mint"); uint256 estimateAmountForMint = msg.value / mintPrice; require(estimateAmountForMint <= MAX_BUY_PER_TX, "So much payable mint"); require(stopMintAfter - reservedForPartners >= totalSupply() + estimateAmountForMint, "Minting is paused"); mintAmount = _multiMint(msg.sender, estimateAmountForMint, 2); if ((msg.value - mintAmount * mintPrice) > 0) { address payable s = payable(msg.sender); s.transfer(msg.value - mintAmount * mintPrice); } } } function upgradeMe(uint256 _upgradeIndex, uint256 _tokenId) external payable { require (_upgradeIndex < upgradeTypes.length, "Unknown upgrade"); require(ownerOf(_tokenId) == msg.sender, "Only for token owner"); require(upgradeTypes[_upgradeIndex].enabled, "Disabled upgrade"); require(upgradeTypes[_upgradeIndex].priceETH <= msg.value, "Not enough ether"); if (upgradeTypes[_upgradeIndex].limit != 0) { require( upgradeTypes[_upgradeIndex].count + 1 <= upgradeTypes[_upgradeIndex].limit, "Upgrade limit exceeded" ); } upgradeTypes[_upgradeIndex].count += 1; _burn(_tokenId); uint256 newToken = upgradeTypes[_upgradeIndex].tokenIdShift + _tokenId; _mint(msg.sender, newToken); emit Upgraded(msg.sender, _upgradeIndex, _tokenId, newToken); if (msg.value - upgradeTypes[_upgradeIndex].priceETH > 0 ){ address payable s = payable(msg.sender); s.transfer(msg.value - upgradeTypes[_upgradeIndex].priceETH); } } /** * @dev Returns avilable for free mint NFTs for address * */ function availableFreeMint(address _partner) external view returns (uint256) { return _availableFreeMint(_partner); } function getUpgradeType(uint256 _index) external view returns(Upgrade memory) { require(_index < upgradeTypes.length, "Unknown upgrade"); return upgradeTypes[_index]; } function getUpgradeTypeCount() external view returns(uint256) { return upgradeTypes.length; } function getBeneficiaries() external view returns(Beneficiary[2] memory) { return beneficiaries; } /////////////////////////////////////////////////////////////////// ///// Owners Functions /////////////////////////////////////////// /////////////////////////////////////////////////////////////////// function setPartner(address _partner, uint256 _limit) external onlyOwner { _setPartner(_partner, _limit); } function setPartnerBatch(address[] memory _partners, uint256[] memory _limits) external onlyOwner { require(_partners.length == _limits.length, "Array params must have equal length"); require(_partners.length <= 256, "Not more than 256"); for (uint8 i; i < _partners.length; i ++) { _setPartner(_partners[i], _limits[i]); } } function setMintPrice(uint256 _newPrice) external onlyOwner { mintPrice = _newPrice; } function withdrawEther() external onlyOwner { uint256 raised = address(this).balance; for (uint8 i; i < beneficiaries.length; i ++) { address payable o = payable(beneficiaries[i].bAddress); o.transfer(raised * beneficiaries[i].bPercent / 10000); } } function setMintPause(uint256 _newTotalSupply) external onlyOwner { stopMintAfter = _newTotalSupply; } function setEnableTimestamp(uint256 _newTimestamp) external onlyOwner { enableBuyAfterTimestamp = _newTimestamp; } function addUpgradeType( uint256 _priceETH, uint256 _limit, uint256 _tokenIdShift, bool _enabled ) external onlyOwner { require(_tokenIdShift > MAX_TOTAL_SUPPLY, "Not Zero"); upgradeTypes.push(Upgrade({ priceETH: _priceETH, limit: _limit, count: 0, tokenIdShift: _tokenIdShift, enabled: _enabled }) ); } function updateUpType( uint256 _inedx, uint256 _priceETH, uint256 _limit, bool _enabled ) external onlyOwner { upgradeTypes[_inedx].priceETH = _priceETH; upgradeTypes[_inedx].limit = _limit; upgradeTypes[_inedx].enabled = _enabled; } function setBeneficiary(uint256 _index, address _beneficiary) external onlyOwner { require(_beneficiary != address(0), "No Zero Address"); beneficiaries[_index].bAddress = _beneficiary; } /////////////////////////////////////////////////////////////////// ///// INTERNALS ///////////////////////////////////////////// /////////////////////////////////////////////////////////////////// function _availableFreeMint(address _partner) internal view returns (uint256) { return partnersLimit[_partner].limit - partnersLimit[_partner].nftMinted; } function _baseURI() internal view override returns (string memory) { return string(abi.encodePacked( //"https://dev.nftstars.app/backend/api/v1/nfts/metadata/0x", "https://nftstars.app/backend/api/v1/nfts/metadata/0x", toAsciiString(address(this)), "/") ); } function _setPartner(address _partner, uint256 _limit) internal { require(_partner != address(0), "No zero"); require(_limit >= partnersLimit[_partner].nftMinted, "Cant decrease more then minted"); if (partnersLimit[_partner].limit < _limit) { reservedForPartners += (_limit - partnersLimit[_partner].limit); } else { reservedForPartners -= (partnersLimit[_partner].limit - _limit); } partnersLimit[_partner].limit = _limit; emit PartnesChanged(_partner, _limit); } function _multiMint(address to, uint256 amount, uint8 channel) internal returns (uint256) { require((totalSupply() + reservedForPartners + amount) <= MAX_TOTAL_SUPPLY, "No more common heroes"); uint256 counter; if (amount > MAX_MINT_PER_TX) { counter = MAX_MINT_PER_TX; } else { counter = amount; } if ((totalSupply() + counter) > MAX_TOTAL_SUPPLY) { counter = MAX_TOTAL_SUPPLY - totalSupply(); } for(uint i = 0; i < counter; i++) { _mint(to, totalSupply()); emit MintSource(totalSupply()-1, channel); } return counter; } function toAsciiString(address x) internal view returns (string memory) { bytes memory s = new bytes(40); for (uint i = 0; i < 20; i++) { bytes1 b = bytes1(uint8(uint(uint160(x)) / (2**(8*(19 - i))))); bytes1 hi = bytes1(uint8(b) / 16); bytes1 lo = bytes1(uint8(b) - 16 * uint8(hi)); s[2*i] = char(hi); s[2*i+1] = char(lo); } return string(s); } function char(bytes1 b) internal view returns (bytes1 c) { if (uint8(b) < 10) return bytes1(uint8(b) + 0x30); else return bytes1(uint8(b) + 0x57); } }
Mint new NFTs with ether or free for partners./
function multiMint() external payable { uint256 mintAmount = _availableFreeMint(msg.sender); if(mintAmount > 0) { require(msg.value == 0, "No need Ether"); mintAmount = _multiMint(msg.sender, mintAmount, 3); partnersLimit[msg.sender].nftMinted += mintAmount; reservedForPartners -= mintAmount; require(enableBuyAfterTimestamp <= block.timestamp, "To early"); require(msg.value >= mintPrice, "Less ether for mint"); uint256 estimateAmountForMint = msg.value / mintPrice; require(estimateAmountForMint <= MAX_BUY_PER_TX, "So much payable mint"); require(stopMintAfter - reservedForPartners >= totalSupply() + estimateAmountForMint, "Minting is paused"); mintAmount = _multiMint(msg.sender, estimateAmountForMint, 2); if ((msg.value - mintAmount * mintPrice) > 0) { address payable s = payable(msg.sender); s.transfer(msg.value - mintAmount * mintPrice); } } }
13,707,686
// SPDX-License-Identifier: AGPL-3.0 // File contracts/dependencies/open-zeppelin/Context.sol pragma solidity 0.7.5; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } // File contracts/dependencies/open-zeppelin/IERC20.sol pragma solidity 0.7.5; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // File contracts/dependencies/open-zeppelin/SafeMath.sol pragma solidity 0.7.5; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, 'SafeMath: addition overflow'); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, 'SafeMath: subtraction overflow'); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. */ function sub( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, 'SafeMath: multiplication overflow'); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, 'SafeMath: division by zero'); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function div( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { // Solidity only automatically asserts when dividing by 0 require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, 'SafeMath: modulo by zero'); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function mod( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } // File contracts/dependencies/open-zeppelin/Address.sol pragma solidity 0.7.5; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // According to EIP-1052, 0x0 is the value returned for not-yet created accounts // and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned // for accounts without code, i.e. `keccak256('')` bytes32 codehash; bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; // solhint-disable-next-line no-inline-assembly assembly { codehash := extcodehash(account) } return (codehash != accountHash && codehash != 0x0); } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, 'Address: insufficient balance'); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{value: amount}(''); require(success, 'Address: unable to send value, recipient may have reverted'); } } // File contracts/dependencies/open-zeppelin/ERC20.sol pragma solidity ^0.7.5; /** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20PresetMinterPauser}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin guidelines: functions revert instead * of returning `false` on failure. This behavior is nonetheless conventional * and does not conflict with the expectations of ERC20 applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */ contract ERC20 is Context, IERC20 { using SafeMath for uint256; using Address for address; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; string internal _name; string internal _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() virtual public view returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() virtual public view returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is * called. * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() virtual public view returns (uint8) { return _decimals; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}; * * Requirements: * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer(address sender, address recipient, uint256 amount) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements * * - `to` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner`s tokens. * * This is internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve(address owner, address spender, uint256 amount) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Sets {decimals} to a value other than the default one of 18. * * WARNING: This function should only be called from the constructor. Most * applications that interact with token contracts will not expect * {decimals} to ever change, and may work incorrectly if it does. */ function _setupDecimals(uint8 decimals_) internal { _decimals = decimals_; } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be to transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { } } // File contracts/dependencies/open-zeppelin/Ownable.sol pragma solidity 0.7.5; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(_owner == _msgSender(), 'Ownable: caller is not the owner'); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public 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 contracts/interfaces/IGovernancePowerDelegationERC20.sol pragma solidity 0.7.5; interface IGovernancePowerDelegationERC20 { enum DelegationType { VOTING_POWER, PROPOSITION_POWER } /** * @dev Emitted when a user delegates governance power to another user. * * @param delegator The delegator. * @param delegatee The delegatee. * @param delegationType The type of delegation (VOTING_POWER, PROPOSITION_POWER). */ event DelegateChanged( address indexed delegator, address indexed delegatee, DelegationType delegationType ); /** * @dev Emitted when an action changes the delegated power of a user. * * @param user The user whose delegated power has changed. * @param amount The new amount of delegated power for the user. * @param delegationType The type of delegation (VOTING_POWER, PROPOSITION_POWER). */ event DelegatedPowerChanged(address indexed user, uint256 amount, DelegationType delegationType); /** * @dev Delegates a specific governance power to a delegatee. * * @param delegatee The address to delegate power to. * @param delegationType The type of delegation (VOTING_POWER, PROPOSITION_POWER). */ function delegateByType(address delegatee, DelegationType delegationType) external virtual; /** * @dev Delegates all governance powers to a delegatee. * * @param delegatee The user to which the power will be delegated. */ function delegate(address delegatee) external virtual; /** * @dev Returns the delegatee of an user. * * @param delegator The address of the delegator. * @param delegationType The type of delegation (VOTING_POWER, PROPOSITION_POWER). */ function getDelegateeByType(address delegator, DelegationType delegationType) external view virtual returns (address); /** * @dev Returns the current delegated power of a user. The current power is the power delegated * at the time of the last snapshot. * * @param user The user whose power to query. * @param delegationType The type of power (VOTING_POWER, PROPOSITION_POWER). */ function getPowerCurrent(address user, DelegationType delegationType) external view virtual returns (uint256); /** * @dev Returns the delegated power of a user at a certain block. * * @param user The user whose power to query. * @param blockNumber The block number at which to get the user's power. * @param delegationType The type of power (VOTING_POWER, PROPOSITION_POWER). */ function getPowerAtBlock( address user, uint256 blockNumber, DelegationType delegationType ) external view virtual returns (uint256); } // File contracts/governance/token/GovernancePowerDelegationERC20Mixin.sol pragma solidity 0.7.5; /** * @title GovernancePowerDelegationERC20Mixin * @author dYdX * * @dev Provides support for two types of governance powers, both endowed by the governance * token, and separately delegatable. Provides functions for delegation and for querying a user's * power at a certain block number. */ abstract contract GovernancePowerDelegationERC20Mixin is ERC20, IGovernancePowerDelegationERC20 { using SafeMath for uint256; // ============ Constants ============ /// @notice EIP-712 typehash for delegation by signature of a specific governance power type. bytes32 public constant DELEGATE_BY_TYPE_TYPEHASH = keccak256( 'DelegateByType(address delegatee,uint256 type,uint256 nonce,uint256 expiry)' ); /// @notice EIP-712 typehash for delegation by signature of all governance powers. bytes32 public constant DELEGATE_TYPEHASH = keccak256( 'Delegate(address delegatee,uint256 nonce,uint256 expiry)' ); // ============ Structs ============ /// @dev Snapshot of a value on a specific block, used to track voting power for proposals. struct Snapshot { uint128 blockNumber; uint128 value; } // ============ External Functions ============ /** * @notice Delegates a specific governance power to a delegatee. * * @param delegatee The address to delegate power to. * @param delegationType The type of delegation (VOTING_POWER, PROPOSITION_POWER). */ function delegateByType( address delegatee, DelegationType delegationType ) external override { _delegateByType(msg.sender, delegatee, delegationType); } /** * @notice Delegates all governance powers to a delegatee. * * @param delegatee The address to delegate power to. */ function delegate( address delegatee ) external override { _delegateByType(msg.sender, delegatee, DelegationType.VOTING_POWER); _delegateByType(msg.sender, delegatee, DelegationType.PROPOSITION_POWER); } /** * @notice Returns the delegatee of a user. * * @param delegator The address of the delegator. * @param delegationType The type of delegation (VOTING_POWER, PROPOSITION_POWER). */ function getDelegateeByType( address delegator, DelegationType delegationType ) external override view returns (address) { (, , mapping(address => address) storage delegates) = _getDelegationDataByType(delegationType); return _getDelegatee(delegator, delegates); } /** * @notice Returns the current power of a user. The current power is the power delegated * at the time of the last snapshot. * * @param user The user whose power to query. * @param delegationType The type of power (VOTING_POWER, PROPOSITION_POWER). */ function getPowerCurrent( address user, DelegationType delegationType ) external override view returns (uint256) { ( mapping(address => mapping(uint256 => Snapshot)) storage snapshots, mapping(address => uint256) storage snapshotsCounts, // delegates ) = _getDelegationDataByType(delegationType); return _searchByBlockNumber(snapshots, snapshotsCounts, user, block.number); } /** * @notice Returns the power of a user at a certain block. * * @param user The user whose power to query. * @param blockNumber The block number at which to get the user's power. * @param delegationType The type of power (VOTING_POWER, PROPOSITION_POWER). */ function getPowerAtBlock( address user, uint256 blockNumber, DelegationType delegationType ) external override view returns (uint256) { ( mapping(address => mapping(uint256 => Snapshot)) storage snapshots, mapping(address => uint256) storage snapshotsCounts, // delegates ) = _getDelegationDataByType(delegationType); return _searchByBlockNumber(snapshots, snapshotsCounts, user, blockNumber); } // ============ Internal Functions ============ /** * @dev Delegates one specific power to a delegatee. * * @param delegator The user whose power to delegate. * @param delegatee The address to delegate power to. * @param delegationType The type of power (VOTING_POWER, PROPOSITION_POWER). */ function _delegateByType( address delegator, address delegatee, DelegationType delegationType ) internal { require( delegatee != address(0), 'INVALID_DELEGATEE' ); (, , mapping(address => address) storage delegates) = _getDelegationDataByType(delegationType); uint256 delegatorBalance = balanceOf(delegator); address previousDelegatee = _getDelegatee(delegator, delegates); delegates[delegator] = delegatee; _moveDelegatesByType(previousDelegatee, delegatee, delegatorBalance, delegationType); emit DelegateChanged(delegator, delegatee, delegationType); } /** * @dev Moves power from one user to another. * * @param from The user from which delegated power is moved. * @param to The user that will receive the delegated power. * @param amount The amount of power to be moved. * @param delegationType The type of power (VOTING_POWER, PROPOSITION_POWER). */ function _moveDelegatesByType( address from, address to, uint256 amount, DelegationType delegationType ) internal { if (from == to) { return; } ( mapping(address => mapping(uint256 => Snapshot)) storage snapshots, mapping(address => uint256) storage snapshotsCounts, // delegates ) = _getDelegationDataByType(delegationType); if (from != address(0)) { uint256 previous = 0; uint256 fromSnapshotsCount = snapshotsCounts[from]; if (fromSnapshotsCount != 0) { previous = snapshots[from][fromSnapshotsCount - 1].value; } else { previous = balanceOf(from); } uint256 newAmount = previous.sub(amount); _writeSnapshot( snapshots, snapshotsCounts, from, uint128(newAmount) ); emit DelegatedPowerChanged(from, newAmount, delegationType); } if (to != address(0)) { uint256 previous = 0; uint256 toSnapshotsCount = snapshotsCounts[to]; if (toSnapshotsCount != 0) { previous = snapshots[to][toSnapshotsCount - 1].value; } else { previous = balanceOf(to); } uint256 newAmount = previous.add(amount); _writeSnapshot( snapshots, snapshotsCounts, to, uint128(newAmount) ); emit DelegatedPowerChanged(to, newAmount, delegationType); } } /** * @dev Searches for a balance snapshot by block number using binary search. * * @param snapshots The mapping of snapshots by user. * @param snapshotsCounts The mapping of the number of snapshots by user. * @param user The user for which the snapshot is being searched. * @param blockNumber The block number being searched. */ function _searchByBlockNumber( mapping(address => mapping(uint256 => Snapshot)) storage snapshots, mapping(address => uint256) storage snapshotsCounts, address user, uint256 blockNumber ) internal view returns (uint256) { require( blockNumber <= block.number, 'INVALID_BLOCK_NUMBER' ); uint256 snapshotsCount = snapshotsCounts[user]; if (snapshotsCount == 0) { return balanceOf(user); } // First check most recent balance if (snapshots[user][snapshotsCount - 1].blockNumber <= blockNumber) { return snapshots[user][snapshotsCount - 1].value; } // Next check implicit zero balance if (snapshots[user][0].blockNumber > blockNumber) { return 0; } uint256 lower = 0; uint256 upper = snapshotsCount - 1; while (upper > lower) { uint256 center = upper - (upper - lower) / 2; // ceil, avoiding overflow Snapshot memory snapshot = snapshots[user][center]; if (snapshot.blockNumber == blockNumber) { return snapshot.value; } else if (snapshot.blockNumber < blockNumber) { lower = center; } else { upper = center - 1; } } return snapshots[user][lower].value; } /** * @dev Returns delegation data (snapshot, snapshotsCount, delegates) by delegation type. * * Note: This mixin contract does not itself define any storage, and we require the inheriting * contract to implement this method to provide access to the relevant mappings in storage. * This pattern was implemented by Aave for legacy reasons and we have decided not to change it. * * @param delegationType The type of power (VOTING_POWER, PROPOSITION_POWER). */ function _getDelegationDataByType( DelegationType delegationType ) internal virtual view returns ( mapping(address => mapping(uint256 => Snapshot)) storage, // snapshots mapping(address => uint256) storage, // snapshotsCount mapping(address => address) storage // delegates ); /** * @dev Writes a snapshot of a user's token/power balance. * * @param snapshots The mapping of snapshots by user. * @param snapshotsCounts The mapping of the number of snapshots by user. * @param owner The user whose power to snapshot. * @param newValue The new balance to snapshot at the current block. */ function _writeSnapshot( mapping(address => mapping(uint256 => Snapshot)) storage snapshots, mapping(address => uint256) storage snapshotsCounts, address owner, uint128 newValue ) internal { uint128 currentBlock = uint128(block.number); uint256 ownerSnapshotsCount = snapshotsCounts[owner]; mapping(uint256 => Snapshot) storage ownerSnapshots = snapshots[owner]; if ( ownerSnapshotsCount != 0 && ownerSnapshots[ownerSnapshotsCount - 1].blockNumber == currentBlock ) { // Doing multiple operations in the same block ownerSnapshots[ownerSnapshotsCount - 1].value = newValue; } else { ownerSnapshots[ownerSnapshotsCount] = Snapshot(currentBlock, newValue); snapshotsCounts[owner] = ownerSnapshotsCount + 1; } } /** * @dev Returns the delegatee of a user. If a user never performed any delegation, their * delegated address will be 0x0, in which case we return the user's own address. * * @param delegator The address of the user for which return the delegatee. * @param delegates The mapping of delegates for a particular type of delegation. */ function _getDelegatee( address delegator, mapping(address => address) storage delegates ) internal view returns (address) { address previousDelegatee = delegates[delegator]; if (previousDelegatee == address(0)) { return delegator; } return previousDelegatee; } } // File contracts/governance/token/DydxToken.sol pragma solidity 0.7.5; /** * @title DydxToken * @author dYdX * * @notice The dYdX governance token. */ contract DydxToken is GovernancePowerDelegationERC20Mixin, Ownable { using SafeMath for uint256; // ============ Events ============ /** * @dev Emitted when an address has been added to or removed from the token transfer allowlist. * * @param account Address that was added to or removed from the token transfer allowlist. * @param isAllowed True if the address was added to the allowlist, false if removed. */ event TransferAllowlistUpdated( address account, bool isAllowed ); /** * @dev Emitted when the transfer restriction timestamp is reassigned. * * @param transfersRestrictedBefore The new timestamp on and after which non-allowlisted * transfers may occur. */ event TransfersRestrictedBeforeUpdated( uint256 transfersRestrictedBefore ); // ============ Constants ============ string internal constant NAME = 'dYdX'; string internal constant SYMBOL = 'DYDX'; uint256 public constant INITIAL_SUPPLY = 1_000_000_000 ether; bytes32 public immutable DOMAIN_SEPARATOR; bytes public constant EIP712_VERSION = '1'; bytes32 public constant EIP712_DOMAIN = keccak256( 'EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)' ); bytes32 public constant PERMIT_TYPEHASH = keccak256( 'Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)' ); /// @notice Minimum time between mints. uint256 public constant MINT_MIN_INTERVAL = 365 days; /// @notice Cap on the percentage of the total supply that can be minted at each mint. /// Denominated in percentage points (units out of 100). uint256 public immutable MINT_MAX_PERCENT; /// @notice The timestamp on and after which the transfer restriction must be lifted. uint256 public immutable TRANSFER_RESTRICTION_LIFTED_NO_LATER_THAN; // ============ Storage ============ /// @dev Mapping from (owner) => (next valid nonce) for EIP-712 signatures. mapping(address => uint256) internal _nonces; mapping(address => mapping(uint256 => Snapshot)) public _votingSnapshots; mapping(address => uint256) public _votingSnapshotsCounts; mapping(address => address) public _votingDelegates; mapping(address => mapping(uint256 => Snapshot)) public _propositionPowerSnapshots; mapping(address => uint256) public _propositionPowerSnapshotsCounts; mapping(address => address) public _propositionPowerDelegates; /// @notice Snapshots of the token total supply, at each block where the total supply has changed. mapping(uint256 => Snapshot) public _totalSupplySnapshots; /// @notice Number of snapshots of the token total supply. uint256 public _totalSupplySnapshotsCount; /// @notice Allowlist of addresses which may send or receive tokens while transfers are /// otherwise restricted. mapping(address => bool) public _tokenTransferAllowlist; /// @notice The timestamp on and after which minting may occur. uint256 public _mintingRestrictedBefore; /// @notice The timestamp on and after which non-allowlisted transfers may occur. uint256 public _transfersRestrictedBefore; // ============ Constructor ============ /** * @notice Constructor. * * @param distributor The address which will receive the initial supply of tokens. * @param transfersRestrictedBefore Timestamp, before which transfers are restricted unless the * origin or destination address is in the allowlist. * @param transferRestrictionLiftedNoLaterThan Timestamp, which is the maximum timestamp that transfer * restrictions can be extended to. * @param mintingRestrictedBefore Timestamp, before which minting is not allowed. * @param mintMaxPercent Cap on the percentage of the total supply that can be minted at * each mint. */ constructor( address distributor, uint256 transfersRestrictedBefore, uint256 transferRestrictionLiftedNoLaterThan, uint256 mintingRestrictedBefore, uint256 mintMaxPercent ) ERC20(NAME, SYMBOL) { uint256 chainId; // solium-disable-next-line assembly { chainId := chainid() } DOMAIN_SEPARATOR = keccak256( abi.encode( EIP712_DOMAIN, keccak256(bytes(NAME)), keccak256(bytes(EIP712_VERSION)), chainId, address(this) ) ); // Validate and set parameters. require( transfersRestrictedBefore > block.timestamp, 'TRANSFERS_RESTRICTED_BEFORE_TOO_EARLY' ); require( transfersRestrictedBefore <= transferRestrictionLiftedNoLaterThan, 'MAX_TRANSFER_RESTRICTION_TOO_EARLY' ); require( mintingRestrictedBefore > block.timestamp, 'MINTING_RESTRICTED_BEFORE_TOO_EARLY' ); _transfersRestrictedBefore = transfersRestrictedBefore; TRANSFER_RESTRICTION_LIFTED_NO_LATER_THAN = transferRestrictionLiftedNoLaterThan; _mintingRestrictedBefore = mintingRestrictedBefore; MINT_MAX_PERCENT = mintMaxPercent; // Mint the initial supply. _mint(distributor, INITIAL_SUPPLY); emit TransfersRestrictedBeforeUpdated(transfersRestrictedBefore); } // ============ Other Functions ============ /** * @notice Adds addresses to the token transfer allowlist. Reverts if any of the addresses * already exist in the allowlist. Only callable by owner. * * @param addressesToAdd Addresses to add to the token transfer allowlist. */ function addToTokenTransferAllowlist( address[] calldata addressesToAdd ) external onlyOwner { for (uint256 i = 0; i < addressesToAdd.length; i++) { require( !_tokenTransferAllowlist[addressesToAdd[i]], 'ADDRESS_EXISTS_IN_TRANSFER_ALLOWLIST' ); _tokenTransferAllowlist[addressesToAdd[i]] = true; emit TransferAllowlistUpdated(addressesToAdd[i], true); } } /** * @notice Removes addresses from the token transfer allowlist. Reverts if any of the addresses * don't exist in the allowlist. Only callable by owner. * * @param addressesToRemove Addresses to remove from the token transfer allowlist. */ function removeFromTokenTransferAllowlist( address[] calldata addressesToRemove ) external onlyOwner { for (uint256 i = 0; i < addressesToRemove.length; i++) { require( _tokenTransferAllowlist[addressesToRemove[i]], 'ADDRESS_DOES_NOT_EXIST_IN_TRANSFER_ALLOWLIST' ); _tokenTransferAllowlist[addressesToRemove[i]] = false; emit TransferAllowlistUpdated(addressesToRemove[i], false); } } /** * @notice Updates the transfer restriction. Reverts if the transfer restriction has already passed, * the new transfer restriction is earlier than the previous one, or the new transfer restriction is * after the maximum transfer restriction. * * @param transfersRestrictedBefore The timestamp on and after which non-allowlisted transfers may occur. */ function updateTransfersRestrictedBefore( uint256 transfersRestrictedBefore ) external onlyOwner { uint256 previousTransfersRestrictedBefore = _transfersRestrictedBefore; require( block.timestamp < previousTransfersRestrictedBefore, 'TRANSFER_RESTRICTION_ENDED' ); require( previousTransfersRestrictedBefore <= transfersRestrictedBefore, 'NEW_TRANSFER_RESTRICTION_TOO_EARLY' ); require( transfersRestrictedBefore <= TRANSFER_RESTRICTION_LIFTED_NO_LATER_THAN, 'AFTER_MAX_TRANSFER_RESTRICTION' ); _transfersRestrictedBefore = transfersRestrictedBefore; emit TransfersRestrictedBeforeUpdated(transfersRestrictedBefore); } /** * @notice Mint new tokens. Only callable by owner after the required time period has elapsed. * * @param recipient The address to receive minted tokens. * @param amount The number of tokens to mint. */ function mint( address recipient, uint256 amount ) external onlyOwner { require( block.timestamp >= _mintingRestrictedBefore, 'MINT_TOO_EARLY' ); require( amount <= totalSupply().mul(MINT_MAX_PERCENT).div(100), 'MAX_MINT_EXCEEDED' ); // Update the next allowed minting time. _mintingRestrictedBefore = block.timestamp.add(MINT_MIN_INTERVAL); // Mint the amount. _mint(recipient, amount); } /** * @notice Implements the permit function as specified in EIP-2612. * * @param owner Address of the token owner. * @param spender Address of the spender. * @param value Amount of allowance. * @param deadline Expiration timestamp for the signature. * @param v Signature param. * @param r Signature param. * @param s Signature param. */ function permit( address owner, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) external { require( owner != address(0), 'INVALID_OWNER' ); require( block.timestamp <= deadline, 'INVALID_EXPIRATION' ); uint256 currentValidNonce = _nonces[owner]; bytes32 digest = keccak256( abi.encodePacked( '\x19\x01', DOMAIN_SEPARATOR, keccak256(abi.encode(PERMIT_TYPEHASH, owner, spender, value, currentValidNonce, deadline)) ) ); require( owner == ecrecover(digest, v, r, s), 'INVALID_SIGNATURE' ); _nonces[owner] = currentValidNonce.add(1); _approve(owner, spender, value); } /** * @notice Get the next valid nonce for EIP-712 signatures. * * This nonce should be used when signing for any of the following functions: * - permit() * - delegateByTypeBySig() * - delegateBySig() */ function nonces( address owner ) external view returns (uint256) { return _nonces[owner]; } function transfer( address recipient, uint256 amount ) public override returns (bool) { _requireTransferAllowed(_msgSender(), recipient); return super.transfer(recipient, amount); } function transferFrom( address sender, address recipient, uint256 amount ) public override returns (bool) { _requireTransferAllowed(sender, recipient); return super.transferFrom(sender, recipient, amount); } /** * @dev Override _mint() to write a snapshot whenever the total supply changes. * * These snapshots are intended to be used by the governance strategy. * * Note that the ERC20 _burn() function is never used. If desired, an official burn mechanism * could be implemented external to this contract, and accounted for in the governance strategy. */ function _mint( address account, uint256 amount ) internal override { super._mint(account, amount); uint256 snapshotsCount = _totalSupplySnapshotsCount; uint128 currentBlock = uint128(block.number); uint128 newValue = uint128(totalSupply()); // Note: There is no special case for the total supply being updated multiple times in the same // block. That should never occur. _totalSupplySnapshots[snapshotsCount] = Snapshot(currentBlock, newValue); _totalSupplySnapshotsCount = snapshotsCount.add(1); } function _requireTransferAllowed( address sender, address recipient ) view internal { // Compare against the constant `TRANSFER_RESTRICTION_LIFTED_NO_LATER_THAN` first // to avoid additional gas costs from reading from storage. if ( block.timestamp < TRANSFER_RESTRICTION_LIFTED_NO_LATER_THAN && block.timestamp < _transfersRestrictedBefore ) { // While transfers are restricted, a transfer is permitted if either the sender or the // recipient is on the allowlist. require( _tokenTransferAllowlist[sender] || _tokenTransferAllowlist[recipient], 'NON_ALLOWLIST_TRANSFERS_DISABLED' ); } } /** * @dev Writes a snapshot before any transfer operation, including: _transfer, _mint and _burn. * - On _transfer, it writes snapshots for both 'from' and 'to'. * - On _mint, only for `to`. * - On _burn, only for `from`. * * @param from The sender. * @param to The recipient. * @param amount The amount being transfered. */ function _beforeTokenTransfer( address from, address to, uint256 amount ) internal override { address votingFromDelegatee = _getDelegatee(from, _votingDelegates); address votingToDelegatee = _getDelegatee(to, _votingDelegates); _moveDelegatesByType( votingFromDelegatee, votingToDelegatee, amount, DelegationType.VOTING_POWER ); address propPowerFromDelegatee = _getDelegatee(from, _propositionPowerDelegates); address propPowerToDelegatee = _getDelegatee(to, _propositionPowerDelegates); _moveDelegatesByType( propPowerFromDelegatee, propPowerToDelegatee, amount, DelegationType.PROPOSITION_POWER ); } function _getDelegationDataByType( DelegationType delegationType ) internal override view returns ( mapping(address => mapping(uint256 => Snapshot)) storage, // snapshots mapping(address => uint256) storage, // snapshots count mapping(address => address) storage // delegatees list ) { if (delegationType == DelegationType.VOTING_POWER) { return (_votingSnapshots, _votingSnapshotsCounts, _votingDelegates); } else { return ( _propositionPowerSnapshots, _propositionPowerSnapshotsCounts, _propositionPowerDelegates ); } } /** * @dev Delegates specific governance power from signer to `delegatee` using an EIP-712 signature. * * @param delegatee The address to delegate votes to. * @param delegationType The type of delegation (VOTING_POWER, PROPOSITION_POWER). * @param nonce The signer's nonce for EIP-712 signatures on this contract. * @param expiry Expiration timestamp for the signature. * @param v Signature param. * @param r Signature param. * @param s Signature param. */ function delegateByTypeBySig( address delegatee, DelegationType delegationType, uint256 nonce, uint256 expiry, uint8 v, bytes32 r, bytes32 s ) public { bytes32 structHash = keccak256( abi.encode(DELEGATE_BY_TYPE_TYPEHASH, delegatee, uint256(delegationType), nonce, expiry) ); bytes32 digest = keccak256(abi.encodePacked('\x19\x01', DOMAIN_SEPARATOR, structHash)); address signer = ecrecover(digest, v, r, s); require( signer != address(0), 'INVALID_SIGNATURE' ); require( nonce == _nonces[signer]++, 'INVALID_NONCE' ); require( block.timestamp <= expiry, 'INVALID_EXPIRATION' ); _delegateByType(signer, delegatee, delegationType); } /** * @dev Delegates both governance powers from signer to `delegatee` using an EIP-712 signature. * * @param delegatee The address to delegate votes to. * @param nonce The signer's nonce for EIP-712 signatures on this contract. * @param expiry Expiration timestamp for the signature. * @param v Signature param. * @param r Signature param. * @param s Signature param. */ function delegateBySig( address delegatee, uint256 nonce, uint256 expiry, uint8 v, bytes32 r, bytes32 s ) public { bytes32 structHash = keccak256(abi.encode(DELEGATE_TYPEHASH, delegatee, nonce, expiry)); bytes32 digest = keccak256(abi.encodePacked('\x19\x01', DOMAIN_SEPARATOR, structHash)); address signer = ecrecover(digest, v, r, s); require( signer != address(0), 'INVALID_SIGNATURE' ); require( nonce == _nonces[signer]++, 'INVALID_NONCE' ); require( block.timestamp <= expiry, 'INVALID_EXPIRATION' ); _delegateByType(signer, delegatee, DelegationType.VOTING_POWER); _delegateByType(signer, delegatee, DelegationType.PROPOSITION_POWER); } }
Returns delegation data (snapshot, snapshotsCount, delegates) by delegation type. Note: This mixin contract does not itself define any storage, and we require the inheriting contract to implement this method to provide access to the relevant mappings in storage. This pattern was implemented by Aave for legacy reasons and we have decided not to change it. delegationType The type of power (VOTING_POWER, PROPOSITION_POWER)./ Writes a snapshot of a user's token/power balance. snapshots The mapping of snapshots by user. snapshotsCounts The mapping of the number of snapshots by user. owner The user whose power to snapshot. newValue The new balance to snapshot at the current block./ Doing multiple operations in the same block
function _getDelegationDataByType( DelegationType delegationType ) internal virtual view returns ( ); function _writeSnapshot( mapping(address => mapping(uint256 => Snapshot)) storage snapshots, mapping(address => uint256) storage snapshotsCounts, address owner, uint128 newValue ) internal { uint128 currentBlock = uint128(block.number); uint256 ownerSnapshotsCount = snapshotsCounts[owner]; mapping(uint256 => Snapshot) storage ownerSnapshots = snapshots[owner]; if ( ownerSnapshotsCount != 0 && ownerSnapshots[ownerSnapshotsCount - 1].blockNumber == currentBlock ) { ownerSnapshots[ownerSnapshotsCount - 1].value = newValue; ownerSnapshots[ownerSnapshotsCount] = Snapshot(currentBlock, newValue); snapshotsCounts[owner] = ownerSnapshotsCount + 1; } }
12,691,738
./full_match/82/0xA3F51Bb79793AC7ca38956f4928E080822814708/sources/contracts/base/vote/VoltVoterUpgradeable.sol
Update gauges by indexes in a range.
function updateForRange(uint start, uint end) public { for (uint i = start; i < end; i++) { _updateFor(gauges[pools[i]]); } }
7,094,268
./full_match/44787/0x0913Ee6847C6225C836431B8bDC16172fb2a52Df/sources/home/boyd/git/keyko/celo-ubi-contract/contracts/UBIController.sol
Returns to normal state. Requirements: The contract must be paused./
function unpause() external onlyOwner nonReentrant { _unpause(); }
13,241,521
pragma solidity ^0.5.0; // File: openzeppelin-solidity/contracts/math/SafeMath.sol /** * @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/access/Roles.sol /** * @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]; } } // File: contracts/controller/Permissions/RootPlatformAdministratorRole.sol /* Copyright 2018, CONDA This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ /** @title RootPlatformAdministratorRole root user role mainly to manage other roles. */ contract RootPlatformAdministratorRole { using Roles for Roles.Role; /////////////////// // Events /////////////////// event RootPlatformAdministratorAdded(address indexed account); event RootPlatformAdministratorRemoved(address indexed account); /////////////////// // Variables /////////////////// Roles.Role private rootPlatformAdministrators; /////////////////// // Constructor /////////////////// constructor() internal { _addRootPlatformAdministrator(msg.sender); } /////////////////// // Modifiers /////////////////// modifier onlyRootPlatformAdministrator() { require(isRootPlatformAdministrator(msg.sender), "no root PFadmin"); _; } /////////////////// // Functions /////////////////// function isRootPlatformAdministrator(address account) public view returns (bool) { return rootPlatformAdministrators.has(account); } function addRootPlatformAdministrator(address account) public onlyRootPlatformAdministrator { _addRootPlatformAdministrator(account); } function renounceRootPlatformAdministrator() public { _removeRootPlatformAdministrator(msg.sender); } function _addRootPlatformAdministrator(address account) internal { rootPlatformAdministrators.add(account); emit RootPlatformAdministratorAdded(account); } function _removeRootPlatformAdministrator(address account) internal { rootPlatformAdministrators.remove(account); emit RootPlatformAdministratorRemoved(account); } } // File: contracts/controller/Permissions/AssetTokenAdministratorRole.sol /* Copyright 2018, CONDA This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ /** @title AssetTokenAdministratorRole of AssetToken administrators. */ contract AssetTokenAdministratorRole is RootPlatformAdministratorRole { /////////////////// // Events /////////////////// event AssetTokenAdministratorAdded(address indexed account); event AssetTokenAdministratorRemoved(address indexed account); /////////////////// // Variables /////////////////// Roles.Role private assetTokenAdministrators; /////////////////// // Constructor /////////////////// constructor() internal { _addAssetTokenAdministrator(msg.sender); } /////////////////// // Modifiers /////////////////// modifier onlyAssetTokenAdministrator() { require(isAssetTokenAdministrator(msg.sender), "no ATadmin"); _; } /////////////////// // Functions /////////////////// function isAssetTokenAdministrator(address _account) public view returns (bool) { return assetTokenAdministrators.has(_account); } function addAssetTokenAdministrator(address _account) public onlyRootPlatformAdministrator { _addAssetTokenAdministrator(_account); } function renounceAssetTokenAdministrator() public { _removeAssetTokenAdministrator(msg.sender); } function _addAssetTokenAdministrator(address _account) internal { assetTokenAdministrators.add(_account); emit AssetTokenAdministratorAdded(_account); } function removeAssetTokenAdministrator(address _account) public onlyRootPlatformAdministrator { _removeAssetTokenAdministrator(_account); } function _removeAssetTokenAdministrator(address _account) internal { assetTokenAdministrators.remove(_account); emit AssetTokenAdministratorRemoved(_account); } } // File: contracts/controller/Permissions/At2CsConnectorRole.sol /* Copyright 2018, CONDA This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ /** @title At2CsConnectorRole AssetToken to Crowdsale connector role. */ contract At2CsConnectorRole is RootPlatformAdministratorRole { /////////////////// // Events /////////////////// event At2CsConnectorAdded(address indexed account); event At2CsConnectorRemoved(address indexed account); /////////////////// // Variables /////////////////// Roles.Role private at2csConnectors; /////////////////// // Constructor /////////////////// constructor() internal { _addAt2CsConnector(msg.sender); } /////////////////// // Modifiers /////////////////// modifier onlyAt2CsConnector() { require(isAt2CsConnector(msg.sender), "no at2csAdmin"); _; } /////////////////// // Functions /////////////////// function isAt2CsConnector(address _account) public view returns (bool) { return at2csConnectors.has(_account); } function addAt2CsConnector(address _account) public onlyRootPlatformAdministrator { _addAt2CsConnector(_account); } function renounceAt2CsConnector() public { _removeAt2CsConnector(msg.sender); } function _addAt2CsConnector(address _account) internal { at2csConnectors.add(_account); emit At2CsConnectorAdded(_account); } function removeAt2CsConnector(address _account) public onlyRootPlatformAdministrator { _removeAt2CsConnector(_account); } function _removeAt2CsConnector(address _account) internal { at2csConnectors.remove(_account); emit At2CsConnectorRemoved(_account); } } // File: openzeppelin-solidity/contracts/token/ERC20/IERC20.sol /** * @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); } // 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: openzeppelin-solidity/contracts/access/roles/MinterRole.sol 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); } } // File: openzeppelin-solidity/contracts/token/ERC20/ERC20Mintable.sol /** * @title ERC20Mintable * @dev ERC20 minting logic */ contract ERC20Mintable is ERC20, MinterRole { /** * @dev Function to mint tokens * @param to The address that will receive the minted tokens. * @param value The amount of tokens to mint. * @return A boolean that indicates if the operation was successful. */ function mint(address to, uint256 value) public onlyMinter returns (bool) { _mint(to, value); return true; } } // File: contracts/controller/0_library/DSMathL.sol // fork from ds-math specifically my librarization fork: https://raw.githubusercontent.com/JohannesMayerConda/ds-math/master/contracts/DSMathL.sol /// math.sol -- mixin for inline numerical wizardry // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. library DSMathL { function ds_add(uint x, uint y) public pure returns (uint z) { require((z = x + y) >= x, "ds-math-add-overflow"); } function ds_sub(uint x, uint y) public pure returns (uint z) { require((z = x - y) <= x, "ds-math-sub-underflow"); } function ds_mul(uint x, uint y) public pure returns (uint z) { require(y == 0 || (z = x * y) / y == x, "ds-math-mul-overflow"); } function ds_min(uint x, uint y) public pure returns (uint z) { return x <= y ? x : y; } function ds_max(uint x, uint y) public pure returns (uint z) { return x >= y ? x : y; } function ds_imin(int x, int y) public pure returns (int z) { return x <= y ? x : y; } function ds_imax(int x, int y) public pure returns (int z) { return x >= y ? x : y; } uint constant WAD = 10 ** 18; uint constant RAY = 10 ** 27; function ds_wmul(uint x, uint y) public pure returns (uint z) { z = ds_add(ds_mul(x, y), WAD / 2) / WAD; } function ds_rmul(uint x, uint y) public pure returns (uint z) { z = ds_add(ds_mul(x, y), RAY / 2) / RAY; } function ds_wdiv(uint x, uint y) public pure returns (uint z) { z = ds_add(ds_mul(x, WAD), y / 2) / y; } function ds_rdiv(uint x, uint y) public pure returns (uint z) { z = ds_add(ds_mul(x, RAY), y / 2) / y; } // This famous algorithm is called "exponentiation by squaring" // and calculates x^n with x as fixed-point and n as regular unsigned. // // It's O(log n), instead of O(n) for naive repeated multiplication. // // These facts are why it works: // // If n is even, then x^n = (x^2)^(n/2). // If n is odd, then x^n = x * x^(n-1), // and applying the equation for even x gives // x^n = x * (x^2)^((n-1) / 2). // // Also, EVM division is flooring and // floor[(n-1) / 2] = floor[n / 2]. // function ds_rpow(uint x, uint n) public pure returns (uint z) { z = n % 2 != 0 ? x : RAY; for (n /= 2; n != 0; n /= 2) { x = ds_rmul(x, x); if (n % 2 != 0) { z = ds_rmul(z, x); } } } } // File: contracts/controller/Permissions/YourOwnable.sol // 1:1 copy of https://raw.githubusercontent.com/OpenZeppelin/openzeppelin-solidity/v2.1.1/contracts/ownership/Ownable.sol // except constructor that can instantly transfer ownership contract YourOwnable { 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 (address newOwner) public { _transferOwnership(newOwner); } /** * @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; } } // File: contracts/controller/FeeTable/StandardFeeTable.sol /* Copyright 2018, CONDA This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ /** @title StandardFeeTable contract to store fees via name (fees per platform for certain name). */ contract StandardFeeTable is YourOwnable { using SafeMath for uint256; /////////////////// // Constructor /////////////////// constructor (address newOwner) YourOwnable(newOwner) public {} /////////////////// // Variables /////////////////// uint256 public defaultFee; mapping (bytes32 => uint256) public feeFor; mapping (bytes32 => bool) public isFeeDisabled; /////////////////// // Functions /////////////////// /// @notice Set default fee (when nothing else applies). /// @param _defaultFee default fee value. Unit is WAD so fee 1 means value=1e18. function setDefaultFee(uint256 _defaultFee) public onlyOwner { defaultFee = _defaultFee; } /// @notice Set fee by name. /// @param _feeName fee name. /// @param _feeValue fee value. Unit is WAD so fee 1 means value=1e18. function setFee(bytes32 _feeName, uint256 _feeValue) public onlyOwner { feeFor[_feeName] = _feeValue; } /// @notice Enable or disable fee by name. /// @param _feeName fee name. /// @param _feeDisabled true if fee should be disabled. function setFeeMode(bytes32 _feeName, bool _feeDisabled) public onlyOwner { isFeeDisabled[_feeName] = _feeDisabled; } /// @notice Get standard fee (not overriden by special fee for specific AssetToken). /// @param _feeName fee name. /// @return fee value. Unit is WAD so fee 1 means value=1e18. function getStandardFee(bytes32 _feeName) public view returns (uint256 _feeValue) { if (isFeeDisabled[_feeName]) { return 0; } if(feeFor[_feeName] == 0) { return defaultFee; } return feeFor[_feeName]; } /// @notice Get standard fee for amount in base unit. /// @param _feeName fee name. /// @param _amountInFeeBaseUnit amount in fee base unit (currently in unit tokens). /// @return fee value. Unit is WAD (converted it). function getStandardFeeFor(bytes32 _feeName, uint256 _amountInFeeBaseUnit) public view returns (uint256) { //1000000000000000 is 0,001 as WAD //example fee 0.001 for amount 3: 3 tokens * 1000000000000000 fee = 3000000000000000 (0.003) return _amountInFeeBaseUnit.mul(getStandardFee(_feeName)); } } // File: contracts/controller/FeeTable/FeeTable.sol /* Copyright 2018, CONDA This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ /** @title FeeTable contract to store fees via name (fees per platform per assettoken for certain name). */ contract FeeTable is StandardFeeTable { /////////////////// // Constructor /////////////////// constructor (address newOwner) StandardFeeTable(newOwner) public {} /////////////////// // Mappings /////////////////// // specialfee mapping feeName -> token -> fee mapping (bytes32 => mapping (address => uint256)) public specialFeeFor; // specialfee mapping feeName -> token -> isSet mapping (bytes32 => mapping (address => bool)) public isSpecialFeeEnabled; /////////////////// // Functions /////////////////// /// @notice Set a special fee specifically for an AssetToken (higher or lower than normal fee). /// @param _feeName fee name. /// @param _regardingAssetToken regarding AssetToken. /// @param _feeValue fee value. Unit is WAD so fee 1 means value=1e18. function setSpecialFee(bytes32 _feeName, address _regardingAssetToken, uint256 _feeValue) public onlyOwner { specialFeeFor[_feeName][_regardingAssetToken] = _feeValue; } /// @notice Enable or disable special fee. /// @param _feeName fee name. /// @param _regardingAssetToken regarding AssetToken. /// @param _feeEnabled true to enable fee. function setSpecialFeeMode(bytes32 _feeName, address _regardingAssetToken, bool _feeEnabled) public onlyOwner { isSpecialFeeEnabled[_feeName][_regardingAssetToken] = _feeEnabled; } /// @notice Get fee by name. /// @param _feeName fee name. /// @param _regardingAssetToken regarding AssetToken. /// @return fee value. Unit is WAD so fee 11 means value=1e18. function getFee(bytes32 _feeName, address _regardingAssetToken) public view returns (uint256) { if (isFeeDisabled[_feeName]) { return 0; } if (isSpecialFeeEnabled[_feeName][_regardingAssetToken]) { return specialFeeFor[_feeName][_regardingAssetToken]; } return super.getStandardFee(_feeName); } /// @notice Get fee for amount in base unit. /// @param _feeName fee name. /// @param _regardingAssetToken regarding AssetToken. /// @param _amountInFeeBaseUnit amount in fee base unit (currently in unit tokens). /// @return fee value. Unit is WAD (converted it). function getFeeFor(bytes32 _feeName, address _regardingAssetToken, uint256 _amountInFeeBaseUnit, address /*oracle*/) public view returns (uint256) { uint256 fee = getFee(_feeName, _regardingAssetToken); //1000000000000000 is 0,001 as WAD //example fee 0.001 for amount 3: 3 tokens * 1000000000000000 fee = 3000000000000000 (0.003) return _amountInFeeBaseUnit.mul(fee); } } // File: contracts/controller/Permissions/WhitelistControlRole.sol /* Copyright 2018, CONDA This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ /** @title WhitelistControlRole role to administrate whitelist and KYC. */ contract WhitelistControlRole is RootPlatformAdministratorRole { /////////////////// // Events /////////////////// event WhitelistControlAdded(address indexed account); event WhitelistControlRemoved(address indexed account); /////////////////// // Variables /////////////////// Roles.Role private whitelistControllers; /////////////////// // Constructor /////////////////// constructor() internal { _addWhitelistControl(msg.sender); } /////////////////// // Modifiers /////////////////// modifier onlyWhitelistControl() { require(isWhitelistControl(msg.sender), "no WLcontrol"); _; } /////////////////// // Functions /////////////////// function isWhitelistControl(address account) public view returns (bool) { return whitelistControllers.has(account); } function addWhitelistControl(address account) public onlyRootPlatformAdministrator { _addWhitelistControl(account); } function _addWhitelistControl(address account) internal { whitelistControllers.add(account); emit WhitelistControlAdded(account); } function removeWhitelistControl(address account) public onlyRootPlatformAdministrator { whitelistControllers.remove(account); emit WhitelistControlRemoved(account); } } // File: contracts/controller/interface/IWhitelistAutoExtendExpirationExecutor.sol interface IWhitelistAutoExtendExpirationExecutor { function recheckIdentity(address _wallet, address _investorKey, address _issuer) external; } // File: contracts/controller/interface/IWhitelistAutoExtendExpirationCallback.sol interface IWhitelistAutoExtendExpirationCallback { function updateIdentity(address _wallet, bool _isWhitelisted, address _investorKey, address _issuer) external; } // File: contracts/controller/Whitelist/Whitelist.sol /** @title Whitelist stores whitelist information of investors like if and when they were KYC checked. */ contract Whitelist is WhitelistControlRole, IWhitelistAutoExtendExpirationCallback { using SafeMath for uint256; /////////////////// // Variables /////////////////// uint256 public expirationBlocks; bool public expirationEnabled; bool public autoExtendExpiration; address public autoExtendExpirationContract; mapping (address => bool) whitelistedWallet; mapping (address => uint256) lastIdentityVerificationDate; mapping (address => address) whitelistedWalletIssuer; mapping (address => address) walletToInvestorKey; /////////////////// // Events /////////////////// event WhitelistChanged(address indexed wallet, bool whitelisted, address investorKey, address issuer); event ExpirationBlocksChanged(address initiator, uint256 addedBlocksSinceWhitelisting); event ExpirationEnabled(address initiator, bool expirationEnabled); event UpdatedIdentity(address initiator, address indexed wallet, bool whitelisted, address investorKey, address issuer); event SetAutoExtendExpirationContract(address initiator, address expirationContract); event UpdatedAutoExtendExpiration(address initiator, bool autoExtendEnabled); /////////////////// // Functions /////////////////// function getIssuer(address _whitelistedWallet) public view returns (address) { return whitelistedWalletIssuer[_whitelistedWallet]; } function getInvestorKey(address _wallet) public view returns (address) { return walletToInvestorKey[_wallet]; } function setWhitelisted(address _wallet, bool _isWhitelisted, address _investorKey, address _issuer) public onlyWhitelistControl { whitelistedWallet[_wallet] = _isWhitelisted; lastIdentityVerificationDate[_wallet] = block.number; whitelistedWalletIssuer[_wallet] = _issuer; assignWalletToInvestorKey(_wallet, _investorKey); emit WhitelistChanged(_wallet, _isWhitelisted, _investorKey, _issuer); } function assignWalletToInvestorKey(address _wallet, address _investorKey) public onlyWhitelistControl { walletToInvestorKey[_wallet] = _investorKey; } //note: no view keyword here because IWhitelistAutoExtendExpirationExecutor could change state via callback function checkWhitelistedWallet(address _wallet) public returns (bool) { if(autoExtendExpiration && isExpired(_wallet)) { address investorKey = walletToInvestorKey[_wallet]; address issuer = whitelistedWalletIssuer[_wallet]; require(investorKey != address(0), "expired, unknown identity"); //IMPORTANT: reentrance hook. make sure calling contract is safe IWhitelistAutoExtendExpirationExecutor(autoExtendExpirationContract).recheckIdentity(_wallet, investorKey, issuer); } require(!isExpired(_wallet), "whitelist expired"); require(whitelistedWallet[_wallet], "not whitelisted"); return true; } function isWhitelistedWallet(address _wallet) public view returns (bool) { if(isExpired(_wallet)) { return false; } return whitelistedWallet[_wallet]; } function isExpired(address _wallet) private view returns (bool) { return expirationEnabled && block.number > lastIdentityVerificationDate[_wallet].add(expirationBlocks); } function blocksLeftUntilExpired(address _wallet) public view returns (uint256) { require(expirationEnabled, "expiration disabled"); return lastIdentityVerificationDate[_wallet].add(expirationBlocks).sub(block.number); } function setExpirationBlocks(uint256 _addedBlocksSinceWhitelisting) public onlyRootPlatformAdministrator { expirationBlocks = _addedBlocksSinceWhitelisting; emit ExpirationBlocksChanged(msg.sender, _addedBlocksSinceWhitelisting); } function setExpirationEnabled(bool _isEnabled) public onlyRootPlatformAdministrator { expirationEnabled = _isEnabled; emit ExpirationEnabled(msg.sender, expirationEnabled); } function setAutoExtendExpirationContract(address _autoExtendContract) public onlyRootPlatformAdministrator { autoExtendExpirationContract = _autoExtendContract; emit SetAutoExtendExpirationContract(msg.sender, _autoExtendContract); } function setAutoExtendExpiration(bool _autoExtendEnabled) public onlyRootPlatformAdministrator { autoExtendExpiration = _autoExtendEnabled; emit UpdatedAutoExtendExpiration(msg.sender, _autoExtendEnabled); } function updateIdentity(address _wallet, bool _isWhitelisted, address _investorKey, address _issuer) public onlyWhitelistControl { setWhitelisted(_wallet, _isWhitelisted, _investorKey, _issuer); emit UpdatedIdentity(msg.sender, _wallet, _isWhitelisted, _investorKey, _issuer); } } // File: contracts/controller/interface/IExchangeRateOracle.sol contract IExchangeRateOracle { function resetCurrencyPair(address _currencyA, address _currencyB) public; function configureCurrencyPair(address _currencyA, address _currencyB, uint256 maxNextUpdateInBlocks) public; function setExchangeRate(address _currencyA, address _currencyB, uint256 _rateFromTo, uint256 _rateToFrom) public; function getExchangeRate(address _currencyA, address _currencyB) public view returns (uint256); function convert(address _currencyA, address _currencyB, uint256 _amount) public view returns (uint256); function convertTT(bytes32 _currencyAText, bytes32 _currencyBText, uint256 _amount) public view returns (uint256); function convertTA(bytes32 _currencyAText, address _currencyB, uint256 _amount) public view returns (uint256); function convertAT(address _currencyA, bytes32 _currencyBText, uint256 _amount) public view returns (uint256); } // 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 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: contracts/controller/interfaces/IBasicAssetToken.sol interface IBasicAssetToken { //AssetToken specific function isTokenAlive() external view returns (bool); //Mintable function mint(address _to, uint256 _amount) external returns (bool); function finishMinting() external returns (bool); } // File: contracts/controller/Permissions/StorageAdministratorRole.sol /* Copyright 2018, CONDA This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ /** @title StorageAdministratorRole role to administrate generic storage. */ contract StorageAdministratorRole is RootPlatformAdministratorRole { /////////////////// // Events /////////////////// event StorageAdministratorAdded(address indexed account); event StorageAdministratorRemoved(address indexed account); /////////////////// // Variables /////////////////// Roles.Role private storageAdministrators; /////////////////// // Constructor /////////////////// constructor() internal { _addStorageAdministrator(msg.sender); } /////////////////// // Modifiers /////////////////// modifier onlyStorageAdministrator() { require(isStorageAdministrator(msg.sender), "no SAdmin"); _; } /////////////////// // Functions /////////////////// function isStorageAdministrator(address account) public view returns (bool) { return storageAdministrators.has(account); } function addStorageAdministrator(address account) public onlyRootPlatformAdministrator { _addStorageAdministrator(account); } function _addStorageAdministrator(address account) internal { storageAdministrators.add(account); emit StorageAdministratorAdded(account); } function removeStorageAdministrator(address account) public onlyRootPlatformAdministrator { storageAdministrators.remove(account); emit StorageAdministratorRemoved(account); } } // File: contracts/controller/Storage/storagetypes/UintStorage.sol /* Copyright 2018, CONDA This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ /** @title UintStorage uint storage. */ contract UintStorage is StorageAdministratorRole { /////////////////// // Mappings /////////////////// mapping (bytes32 => uint256) private uintStorage; /////////////////// // Functions /////////////////// function setUint(bytes32 _name, uint256 _value) public onlyStorageAdministrator { return _setUint(_name, _value); } function getUint(bytes32 _name) public view returns (uint256) { return _getUint(_name); } function _setUint(bytes32 _name, uint256 _value) private { if(_name != "") { uintStorage[_name] = _value; } } function _getUint(bytes32 _name) private view returns (uint256) { return uintStorage[_name]; } function get2Uint( bytes32 _name1, bytes32 _name2) public view returns (uint256, uint256) { return (_getUint(_name1), _getUint(_name2)); } function get3Uint( bytes32 _name1, bytes32 _name2, bytes32 _name3) public view returns (uint256, uint256, uint256) { return (_getUint(_name1), _getUint(_name2), _getUint(_name3)); } function get4Uint( bytes32 _name1, bytes32 _name2, bytes32 _name3, bytes32 _name4) public view returns (uint256, uint256, uint256, uint256) { return (_getUint(_name1), _getUint(_name2), _getUint(_name3), _getUint(_name4)); } function get5Uint( bytes32 _name1, bytes32 _name2, bytes32 _name3, bytes32 _name4, bytes32 _name5) public view returns (uint256, uint256, uint256, uint256, uint256) { return (_getUint(_name1), _getUint(_name2), _getUint(_name3), _getUint(_name4), _getUint(_name5)); } function set2Uint( bytes32 _name1, uint256 _value1, bytes32 _name2, uint256 _value2) public onlyStorageAdministrator { _setUint(_name1, _value1); _setUint(_name2, _value2); } function set3Uint( bytes32 _name1, uint256 _value1, bytes32 _name2, uint256 _value2, bytes32 _name3, uint256 _value3) public onlyStorageAdministrator { _setUint(_name1, _value1); _setUint(_name2, _value2); _setUint(_name3, _value3); } function set4Uint( bytes32 _name1, uint256 _value1, bytes32 _name2, uint256 _value2, bytes32 _name3, uint256 _value3, bytes32 _name4, uint256 _value4) public onlyStorageAdministrator { _setUint(_name1, _value1); _setUint(_name2, _value2); _setUint(_name3, _value3); _setUint(_name4, _value4); } function set5Uint( bytes32 _name1, uint256 _value1, bytes32 _name2, uint256 _value2, bytes32 _name3, uint256 _value3, bytes32 _name4, uint256 _value4, bytes32 _name5, uint256 _value5) public onlyStorageAdministrator { _setUint(_name1, _value1); _setUint(_name2, _value2); _setUint(_name3, _value3); _setUint(_name4, _value4); _setUint(_name5, _value5); } } // File: contracts/controller/Storage/storagetypes/AddrStorage.sol /* Copyright 2018, CONDA This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ /** @title AddrStorage address storage. */ contract AddrStorage is StorageAdministratorRole { /////////////////// // Mappings /////////////////// mapping (bytes32 => address) private addrStorage; /////////////////// // Functions /////////////////// function setAddr(bytes32 _name, address _value) public onlyStorageAdministrator { return _setAddr(_name, _value); } function getAddr(bytes32 _name) public view returns (address) { return _getAddr(_name); } function _setAddr(bytes32 _name, address _value) private { if(_name != "") { addrStorage[_name] = _value; } } function _getAddr(bytes32 _name) private view returns (address) { return addrStorage[_name]; } function get2Address( bytes32 _name1, bytes32 _name2) public view returns (address, address) { return (_getAddr(_name1), _getAddr(_name2)); } function get3Address( bytes32 _name1, bytes32 _name2, bytes32 _name3) public view returns (address, address, address) { return (_getAddr(_name1), _getAddr(_name2), _getAddr(_name3)); } function set2Address( bytes32 _name1, address _value1, bytes32 _name2, address _value2) public onlyStorageAdministrator { _setAddr(_name1, _value1); _setAddr(_name2, _value2); } function set3Address( bytes32 _name1, address _value1, bytes32 _name2, address _value2, bytes32 _name3, address _value3) public onlyStorageAdministrator { _setAddr(_name1, _value1); _setAddr(_name2, _value2); _setAddr(_name3, _value3); } } // File: contracts/controller/Storage/storagetypes/Addr2UintStorage.sol /* Copyright 2018, CONDA This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ /** @title Addr2UintStorage address to uint mapping storage. */ contract Addr2UintStorage is StorageAdministratorRole { /////////////////// // Mappings /////////////////// mapping (bytes32 => mapping (address => uint256)) private addr2UintStorage; /////////////////// // Functions /////////////////// function setAddr2Uint(bytes32 _name, address _address, uint256 _value) public onlyStorageAdministrator { return _setAddr2Uint(_name, _address, _value); } function getAddr2Uint(bytes32 _name, address _address) public view returns (uint256) { return _getAddr2Uint(_name, _address); } function _setAddr2Uint(bytes32 _name, address _address, uint256 _value) private { if(_name != "") { addr2UintStorage[_name][_address] = _value; } } function _getAddr2Uint(bytes32 _name, address _address) private view returns (uint256) { return addr2UintStorage[_name][_address]; } function get2Addr2Uint( bytes32 _name1, address _address1, bytes32 _name2, address _address2) public view returns (uint256, uint256) { return (_getAddr2Uint(_name1, _address1), _getAddr2Uint(_name2, _address2)); } function get3Addr2Addr2Uint( bytes32 _name1, address _address1, bytes32 _name2, address _address2, bytes32 _name3, address _address3) public view returns (uint256, uint256, uint256) { return (_getAddr2Uint(_name1, _address1), _getAddr2Uint(_name2, _address2), _getAddr2Uint(_name3, _address3)); } function set2Addr2Uint( bytes32 _name1, address _address1, uint256 _value1, bytes32 _name2, address _address2, uint256 _value2) public onlyStorageAdministrator { _setAddr2Uint(_name1, _address1, _value1); _setAddr2Uint(_name2, _address2, _value2); } function set3Addr2Uint( bytes32 _name1, address _address1, uint256 _value1, bytes32 _name2, address _address2, uint256 _value2, bytes32 _name3, address _address3, uint256 _value3) public onlyStorageAdministrator { _setAddr2Uint(_name1, _address1, _value1); _setAddr2Uint(_name2, _address2, _value2); _setAddr2Uint(_name3, _address3, _value3); } } // File: contracts/controller/Storage/storagetypes/Addr2AddrStorage.sol /* Copyright 2018, CONDA This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ /** @title Addr2AddrStorage address to address mapping storage. */ contract Addr2AddrStorage is StorageAdministratorRole { /////////////////// // Mappings /////////////////// mapping (bytes32 => mapping (address => address)) private addr2AddrStorage; /////////////////// // Functions /////////////////// function setAddr2Addr(bytes32 _name, address _address, address _value) public onlyStorageAdministrator { return _setAddr2Addr(_name, _address, _value); } function getAddr2Addr(bytes32 _name, address _address) public view returns (address) { return _getAddr2Addr(_name, _address); } function _setAddr2Addr(bytes32 _name, address _address, address _value) private { if(_name != "") { addr2AddrStorage[_name][_address] = _value; } } function _getAddr2Addr(bytes32 _name, address _address) private view returns (address) { return addr2AddrStorage[_name][_address]; } function get2Addr2Addr( bytes32 _name1, address _address1, bytes32 _name2, address _address2) public view returns (address, address) { return (_getAddr2Addr(_name1, _address1), _getAddr2Addr(_name2, _address2)); } function get3Addr2Addr2Addr( bytes32 _name1, address _address1, bytes32 _name2, address _address2, bytes32 _name3, address _address3) public view returns (address, address, address) { return (_getAddr2Addr(_name1, _address1), _getAddr2Addr(_name2, _address2), _getAddr2Addr(_name3, _address3)); } function set2Addr2Addr( bytes32 _name1, address _address1, address _value1, bytes32 _name2, address _address2, address _value2) public onlyStorageAdministrator { _setAddr2Addr(_name1, _address1, _value1); _setAddr2Addr(_name2, _address2, _value2); } function set3Addr2Addr( bytes32 _name1, address _address1, address _value1, bytes32 _name2, address _address2, address _value2, bytes32 _name3, address _address3, address _value3) public onlyStorageAdministrator { _setAddr2Addr(_name1, _address1, _value1); _setAddr2Addr(_name2, _address2, _value2); _setAddr2Addr(_name3, _address3, _value3); } } // File: contracts/controller/Storage/storagetypes/Addr2BoolStorage.sol /* Copyright 2018, CONDA This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ /** @title Addr2BoolStorage address to address mapping storage. */ contract Addr2BoolStorage is StorageAdministratorRole { /////////////////// // Mappings /////////////////// mapping (bytes32 => mapping (address => bool)) private addr2BoolStorage; /////////////////// // Functions /////////////////// function setAddr2Bool(bytes32 _name, address _address, bool _value) public onlyStorageAdministrator { return _setAddr2Bool(_name, _address, _value); } function getAddr2Bool(bytes32 _name, address _address) public view returns (bool) { return _getAddr2Bool(_name, _address); } function _setAddr2Bool(bytes32 _name, address _address, bool _value) private { if(_name != "") { addr2BoolStorage[_name][_address] = _value; } } function _getAddr2Bool(bytes32 _name, address _address) private view returns (bool) { return addr2BoolStorage[_name][_address]; } function get2Addr2Bool( bytes32 _name1, address _address1, bytes32 _name2, address _address2) public view returns (bool, bool) { return (_getAddr2Bool(_name1, _address1), _getAddr2Bool(_name2, _address2)); } function get3Address2Address2Bool( bytes32 _name1, address _address1, bytes32 _name2, address _address2, bytes32 _name3, address _address3) public view returns (bool, bool, bool) { return (_getAddr2Bool(_name1, _address1), _getAddr2Bool(_name2, _address2), _getAddr2Bool(_name3, _address3)); } function set2Address2Bool( bytes32 _name1, address _address1, bool _value1, bytes32 _name2, address _address2, bool _value2) public onlyStorageAdministrator { _setAddr2Bool(_name1, _address1, _value1); _setAddr2Bool(_name2, _address2, _value2); } function set3Address2Bool( bytes32 _name1, address _address1, bool _value1, bytes32 _name2, address _address2, bool _value2, bytes32 _name3, address _address3, bool _value3) public onlyStorageAdministrator { _setAddr2Bool(_name1, _address1, _value1); _setAddr2Bool(_name2, _address2, _value2); _setAddr2Bool(_name3, _address3, _value3); } } // File: contracts/controller/Storage/storagetypes/BytesStorage.sol /* Copyright 2018, CONDA This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ /** @title BytesStorage bytes storage. */ contract BytesStorage is StorageAdministratorRole { /////////////////// // Mappings /////////////////// mapping (bytes32 => bytes32) private bytesStorage; /////////////////// // Functions /////////////////// function setBytes(bytes32 _name, bytes32 _value) public onlyStorageAdministrator { return _setBytes(_name, _value); } function getBytes(bytes32 _name) public view returns (bytes32) { return _getBytes(_name); } function _setBytes(bytes32 _name, bytes32 _value) private { if(_name != "") { bytesStorage[_name] = _value; } } function _getBytes(bytes32 _name) private view returns (bytes32) { return bytesStorage[_name]; } function get2Bytes( bytes32 _name1, bytes32 _name2) public view returns (bytes32, bytes32) { return (_getBytes(_name1), _getBytes(_name2)); } function get3Bytes( bytes32 _name1, bytes32 _name2, bytes32 _name3) public view returns (bytes32, bytes32, bytes32) { return (_getBytes(_name1), _getBytes(_name2), _getBytes(_name3)); } function set2Bytes( bytes32 _name1, bytes32 _value1, bytes32 _name2, bytes32 _value2) public onlyStorageAdministrator { _setBytes(_name1, _value1); _setBytes(_name2, _value2); } function set3Bytes( bytes32 _name1, bytes32 _value1, bytes32 _name2, bytes32 _value2, bytes32 _name3, bytes32 _value3) public onlyStorageAdministrator { _setBytes(_name1, _value1); _setBytes(_name2, _value2); _setBytes(_name3, _value3); } } // File: contracts/controller/Storage/storagetypes/Addr2AddrArrStorage.sol /* Copyright 2018, CONDA This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ /** @title Addr2AddrArrStorage address to address array mapping storage. */ contract Addr2AddrArrStorage is StorageAdministratorRole { /////////////////// // Mappings /////////////////// mapping (bytes32 => mapping (address => address[])) private addr2AddrArrStorage; /////////////////// // Functions /////////////////// function addToAddr2AddrArr(bytes32 _name, address _address, address _value) public onlyStorageAdministrator { addr2AddrArrStorage[_name][_address].push(_value); } function getAddr2AddrArr(bytes32 _name, address _address) public view returns (address[] memory) { return addr2AddrArrStorage[_name][_address]; } } // File: contracts/controller/Storage/storagetypes/StorageHolder.sol /* Copyright 2018, CONDA This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ /** @title StorageHolder holds the fine-grained generic storage functions. */ contract StorageHolder is UintStorage, BytesStorage, AddrStorage, Addr2UintStorage, Addr2BoolStorage, Addr2AddrStorage, Addr2AddrArrStorage { /////////////////// // Functions /////////////////// function getMixedUBA(bytes32 _uintName, bytes32 _bytesName, bytes32 _addressName) public view returns (uint256, bytes32, address) { return (getUint(_uintName), getBytes(_bytesName), getAddr(_addressName)); } function getMixedMapA2UA2BA2A( bytes32 _a2uName, address _a2uAddress, bytes32 _a2bName, address _a2bAddress, bytes32 _a2aName, address _a2aAddress) public view returns (uint256, bool, address) { return (getAddr2Uint(_a2uName, _a2uAddress), getAddr2Bool(_a2bName, _a2bAddress), getAddr2Addr(_a2aName, _a2aAddress)); } } // File: contracts/controller/Storage/AT2CSStorage.sol /* Copyright 2018, CONDA This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ /** @title AT2CSStorage AssetToken to Crowdsale storage (that is upgradeable). */ contract AT2CSStorage is StorageAdministratorRole { /////////////////// // Constructor /////////////////// constructor(address controllerStorage) public { storageHolder = StorageHolder(controllerStorage); } /////////////////// // Variables /////////////////// StorageHolder storageHolder; /////////////////// // Functions /////////////////// function getAssetTokenOfCrowdsale(address _crowdsale) public view returns (address) { return storageHolder.getAddr2Addr("cs2at", _crowdsale); } function getRateFromCrowdsale(address _crowdsale) public view returns (uint256) { address assetToken = storageHolder.getAddr2Addr("cs2at", _crowdsale); return getRateFromAssetToken(assetToken); } function getRateFromAssetToken(address _assetToken) public view returns (uint256) { require(_assetToken != address(0), "rate assetTokenIs0"); return storageHolder.getAddr2Uint("rate", _assetToken); } function getAssetTokenOwnerWalletFromCrowdsale(address _crowdsale) public view returns (address) { address assetToken = storageHolder.getAddr2Addr("cs2at", _crowdsale); return getAssetTokenOwnerWalletFromAssetToken(assetToken); } function getAssetTokenOwnerWalletFromAssetToken(address _assetToken) public view returns (address) { return storageHolder.getAddr2Addr("at2wallet", _assetToken); } function getAssetTokensOf(address _wallet) public view returns (address[] memory) { return storageHolder.getAddr2AddrArr("wallet2AT", _wallet); } function isAssignedCrowdsale(address _crowdsale) public view returns (bool) { return storageHolder.getAddr2Bool("isCS", _crowdsale); } function isTrustedAssetTokenRegistered(address _assetToken) public view returns (bool) { return storageHolder.getAddr2Bool("trustedAT", _assetToken); } function isTrustedAssetTokenActive(address _assetToken) public view returns (bool) { return storageHolder.getAddr2Bool("ATactive", _assetToken); } function checkTrustedAssetToken(address _assetToken) public view returns (bool) { require(storageHolder.getAddr2Bool("ATactive", _assetToken), "not trusted AT"); return true; } function checkTrustedCrowdsaleInternal(address _crowdsale) public view returns (bool) { address _assetTokenAddress = storageHolder.getAddr2Addr("cs2at", _crowdsale); require(storageHolder.getAddr2Bool("isCS", _crowdsale), "not registered CS"); require(checkTrustedAssetToken(_assetTokenAddress), "not trusted AT"); return true; } function changeActiveTrustedAssetToken(address _assetToken, bool _active) public onlyStorageAdministrator { storageHolder.setAddr2Bool("ATactive", _assetToken, _active); } function addTrustedAssetTokenInternal(address _ownerWallet, address _assetToken, uint256 _rate) public onlyStorageAdministrator { require(!storageHolder.getAddr2Bool("trustedAT", _assetToken), "exists"); require(ERC20Detailed(_assetToken).decimals() == 0, "decimal not 0"); storageHolder.setAddr2Bool("trustedAT", _assetToken, true); storageHolder.setAddr2Bool("ATactive", _assetToken, true); storageHolder.addToAddr2AddrArr("wallet2AT", _ownerWallet, _assetToken); storageHolder.setAddr2Addr("at2wallet", _assetToken, _ownerWallet); storageHolder.setAddr2Uint("rate", _assetToken, _rate); } function assignCrowdsale(address _assetToken, address _crowdsale) public onlyStorageAdministrator { require(storageHolder.getAddr2Bool("trustedAT", _assetToken), "no AT"); require(!storageHolder.getAddr2Bool("isCS", _crowdsale), "is assigned"); require(IBasicAssetToken(_assetToken).isTokenAlive(), "not alive"); require(ERC20Detailed(_assetToken).decimals() == 0, "decimal not 0"); storageHolder.setAddr2Bool("isCS", _crowdsale, true); storageHolder.setAddr2Addr("cs2at", _crowdsale, _assetToken); } function setAssetTokenRate(address _assetToken, uint256 _rate) public onlyStorageAdministrator { storageHolder.setAddr2Uint("rate", _assetToken, _rate); } } // File: contracts/controller/0_library/ControllerL.sol /* Copyright 2018, CONDA This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ /** @title ControllerL library. */ library ControllerL { using SafeMath for uint256; /////////////////// // Structs /////////////////// struct Data { // global flag fees enabled bool feesEnabled; // global flag whitelist enabled bool whitelistEnabled; // address of the crwd token (for fees etc.) address crwdToken; // root platform wallet (receives fees according to it's FeeTable) address rootPlatformAddress; // address of ExchangeRateOracle (converts e.g. ETH to EUR and vice versa) address exchangeRateOracle; // the address of the whitelist contract address whitelist; // the generic storage contract AT2CSStorage store; // global flag to prevent new AssetToken or crowdsales to be accepted (e.g. after upgrade). bool blockNew; // mapping of platform addresses that are trusted mapping ( address => bool ) trustedPlatform; //note: not easily upgradeable // mapping of platform addresses that are trusted mapping ( address => bool ) onceTrustedPlatform; //note: not easily upgradeable // mapping of crowdsale to platform wallet mapping ( address => address ) crowdsaleToPlatform; //note: not easily upgradeable // mapping from platform address to FeeTable mapping ( address => address ) platformToFeeTable; //note: not easily upgradeable } /////////////////// // Functions /////////////////// /// @dev Contant point multiplier because no decimals. function pointMultiplier() private pure returns (uint256) { return 1e18; } /// @notice Address of generic storage (for upgradability). function getStorageAddress(Data storage _self) public view returns (address) { return address(_self.store); } /// @notice Assign generic storage (for upgradability). /// @param _storage storage address. function assignStore(Data storage _self, address _storage) public { _self.store = AT2CSStorage(_storage); } /// @notice Get FeeTable for platform. /// @param _platform platform to find FeeTable for. /// @return address of FeeTable of platform. function getFeeTableAddressForPlatform(Data storage _self, address _platform) public view returns (address) { return _self.platformToFeeTable[_platform]; } /// @notice Get FeeTable for platform. /// @param _platform platform to find FeeTable for. /// @return address of FeeTable of platform. function getFeeTableForPlatform(Data storage _self, address _platform) private view returns (FeeTable) { return FeeTable(_self.platformToFeeTable[_platform]); } /// @notice Set exchange rate oracle address. /// @param _oracleAddress the address of the ExchangeRateOracle. function setExchangeRateOracle(Data storage _self, address _oracleAddress) public { _self.exchangeRateOracle = _oracleAddress; emit ExchangeRateOracleSet(msg.sender, _oracleAddress); } /// @notice Check if a wallet is whitelisted or fail. Also considers auto extend (if enabled). /// @param _wallet the wallet to check. function checkWhitelistedWallet(Data storage _self, address _wallet) public returns (bool) { require(Whitelist(_self.whitelist).checkWhitelistedWallet(_wallet), "not whitelist"); return true; } /// @notice Check if a wallet is whitelisted. /// @param _wallet the wallet to check. /// @return true if whitelisted. function isWhitelistedWallet(Data storage _self, address _wallet) public view returns (bool) { return Whitelist(_self.whitelist).isWhitelistedWallet(_wallet); } /// @notice Convert eth amount into base currency (EUR), apply exchange rate via oracle, apply rate for AssetToken. /// @param _crowdsale the crowdsale address. /// @param _amountInWei the amount desired to be converted into tokens. function convertEthToEurApplyRateGetTokenAmountFromCrowdsale( Data storage _self, address _crowdsale, uint256 _amountInWei) public view returns (uint256 _effectiveTokensNoDecimals, uint256 _overpaidEthWhenZeroDecimals) { uint256 amountInEur = convertEthToEur(_self, _amountInWei); uint256 tokens = DSMathL.ds_wmul(amountInEur, _self.store.getRateFromCrowdsale(_crowdsale)); _effectiveTokensNoDecimals = tokens.div(pointMultiplier()); _overpaidEthWhenZeroDecimals = convertEurToEth(_self, DSMathL.ds_wdiv(tokens.sub(_effectiveTokensNoDecimals.mul(pointMultiplier())), _self.store.getRateFromCrowdsale(_crowdsale))); return (_effectiveTokensNoDecimals, _overpaidEthWhenZeroDecimals); } /// @notice Checks if a crowdsale is trusted or fail. /// @param _crowdsale the address of the crowdsale. /// @return true if trusted. function checkTrustedCrowdsale(Data storage _self, address _crowdsale) public view returns (bool) { require(checkTrustedPlatform(_self, _self.crowdsaleToPlatform[_crowdsale]), "not trusted PF0"); require(_self.store.checkTrustedCrowdsaleInternal(_crowdsale), "not trusted CS1"); return true; } /// @notice Checks if a AssetToken is trusted or fail. /// @param _assetToken the address of the AssetToken. /// @return true if trusted. function checkTrustedAssetToken(Data storage _self, address _assetToken) public view returns (bool) { //here just a minimal check for active (simple check on transfer). require(_self.store.checkTrustedAssetToken(_assetToken), "untrusted AT"); return true; } /// @notice Checks if a platform is certified or fail. /// @param _platformWallet wallet of platform. /// @return true if trusted. function checkTrustedPlatform(Data storage _self, address _platformWallet) public view returns (bool) { require(isTrustedPlatform(_self, _platformWallet), "not trusted PF3"); return true; } /// @notice Checks if a platform is certified. /// @param _platformWallet wallet of platform. /// @return true if certified. function isTrustedPlatform(Data storage _self, address _platformWallet) public view returns (bool) { return _self.trustedPlatform[_platformWallet]; } /// @notice Add trusted AssetToken. /// @param _ownerWallet requires CRWD for fees, receives ETH on successful campaign. /// @param _rate the rate of tokens per basecurrency (currently EUR). function addTrustedAssetToken(Data storage _self, address _ownerWallet, address _assetToken, uint256 _rate) public { require(!_self.blockNew, "blocked. newest version?"); _self.store.addTrustedAssetTokenInternal(_ownerWallet, _assetToken, _rate); emit AssetTokenAdded(msg.sender, _ownerWallet, _assetToken, _rate); } /// @notice assign a crowdsale to an AssetToken. /// @param _assetToken the AssetToken being sold. /// @param _crowdsale the crowdsale that takes ETH (if enabled) and triggers assignment of tokens. /// @param _platformWallet the wallet of the platform. Fees are paid to this address. function assignCrowdsale(Data storage _self, address _assetToken, address _crowdsale, address _platformWallet) public { require(!_self.blockNew, "blocked. newest version?"); checkTrustedPlatform(_self, _platformWallet); _self.store.assignCrowdsale(_assetToken, _crowdsale); _self.crowdsaleToPlatform[_crowdsale] = _platformWallet; emit CrowdsaleAssigned(msg.sender, _assetToken, _crowdsale, _platformWallet); } /// @notice Can change the state of an AssetToken (e.g. blacklist for legal reasons) /// @param _assetToken the AssetToken to change state. /// @param _active the state. True means active. /// @return True if successful. function changeActiveTrustedAssetToken(Data storage _self, address _assetToken, bool _active) public returns (bool) { _self.store.changeActiveTrustedAssetToken(_assetToken, _active); emit AssetTokenChangedActive(msg.sender, _assetToken, _active); } /// @notice Function to call on buy request. /// @param _to beneficiary of tokens. /// @param _amountInWei the invested ETH amount (unit WEI). function buyFromCrowdsale( Data storage _self, address _to, uint256 _amountInWei) public returns (uint256 _tokensCreated, uint256 _overpaidRefund) { (uint256 effectiveTokensNoDecimals, uint256 overpaidEth) = convertEthToEurApplyRateGetTokenAmountFromCrowdsale( _self, msg.sender, _amountInWei); checkValidTokenAssignmentFromCrowdsale(_self, _to); payFeeFromCrowdsale(_self, effectiveTokensNoDecimals); _tokensCreated = doTokenAssignment(_self, _to, effectiveTokensNoDecimals, msg.sender); return (_tokensCreated, overpaidEth); } /// @notice Assign tokens. /// @dev Pure assignment without e.g. rate calculation. /// @param _to beneficiary of tokens. /// @param _tokensToMint amount of tokens beneficiary receives. /// @return amount of tokens being created. function assignFromCrowdsale(Data storage _self, address _to, uint256 _tokensToMint) public returns (uint256 _tokensCreated) { checkValidTokenAssignmentFromCrowdsale(_self, _to); payFeeFromCrowdsale(_self, _tokensToMint); _tokensCreated = doTokenAssignment(_self, _to, _tokensToMint, msg.sender); return _tokensCreated; } /// @dev Token assignment logic. /// @param _to beneficiary of tokens. /// @param _tokensToMint amount of tokens beneficiary receives. /// @param _crowdsale being used. /// @return amount of tokens being created. function doTokenAssignment( Data storage _self, address _to, uint256 _tokensToMint, address _crowdsale) private returns (uint256 _tokensCreated) { address assetToken = _self.store.getAssetTokenOfCrowdsale(_crowdsale); require(assetToken != address(0), "assetTokenIs0"); ERC20Mintable(assetToken).mint(_to, _tokensToMint); return _tokensToMint; } /// @notice Pay fee on calls from crowdsale. /// @param _tokensToMint tokens being created. function payFeeFromCrowdsale(Data storage _self, uint256 _tokensToMint) private { if (_self.feesEnabled) { address ownerAssetTokenWallet = _self.store.getAssetTokenOwnerWalletFromCrowdsale(msg.sender); payFeeKnowingCrowdsale(_self, msg.sender, ownerAssetTokenWallet, _tokensToMint, "investorInvests"); } } /// @notice Check if token assignment is valid and e.g. crowdsale is trusted and investor KYC checked. /// @param _to beneficiary. function checkValidTokenAssignmentFromCrowdsale(Data storage _self, address _to) private { require(checkTrustedCrowdsale(_self, msg.sender), "untrusted source1"); if (_self.whitelistEnabled) { checkWhitelistedWallet(_self, _to); } } /// @notice Pay fee on controller call from Crowdsale. /// @param _crowdsale the calling Crowdsale contract. /// @param _ownerAssetToken the AssetToken of the owner. /// @param _tokensToMint the tokens being created. /// @param _feeName the name of the fee (key in mapping). function payFeeKnowingCrowdsale( Data storage _self, address _crowdsale, address _ownerAssetToken, uint256 _tokensToMint, //tokensToMint requires precalculations and is base for fees bytes32 _feeName) private { address platform = _self.crowdsaleToPlatform[_crowdsale]; uint256 feePromilleRootPlatform = getFeeKnowingCrowdsale( _self, _crowdsale, getFeeTableAddressForPlatform(_self, _self.rootPlatformAddress), _tokensToMint, false, _feeName); payWithCrwd(_self, _ownerAssetToken, _self.rootPlatformAddress, feePromilleRootPlatform); if(platform != _self.rootPlatformAddress) { address feeTable = getFeeTableAddressForPlatform(_self, platform); require(feeTable != address(0), "FeeTbl 0 addr"); uint256 feePromillePlatform = getFeeKnowingCrowdsale(_self, _crowdsale, feeTable, _tokensToMint, false, _feeName); payWithCrwd(_self, _ownerAssetToken, platform, feePromillePlatform); } } /// @notice Pay fee on controller call from AssetToken. /// @param _assetToken the calling AssetToken contract. /// @param _initiator the initiator passed through as parameter by AssetToken. /// @param _tokensToMint the tokens being handled. /// @param _feeName the name of the fee (key in mapping). function payFeeKnowingAssetToken( Data storage _self, address _assetToken, address _initiator, uint256 _tokensToMint, //tokensToMint requires precalculations and is base for fees bytes32 _feeName) public { uint256 feePromille = getFeeKnowingAssetToken( _self, _assetToken, _initiator, _tokensToMint, _feeName); payWithCrwd(_self, _initiator, _self.rootPlatformAddress, feePromille); } /// @dev this function in the end does the fee payment in CRWD. function payWithCrwd(Data storage _self, address _from, address _to, uint256 _value) private { if(_value > 0 && _from != _to) { ERC20Mintable(_self.crwdToken).transferFrom(_from, _to, _value); emit FeesPaid(_from, _to, _value); } } /// @notice Current conversion of ETH to EUR via oracle. /// @param _weiAmount the ETH amount (uint WEI). /// @return amount converted in euro. function convertEthToEur(Data storage _self, uint256 _weiAmount) public view returns (uint256) { require(_self.exchangeRateOracle != address(0), "no oracle"); return IExchangeRateOracle(_self.exchangeRateOracle).convertTT("ETH", "EUR", _weiAmount); } /// @notice Current conversion of EUR to ETH via oracle. /// @param _eurAmount the EUR amount /// @return amount converted in eth (formatted like WEI) function convertEurToEth(Data storage _self, uint256 _eurAmount) public view returns (uint256) { require(_self.exchangeRateOracle != address(0), "no oracle"); return IExchangeRateOracle(_self.exchangeRateOracle).convertTT("EUR", "ETH", _eurAmount); } /// @notice Get fee that needs to be paid for certain Crowdsale and FeeName. /// @param _crowdsale the Crowdsale being used. /// @param _feeTableAddr the address of the feetable. /// @param _amountInTokensOrEth the amount in tokens or pure ETH when conversion parameter true. /// @param _amountRequiresConversion when true amount parameter is converted from ETH into tokens. /// @param _feeName the name of the fee being paid. /// @return amount of fees that would/will be paid. function getFeeKnowingCrowdsale( Data storage _self, address _crowdsale, address _feeTableAddr, uint256 _amountInTokensOrEth, bool _amountRequiresConversion, bytes32 _feeName) public view returns (uint256) { uint256 tokens = _amountInTokensOrEth; if(_amountRequiresConversion) { (tokens, ) = convertEthToEurApplyRateGetTokenAmountFromCrowdsale(_self, _crowdsale, _amountInTokensOrEth); } FeeTable feeTable = FeeTable(_feeTableAddr); address assetTokenOfCrowdsale = _self.store.getAssetTokenOfCrowdsale(_crowdsale); return feeTable.getFeeFor(_feeName, assetTokenOfCrowdsale, tokens, _self.exchangeRateOracle); } /// @notice Get fee that needs to be paid for certain AssetToken and FeeName. /// @param _assetToken the AssetToken being used. /// @param _tokenAmount the amount in tokens. /// @param _feeName the name of the fee being paid. /// @return amount of fees that would/will be paid. function getFeeKnowingAssetToken( Data storage _self, address _assetToken, address /*_from*/, uint256 _tokenAmount, bytes32 _feeName) public view returns (uint256) { FeeTable feeTable = getFeeTableForPlatform(_self, _self.rootPlatformAddress); return feeTable.getFeeFor(_feeName, _assetToken, _tokenAmount, _self.exchangeRateOracle); } /// @notice Set CRWD token address (e.g. for fees). /// @param _crwdToken the CRWD token address. function setCrwdTokenAddress(Data storage _self, address _crwdToken) public { _self.crwdToken = _crwdToken; emit CrwdTokenAddressChanged(_crwdToken); } /// @notice set platform address to trusted. A platform can receive fees. /// @param _platformWallet the wallet that will receive fees. /// @param _trusted true means trusted and false means not (=default). function setTrustedPlatform(Data storage _self, address _platformWallet, bool _trusted) public { setTrustedPlatformInternal(_self, _platformWallet, _trusted, false); } /// @dev set trusted platform logic /// @param _platformWallet the wallet that will receive fees. /// @param _trusted true means trusted and false means not (=default). /// @param _isRootPlatform true means that the given address is the root platform (here mainly used to save info into event). function setTrustedPlatformInternal(Data storage _self, address _platformWallet, bool _trusted, bool _isRootPlatform) private { require(_self.rootPlatformAddress != address(0), "no rootPF"); _self.trustedPlatform[_platformWallet] = _trusted; if(_trusted && !_self.onceTrustedPlatform[msg.sender]) { _self.onceTrustedPlatform[_platformWallet] = true; FeeTable ft = new FeeTable(_self.rootPlatformAddress); _self.platformToFeeTable[_platformWallet] = address(ft); } emit PlatformTrustChanged(_platformWallet, _trusted, _isRootPlatform); } /// @notice Set root platform address. Root platform address can receive fees (independent of which Crowdsale/AssetToken). /// @param _rootPlatformWallet wallet of root platform. function setRootPlatform(Data storage _self, address _rootPlatformWallet) public { _self.rootPlatformAddress = _rootPlatformWallet; emit RootPlatformChanged(_rootPlatformWallet); setTrustedPlatformInternal(_self, _rootPlatformWallet, true, true); } /// @notice Set rate of AssetToken. /// @dev Rate is from BaseCurrency (currently EUR). E.g. rate 2 means 2 tokens per 1 EUR. /// @param _assetToken the regarding AssetToken the rate should be applied on. /// @param _rate the rate. function setAssetTokenRate(Data storage _self, address _assetToken, uint256 _rate) public { _self.store.setAssetTokenRate(_assetToken, _rate); emit AssetTokenRateChanged(_assetToken, _rate); } /// @notice If this contract gets a balance in some other ERC20 contract - or even iself - then we can rescue it. /// @param _foreignTokenAddress token where contract has balance. /// @param _to the beneficiary. function rescueToken(Data storage /*_self*/, address _foreignTokenAddress, address _to) public { ERC20Mintable(_foreignTokenAddress).transfer(_to, ERC20(_foreignTokenAddress).balanceOf(address(this))); } /////////////////// // Events /////////////////// event AssetTokenAdded(address indexed initiator, address indexed wallet, address indexed assetToken, uint256 rate); event AssetTokenChangedActive(address indexed initiator, address indexed assetToken, bool active); event PlatformTrustChanged(address indexed platformWallet, bool trusted, bool isRootPlatform); event CrwdTokenAddressChanged(address indexed crwdToken); event AssetTokenRateChanged(address indexed assetToken, uint256 rate); event RootPlatformChanged(address indexed _rootPlatformWalletAddress); event CrowdsaleAssigned(address initiator, address indexed assetToken, address indexed crowdsale, address platformWallet); event ExchangeRateOracleSet(address indexed initiator, address indexed oracleAddress); event FeesPaid(address indexed from, address indexed to, uint256 value); } // File: contracts/controller/0_library/LibraryHolder.sol /** @title LibraryHolder holds libraries used in inheritance bellow. */ contract LibraryHolder { using ControllerL for ControllerL.Data; /////////////////// // Variables /////////////////// ControllerL.Data internal controllerData; } // File: contracts/controller/1_permissions/PermissionHolder.sol /* Copyright 2018, CONDA This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ /** @title PermissionHolder role permissions used in inheritance bellow. */ contract PermissionHolder is AssetTokenAdministratorRole, At2CsConnectorRole, LibraryHolder { } // File: contracts/controller/2_provider/MainInfoProvider.sol /* Copyright 2018, CONDA This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ /** @title MainInfoProvider holding simple getters and setters and events without much logic. */ contract MainInfoProvider is PermissionHolder { /////////////////// // Events /////////////////// event AssetTokenAdded(address indexed initiator, address indexed wallet, address indexed assetToken, uint256 rate); event AssetTokenChangedActive(address indexed initiator, address indexed assetToken, bool active); event CrwdTokenAddressChanged(address indexed crwdToken); event ExchangeRateOracleSet(address indexed initiator, address indexed oracleAddress); event AssetTokenRateChanged(address indexed assetToken, uint256 rate); event RootPlatformChanged(address indexed _rootPlatformWalletAddress); event PlatformTrustChanged(address indexed platformWallet, bool trusted, bool isRootPlatform); event WhitelistSet(address indexed initiator, address indexed whitelistAddress); event CrowdsaleAssigned(address initiator, address indexed assetToken, address indexed crowdsale, address platformWallet); event FeesPaid(address indexed from, address indexed to, uint256 value); event TokenAssignment(address indexed to, uint256 tokensToMint, address indexed crowdsale, bytes8 tag); /////////////////// // Methods (simple getters/setters ONLY) /////////////////// /// @notice Set CRWD token address (e.g. for fees). /// @param _crwdToken the CRWD token address. function setCrwdTokenAddress(address _crwdToken) public onlyRootPlatformAdministrator { controllerData.setCrwdTokenAddress(_crwdToken); } /// @notice Set exchange rate oracle address. /// @param _oracleAddress the address of the ExchangeRateOracle. function setOracle(address _oracleAddress) public onlyRootPlatformAdministrator { controllerData.setExchangeRateOracle(_oracleAddress); } /// @notice Get FeeTable for platform. /// @param _platform platform to find FeeTable for. /// @return address of FeeTable of platform. function getFeeTableAddressForPlatform(address _platform) public view returns (address) { return controllerData.getFeeTableAddressForPlatform(_platform); } /// @notice Set rate of AssetToken. /// @dev Rate is from BaseCurrency (currently EUR). E.g. rate 2 means 2 tokens per 1 EUR. /// @param _assetToken the regarding AssetToken the rate should be applied on. /// @param _rate the rate. Unit is WAD (decimal number with 18 digits, so rate of x WAD is x*1e18). function setAssetTokenRate(address _assetToken, uint256 _rate) public onlyRootPlatformAdministrator { controllerData.setAssetTokenRate(_assetToken, _rate); } /// @notice Set root platform address. Root platform address can receive fees (independent of which Crowdsale/AssetToken). /// @param _rootPlatformWallet wallet of root platform. function setRootPlatform(address _rootPlatformWallet) public onlyRootPlatformAdministrator { controllerData.setRootPlatform(_rootPlatformWallet); } /// @notice Root platform wallet (receives fees according to it's FeeTable regardless of which Crowdsale/AssetToken) function getRootPlatform() public view returns (address) { return controllerData.rootPlatformAddress; } /// @notice Set platform address to trusted. A platform can receive fees. /// @param _platformWallet the wallet that will receive fees. /// @param _trusted true means trusted and false means not (=default). function setTrustedPlatform(address _platformWallet, bool _trusted) public onlyRootPlatformAdministrator { controllerData.setTrustedPlatform(_platformWallet, _trusted); } /// @notice Is trusted platform. /// @param _platformWallet platform wallet that recieves fees. /// @return true if trusted. function isTrustedPlatform(address _platformWallet) public view returns (bool) { return controllerData.trustedPlatform[_platformWallet]; } /// @notice Get platform of crowdsale. /// @param _crowdsale the crowdsale to get platfrom from. /// @return address of owning platform. function getPlatformOfCrowdsale(address _crowdsale) public view returns (address) { return controllerData.crowdsaleToPlatform[_crowdsale]; } /// @notice Set whitelist contrac address. /// @param _whitelistAddress the whitelist address. function setWhitelistContract(address _whitelistAddress) public onlyRootPlatformAdministrator { controllerData.whitelist = _whitelistAddress; emit WhitelistSet(msg.sender, _whitelistAddress); } /// @notice Get address of generic storage that survives an upgrade. /// @return address of storage. function getStorageAddress() public view returns (address) { return controllerData.getStorageAddress(); } /// @notice Block new connections between AssetToken and Crowdsale (e.g. on upgrade) /// @param _isBlockNewActive true if no new AssetTokens or Crowdsales can be added to controller. function setBlockNewState(bool _isBlockNewActive) public onlyRootPlatformAdministrator { controllerData.blockNew = _isBlockNewActive; } /// @notice Gets state of block new. /// @return true if no new AssetTokens or Crowdsales can be added to controller. function getBlockNewState() public view returns (bool) { return controllerData.blockNew; } } // File: contracts/controller/3_manage/ManageAssetToken.sol /* Copyright 2018, CONDA This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ /** @title ManageAssetToken holds logic functions managing AssetTokens. */ contract ManageAssetToken is MainInfoProvider { using SafeMath for uint256; /////////////////// // Functions /////////////////// /// @notice Add trusted AssetToken. /// @param _ownerWallet requires CRWD for fees, receives ETH on successful campaign. /// @param _rate the rate of tokens per basecurrency (currently EUR). function addTrustedAssetToken(address _ownerWallet, address _assetToken, uint256 _rate) public onlyAssetTokenAdministrator { controllerData.addTrustedAssetToken(_ownerWallet, _assetToken, _rate); } /// @notice Checks if a AssetToken is trusted. /// @param _assetToken the address of the AssetToken. function checkTrustedAssetToken(address _assetToken) public view returns (bool) { return controllerData.checkTrustedAssetToken(_assetToken); } /// @notice Can change the state of an AssetToken (e.g. blacklist for legal reasons) /// @param _assetToken the AssetToken to change state. /// @param _active the state. True means active. /// @return True if successful. function changeActiveTrustedAssetToken(address _assetToken, bool _active) public onlyRootPlatformAdministrator returns (bool) { return controllerData.changeActiveTrustedAssetToken(_assetToken, _active); } /// @notice Get fee that needs to be paid for certain AssetToken and FeeName. /// @param _assetToken the AssetToken being used. /// @param _tokenAmount the amount in tokens. /// @param _feeName the name of the fee being paid. /// @return amount of fees that would/will be paid. function getFeeKnowingAssetToken( address _assetToken, address _from, uint256 _tokenAmount, bytes32 _feeName) public view returns (uint256) { return controllerData.getFeeKnowingAssetToken(_assetToken, _from, _tokenAmount, _feeName); } /// @notice Convert eth amount into base currency (EUR), apply exchange rate via oracle, apply rate for AssetToken. /// @param _crowdsale the crowdsale address. /// @param _amountInWei the amount desired to be converted into tokens. function convertEthToTokenAmount(address _crowdsale, uint256 _amountInWei) public view returns (uint256 _tokens) { (uint256 tokens, ) = controllerData.convertEthToEurApplyRateGetTokenAmountFromCrowdsale(_crowdsale, _amountInWei); return tokens; } } // File: contracts/controller/3_manage/ManageFee.sol /* Copyright 2018, CONDA This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ /** @title ManageAssetToken holds logic functions managing Fees. */ contract ManageFee is MainInfoProvider { /////////////////// // Functions /////////////////// /// @notice Pay fee on controller call from AssetToken. /// @param _assetToken the calling AssetToken contract. /// @param _from the initiator passed through as parameter by AssetToken. /// @param _amount the tokens being handled. /// @param _feeName the name of the fee (key in mapping). function payFeeKnowingAssetToken(address _assetToken, address _from, uint256 _amount, bytes32 _feeName) internal { controllerData.payFeeKnowingAssetToken(_assetToken, _from, _amount, _feeName); } } // File: contracts/controller/3_manage/ManageCrowdsale.sol /* Copyright 2018, CONDA This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ /** @title ManageAssetToken holds logic functions managing Crowdsales. */ contract ManageCrowdsale is MainInfoProvider { /////////////////// // Functions /////////////////// /// @notice assign a crowdsale to an AssetToken. /// @param _assetToken the AssetToken being sold. /// @param _crowdsale the crowdsale that takes ETH (if enabled) and triggers assignment of tokens. /// @param _platformWallet the wallet of the platform. Fees are paid to this address. function assignCrowdsale(address _assetToken, address _crowdsale, address _platformWallet) public onlyAt2CsConnector { controllerData.assignCrowdsale(_assetToken, _crowdsale, _platformWallet); } /// @notice Checks if a crowdsale is trusted. /// @param _crowdsale the address of the crowdsale. function checkTrustedCrowdsale(address _crowdsale) public view returns (bool) { return controllerData.checkTrustedCrowdsale(_crowdsale); } /// @notice Get fee that needs to be paid for certain Crowdsale and FeeName. /// @param _crowdsale the Crowdsale being used. /// @param _feeTableAddr the address of the feetable. /// @param _amountInTokensOrEth the amount in tokens or pure ETH when conversion parameter true. /// @param _amountRequiresConversion when true amount parameter is converted from ETH into tokens. /// @param _feeName the name of the fee being paid. /// @return amount of fees that would/will be paid. function getFeeKnowingCrowdsale( address _crowdsale, address _feeTableAddr, uint256 _amountInTokensOrEth, bool _amountRequiresConversion, bytes32 _feeName) public view returns (uint256) { return controllerData.getFeeKnowingCrowdsale(_crowdsale, _feeTableAddr, _amountInTokensOrEth, _amountRequiresConversion, _feeName); } } // File: contracts/controller/3_manage/ManagePlatform.sol /* Copyright 2018, CONDA This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ /** @title ManageAssetToken holds logic functions managing platforms. */ contract ManagePlatform is MainInfoProvider { /////////////////// // Functions /////////////////// /// @notice Checks if a crowdsale is trusted or fail. /// @param _platformWallet the platform wallet. /// @return true if trusted. function checkTrustedPlatform(address _platformWallet) public view returns (bool) { return controllerData.checkTrustedPlatform(_platformWallet); } /// @notice Is a platform wallet trusted. /// @return true if trusted. function isTrustedPlatform(address _platformWallet) public view returns (bool) { return controllerData.trustedPlatform[_platformWallet]; } } // File: contracts/controller/3_manage/ManageWhitelist.sol /* Copyright 2018, CONDA This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ /** @title ManageAssetToken holds logic functions managing Whitelist and KYC. */ contract ManageWhitelist is MainInfoProvider { /////////////////// // Functions /////////////////// /// @notice Check if a wallet is whitelisted or fail. Also considers auto extend (if enabled). /// @param _wallet the wallet to check. function checkWhitelistedWallet(address _wallet) public returns (bool) { controllerData.checkWhitelistedWallet(_wallet); } /// @notice Check if a wallet is whitelisted. /// @param _wallet the wallet to check. /// @return true if whitelisted. function isWhitelistedWallet(address _wallet) public view returns (bool) { controllerData.isWhitelistedWallet(_wallet); } } // File: contracts/controller/3_manage/ManagerHolder.sol /* Copyright 2018, CONDA This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ /** @title ManagerHolder combining all managers into single contract to be inherited. */ contract ManagerHolder is ManageAssetToken, ManageFee, ManageCrowdsale, ManagePlatform, ManageWhitelist { } // File: contracts/controller/interface/ICRWDController.sol interface ICRWDController { function transferParticipantsVerification(address _underlyingCurrency, address _from, address _to, uint256 _tokenAmount) external returns (bool); //from AssetToken function buyFromCrowdsale(address _to, uint256 _amountInWei) external returns (uint256 _tokensCreated, uint256 _overpaidRefund); //from Crowdsale function assignFromCrowdsale(address _to, uint256 _tokenAmount, bytes8 _tag) external returns (uint256 _tokensCreated); //from Crowdsale function calcTokensForEth(uint256 _amountInWei) external view returns (uint256 _tokensWouldBeCreated); //from Crowdsale } // File: contracts/controller/CRWDController.sol /** @title CRWDController main contract and n-th child of multi-level inheritance. */ contract CRWDController is ManagerHolder, ICRWDController { /////////////////// // Events /////////////////// event GlobalConfigurationChanged(bool feesEnabled, bool whitelistEnabled); /////////////////// // Constructor /////////////////// constructor(bool _feesEnabled, bool _whitelistEnabled, address _rootPlatformAddress, address _storage) public { controllerData.assignStore(_storage); setRootPlatform(_rootPlatformAddress); configure(_feesEnabled, _whitelistEnabled); } /////////////////// // Functions /////////////////// /// @notice configure global flags. /// @param _feesEnabled global flag fees enabled. /// @param _whitelistEnabled global flag whitelist check enabled. function configure(bool _feesEnabled, bool _whitelistEnabled) public onlyRootPlatformAdministrator { controllerData.feesEnabled = _feesEnabled; controllerData.whitelistEnabled = _whitelistEnabled; emit GlobalConfigurationChanged(_feesEnabled, _whitelistEnabled); } /// @notice Called from AssetToken on transfer for whitelist check. /// @param _from the original initiator passed through. /// @param _to the receiver of the tokens. /// @param _tokenAmount the amount of tokens to be transfered. function transferParticipantsVerification(address /*_underlyingCurrency*/, address _from, address _to, uint256 _tokenAmount) public returns (bool) { if (controllerData.whitelistEnabled) { checkWhitelistedWallet(_to); //receiver must be whitelisted } // Caller must be a trusted AssetToken. Otherwise anyone could make investor pay fees for no reason. require(checkTrustedAssetToken(msg.sender), "untrusted"); if (controllerData.feesEnabled) { payFeeKnowingAssetToken(msg.sender, _from, _tokenAmount, "clearTransferFunds"); } return true; } /// @notice Called from Crowdsale on buy token action (paid via Ether). /// @param _to the beneficiary of the tokens (passed through from Crowdsale). /// @param _amountInWei the ETH amount (unit WEI). function buyFromCrowdsale(address _to, uint256 _amountInWei) public returns (uint256 _tokensCreated, uint256 _overpaidRefund) { return controllerData.buyFromCrowdsale(_to, _amountInWei); } /// @notice Calculate how many tokens will be received per Ether. /// @param _amountInWei the ETH amount (unit WEI). /// @return tokens that would be created. function calcTokensForEth(uint256 _amountInWei) external view returns (uint256 _tokensWouldBeCreated) { require(checkTrustedCrowdsale(msg.sender), "untrusted source2"); return convertEthToTokenAmount(msg.sender, _amountInWei); } /// @notice Called from Crowdsale via (semi-)automatic process on off-chain payment. /// @param _to the beneficiary of the tokens. /// @param _tokenAmount the amount of tokens to be minted/assigned. /// @return tokens created. function assignFromCrowdsale(address _to, uint256 _tokenAmount, bytes8 _tag) external returns (uint256 _tokensCreated) { _tokensCreated = controllerData.assignFromCrowdsale(_to, _tokenAmount); emit TokenAssignment(_to, _tokenAmount, msg.sender, _tag); return _tokensCreated; } //////////////// // Rescue Tokens //////////////// /// @dev Can rescue tokens accidentally assigned to this contract /// @param _foreignTokenAddress The address from which the balance will be retrieved /// @param _to beneficiary function rescueToken(address _foreignTokenAddress, address _to) public onlyRootPlatformAdministrator { controllerData.rescueToken(_foreignTokenAddress, _to); } }
Function to call on buy request. _to beneficiary of tokens. _amountInWei the invested ETH amount (unit WEI).
function buyFromCrowdsale( Data storage _self, address _to, uint256 _amountInWei) public returns (uint256 _tokensCreated, uint256 _overpaidRefund) { (uint256 effectiveTokensNoDecimals, uint256 overpaidEth) = convertEthToEurApplyRateGetTokenAmountFromCrowdsale( _self, msg.sender, _amountInWei); checkValidTokenAssignmentFromCrowdsale(_self, _to); payFeeFromCrowdsale(_self, effectiveTokensNoDecimals); _tokensCreated = doTokenAssignment(_self, _to, effectiveTokensNoDecimals, msg.sender); return (_tokensCreated, overpaidEth); }
2,537,436
./partial_match/42/0x6472572dC495039b6A298fCAC5949c5e10818FeA/sources/LpStakingRewards.sol
Inheritance Views Mutative
interface IStakingRewards { function lastTimeRewardApplicable() external view returns (uint256); function rewardPerToken() external view returns (uint256); function earned(address account) external view returns (uint256); function getRewardForDuration() external view returns (uint256); function totalSupply() external view returns (uint256); function balanceOf(address account) external view returns (uint256); function stake(uint256 amount, address user) external; function withdraw(uint256 amount, address user) external; function getReward(address user) external; function exit(address user) external; }
3,438,665
./full_match/1/0xBb4BAB913E3C001b6C30059B398c0797ded84d34/sources/contracts/deploy/DSProxyContract.sol
throw if contract failed to deploy
function write(bytes memory _code) external returns (address target) { assembly { target := create(0, add(_code, 0x20), mload(_code)) switch iszero(extcodesize(target)) case 1 { revert(0, 0) } } bytes32 hash = keccak256(_code); cache[hash] = target; }
4,876,353
// SPDX-License-Identifier: MIT pragma solidity 0.8.11; import "./Strings.sol"; import "./AbiDecoder.sol"; import "./IAllowlist.sol"; /** * @title Validate raw calldata against an allowlist * @author yearn.finance */ /******************************************************* * Main Contract Logic *******************************************************/ library CalldataValidation { /** * @notice Calculate a method signature given a condition * @param condition The condition from which to generate the signature * @return signature The method signature in string format (ie. "approve(address,uint256)") */ function methodSignatureByCondition(IAllowlist.Condition memory condition) public pure returns (string memory signature) { bytes memory signatureBytes = abi.encodePacked(condition.methodName, "("); for (uint256 paramIdx; paramIdx < condition.paramTypes.length; paramIdx++) { signatureBytes = abi.encodePacked( signatureBytes, condition.paramTypes[paramIdx] ); if (paramIdx + 1 < condition.paramTypes.length) { signatureBytes = abi.encodePacked(signatureBytes, ","); } } signatureBytes = abi.encodePacked(signatureBytes, ")"); signature = string(signatureBytes); } /** * @notice Check target validity * @param implementationAddress The address the validation method will be executed against * @param targetAddress The target address to validate * @param requirementValidationMethod The method to execute * @return targetValid Returns true if the target is valid and false otherwise * @dev If "requirementValidationMethod" is "isValidVaultToken" and target address is usdc * the validation check will look like this: usdc.isValidVaultToken(targetAddress), * where the result of the validation method is expected to return a bool */ function checkTarget( address implementationAddress, address targetAddress, string memory requirementValidationMethod ) public view returns (bool targetValid) { string memory methodSignature = string( abi.encodePacked(requirementValidationMethod, "(address)") ); (, bytes memory data) = address(implementationAddress).staticcall( abi.encodeWithSignature(methodSignature, targetAddress) ); targetValid = abi.decode(data, (bool)); } /** * @notice Check method selector validity * @param data Raw input calldata (we will extract the 4-byte selector * from the beginning of the calldata) * @param condition The condition struct to check (we generate the complete * method selector using condition.methodName and condition.paramTypes) * @return methodSelectorValid Returns true if the method selector is valid and false otherwise */ function checkMethodSelector( bytes calldata data, IAllowlist.Condition memory condition ) public pure returns (bool methodSelectorValid) { string memory methodSignature = methodSignatureByCondition(condition); bytes4 methodSelectorBySignature = bytes4( keccak256(bytes(methodSignature)) ); bytes4 methodSelectorByCalldata = bytes4(data[0:4]); methodSelectorValid = methodSelectorBySignature == methodSelectorByCalldata; } /** * @notice Check an individual method param's validity * @param implementationAddress The address the validation method will be executed against * @param requirement The specific requirement (of type "param") to check (ie. ["param", "isVault", "0"]) * @dev A condition may have multiple requirements, all of which must be true * @dev The middle element of a requirement is the requirement validation method * @dev The last element of a requirement is the parameter index to validate against * @param condition The entire condition struct to check the param against * @param data Raw input calldata for the original method call * @return Returns true if the param is valid, false if not */ function checkParam( address implementationAddress, string[] memory requirement, IAllowlist.Condition memory condition, bytes calldata data ) public view returns (bool) { uint256 paramIdx = Strings.atoi(requirement[2], 10); string memory paramType = condition.paramTypes[paramIdx]; bytes memory paramCalldata = AbiDecoder.getParamFromCalldata( data, paramType, paramIdx ); string memory methodSignature = string( abi.encodePacked(requirement[1], "(", paramType, ")") ); bytes memory encodedCalldata = abi.encodePacked( bytes4(keccak256(bytes(methodSignature))), paramCalldata ); bool success; bytes memory resultData; (success, resultData) = address(implementationAddress).staticcall( encodedCalldata ); if (success) { return abi.decode(resultData, (bool)); } return false; } /** * @notice Test a target address and calldata against a specific condition and implementation * @param condition The condition to test * @param targetAddress Target address of the original method call * @param data Calldata of the original methodcall * @return Returns true if the condition passes and false if not * @dev The condition check is comprised of 3 parts: - Method selector check (to make sure the calldata method selector matches the condition method selector) - Target check (to make sure the target is valid) - Param check (to make sure the specified param is valid) */ function testCondition( address allowlistAddress, IAllowlist.Condition memory condition, address targetAddress, bytes calldata data ) public view returns (bool) { string[][] memory requirements = condition.requirements; address implementationAddress = IAllowlist(allowlistAddress) .implementationById(condition.implementationId); for ( uint256 requirementIdx; requirementIdx < requirements.length; requirementIdx++ ) { string[] memory requirement = requirements[requirementIdx]; string memory requirementType = requirement[0]; string memory requirementValidationMethod = requirement[1]; if (!checkMethodSelector(data, condition)) { return false; } if (Strings.stringsEqual(requirementType, "target")) { bool targetValid = checkTarget( implementationAddress, targetAddress, requirementValidationMethod ); if (!targetValid) { return false; } } else if (Strings.stringsEqual(requirementType, "param")) { bool paramValid = checkParam( implementationAddress, requirement, condition, data ); if (!paramValid) { return false; } } } return true; } /** * @notice Test target address and calldata against all stored protocol conditions * @dev This is done to determine whether or not the target address and calldata are valid and whitelisted * @dev This is the primary method that should be called by integrators * @param allowlistAddress The address of the allowlist to check calldata against * @param targetAddress The target address of the call * @param data The raw calldata to test * @return Returns true if the calldata/target test is successful and false if not */ function validateCalldataByAllowlist( address allowlistAddress, address targetAddress, bytes calldata data ) public view returns (bool) { IAllowlist.Condition[] memory _conditions = IAllowlist(allowlistAddress) .conditionsList(); for ( uint256 conditionIdx; conditionIdx < _conditions.length; conditionIdx++ ) { IAllowlist.Condition memory condition = _conditions[conditionIdx]; bool conditionPassed = testCondition( allowlistAddress, condition, targetAddress, data ); if (conditionPassed) { return true; } } return false; } }
Check an individual method param's validity implementationAddress The address the validation method will be executed against requirement The specific requirement (of type "param") to check (ie. ["param", "isVault", "0"]) A condition may have multiple requirements, all of which must be true The middle element of a requirement is the requirement validation method The last element of a requirement is the parameter index to validate against condition The entire condition struct to check the param against data Raw input calldata for the original method call return Returns true if the param is valid, false if not/
function checkParam( address implementationAddress, string[] memory requirement, IAllowlist.Condition memory condition, bytes calldata data ) public view returns (bool) { uint256 paramIdx = Strings.atoi(requirement[2], 10); string memory paramType = condition.paramTypes[paramIdx]; bytes memory paramCalldata = AbiDecoder.getParamFromCalldata( data, paramType, paramIdx ); string memory methodSignature = string( abi.encodePacked(requirement[1], "(", paramType, ")") ); bytes memory encodedCalldata = abi.encodePacked( bytes4(keccak256(bytes(methodSignature))), paramCalldata ); bool success; bytes memory resultData; (success, resultData) = address(implementationAddress).staticcall( encodedCalldata ); if (success) { return abi.decode(resultData, (bool)); } return false; } - Target check (to make sure the target is valid) - Param check (to make sure the specified param is valid)
12,224,915
/* @AUTHOR - Raj Jha & Harish Jaggi */ pragma solidity ^0.5.1; import "./interface_test_event.sol"; /** * @title Insurance interface */ contract InsuranceCompany is IInsurance { mapping(address => bytes32) createdPolicies; //create dummy policies. Test data - ("0x12",0xca35b7d915458ef540ade6068dfe2f44e8fa733c) function createPolicies(bytes32 policyId, address sender) external { createdPolicies[sender] = policyId; } //Approve policies. Test data - ("0x12",0xca35b7d915458ef540ade6068dfe2f44e8fa733c) function approval(bytes32 policyId, address sender) external returns (bool){ _approveInsurance(policyId,sender); return true; } function _approveInsurance(bytes32 policyId, address sender) internal returns (bool) { require(createdPolicies[sender] == policyId); emit Approval(sender, policyId); //Emit Parent abstract contract event. } }
Approve policies. Test data - ("0x12",0xca35b7d915458ef540ade6068dfe2f44e8fa733c)
function approval(bytes32 policyId, address sender) external returns (bool){ _approveInsurance(policyId,sender); return true; }
15,848,890
// SPDX-License-Identifier: Apache-2.0 pragma solidity 0.7.6; pragma abicoder v2; import {OwnableUpgradeable} from '@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol'; import {ERC20} from '@openzeppelin/contracts/token/ERC20/ERC20.sol'; import {IERC20} from '@openzeppelin/contracts/token/ERC20/IERC20.sol'; import {SafeERC20} from '@openzeppelin/contracts/token/ERC20/SafeERC20.sol'; import {ECDSA} from '@openzeppelin/contracts/cryptography/ECDSA.sol'; import '@uniswap/v3-core/contracts/interfaces/IUniswapV3Factory.sol'; import '@uniswap/v3-periphery/contracts/interfaces/ISwapRouter.sol'; import '@uniswap/v3-periphery/contracts/libraries/TransferHelper.sol'; import '@uniswap/v3-core/contracts/interfaces/IUniswapV3Pool.sol'; import {IHypervisor} from './interfaces/IHypervisor.sol'; import {IBabController} from './interfaces/IBabController.sol'; import {IGovernor} from './interfaces/external/oz/IGovernor.sol'; import {IGarden} from './interfaces/IGarden.sol'; import {IHeart} from './interfaces/IHeart.sol'; import {IWETH} from './interfaces/external/weth/IWETH.sol'; import {ICToken} from './interfaces/external/compound/ICToken.sol'; import {ICEther} from './interfaces/external/compound/ICEther.sol'; import {IComptroller} from './interfaces/external/compound/IComptroller.sol'; import {IPriceOracle} from './interfaces/IPriceOracle.sol'; import {IMasterSwapper} from './interfaces/IMasterSwapper.sol'; import {IVoteToken} from './interfaces/IVoteToken.sol'; import {IERC1271} from './interfaces/IERC1271.sol'; import {PreciseUnitMath} from './lib/PreciseUnitMath.sol'; import {SafeDecimalMath} from './lib/SafeDecimalMath.sol'; import {LowGasSafeMath as SafeMath} from './lib/LowGasSafeMath.sol'; import {Errors, _require, _revert} from './lib/BabylonErrors.sol'; import {ControllerLib} from './lib/ControllerLib.sol'; /** * @title Heart * @author Babylon Finance * * Contract that assists The Heart of Babylon garden with BABL staking. * */ contract Heart is OwnableUpgradeable, IHeart, IERC1271 { using SafeERC20 for IERC20; using PreciseUnitMath for uint256; using SafeMath for uint256; using SafeDecimalMath for uint256; using ControllerLib for IBabController; /* ============ Modifiers ============ */ /** * Throws if the sender is not a keeper in the protocol */ function _onlyKeeper() private view { _require(controller.isValidKeeper(msg.sender), Errors.ONLY_KEEPER); } /* ============ Events ============ */ event FeesCollected(uint256 _timestamp, uint256 _amount); event LiquidityAdded(uint256 _timestamp, uint256 _wethBalance, uint256 _bablBalance); event BablBuyback(uint256 _timestamp, uint256 _wethSpent, uint256 _bablBought); event GardenSeedInvest(uint256 _timestamp, address indexed _garden, uint256 _wethInvested); event FuseLentAsset(uint256 _timestamp, address indexed _asset, uint256 _assetAmount); event BABLRewardSent(uint256 _timestamp, uint256 _bablSent); event ProposalVote(uint256 _timestamp, uint256 _proposalId, bool _isApprove); event UpdatedGardenWeights(uint256 _timestamp); /* ============ Constants ============ */ // Only for offline use by keeper/fauna bytes32 private constant VOTE_PROPOSAL_TYPEHASH = keccak256('ProposalVote(uint256 _proposalId,uint256 _amount,bool _isApprove)'); bytes32 private constant VOTE_GARDEN_TYPEHASH = keccak256('GardenVote(address _garden,uint256 _amount)'); // Visor IHypervisor private constant visor = IHypervisor(0xF19F91d7889668A533F14d076aDc187be781a458); // Address of Uniswap factory IUniswapV3Factory internal constant factory = IUniswapV3Factory(0x1F98431c8aD98523631AE4a59f267346ea31F984); uint24 private constant FEE_LOW = 500; uint24 private constant FEE_MEDIUM = 3000; uint24 private constant FEE_HIGH = 10000; uint256 private constant DEFAULT_TRADE_SLIPPAGE = 25e15; // 2.5% // Tokens IWETH private constant WETH = IWETH(0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2); IERC20 private constant BABL = IERC20(0xF4Dc48D260C93ad6a96c5Ce563E70CA578987c74); IERC20 private constant DAI = IERC20(0x6B175474E89094C44Da98b954EedeAC495271d0F); IERC20 private constant USDC = IERC20(0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48); IERC20 private constant WBTC = IERC20(0x2260FAC5E5542a773Aa44fBCfeDf7C193bc2C599); IERC20 private constant FRAX = IERC20(0x853d955aCEf822Db058eb8505911ED77F175b99e); // Fuse address private constant BABYLON_FUSE_POOL_ADDRESS = 0xC7125E3A2925877C7371d579D29dAe4729Ac9033; // Value Amount for protect purchases in DAI uint256 private constant PROTECT_BUY_AMOUNT_DAI = 2e21; /* ============ Immutables ============ */ IBabController private immutable controller; IGovernor private immutable governor; address private immutable treasury; /* ============ State Variables ============ */ // Instance of the Controller contract // Heart garden address IGarden public override heartGarden; // Variables to handle garden seed investments address[] public override votedGardens; uint256[] public override gardenWeights; // Min Amounts to trade mapping(address => uint256) public override minAmounts; // Fuse pool Variables // Mapping of asset addresses to cToken addresses in the fuse pool mapping(address => address) public override assetToCToken; // Which asset is going to receive the next batch of liquidity in fuse address public override assetToLend; // Timestamp when the heart was last pumped uint256 public override lastPumpAt; // Timestamp when the votes were sent by the keeper last uint256 public override lastVotesAt; // Amount to gift to the Heart of Babylon Garden weekly uint256 public override weeklyRewardAmount; uint256 public override bablRewardLeft; // Array with the weights to distribute to different heart activities // 0: Treasury // 1: Buybacks // 2: Liquidity BABL-ETH // 3: Garden Seed Investments // 4: Fuse Pool uint256[] public override feeDistributionWeights; // Metric Totals // 0: fees accumulated in weth // 1: Money sent to treasury // 2: babl bought in babl // 3: liquidity added in weth // 4: amount invested in gardens in weth // 5: amount lent on fuse in weth // 6: weekly rewards paid in babl uint256[7] public override totalStats; // Trade slippage to apply in trades uint256 public override tradeSlippage; // Asset to use to buy protocol wanted assets address public override assetForPurchases; // Bond Assets with the discount mapping(address => uint256) public override bondAssets; // EIP-1271 signer address private signer; /* ============ Initializer ============ */ /** * Set controller and governor addresses * * @param _controller Address of controller contract * @param _governor Address of governor contract */ constructor(IBabController _controller, IGovernor _governor) initializer { _require(address(_controller) != address(0), Errors.ADDRESS_IS_ZERO); _require(address(_governor) != address(0), Errors.ADDRESS_IS_ZERO); controller = _controller; treasury = _controller.treasury(); governor = _governor; } /** * Set state variables and map asset pairs to their oracles * * @param _feeWeights Weights of the fee distribution */ function initialize(uint256[] calldata _feeWeights) external initializer { OwnableUpgradeable.__Ownable_init(); updateFeeWeights(_feeWeights); updateMarkets(); updateAssetToLend(address(DAI)); minAmounts[address(DAI)] = 500e18; minAmounts[address(USDC)] = 500e6; minAmounts[address(WETH)] = 5e17; minAmounts[address(WBTC)] = 3e6; // Self-delegation to be able to use BABL balance as voting power IVoteToken(address(BABL)).delegate(address(this)); tradeSlippage = DEFAULT_TRADE_SLIPPAGE; } /* ============ External Functions ============ */ /** * Function to pump blood to the heart * * Note: Anyone can call this. Keeper in Defender will be set up to do it for convenience. */ function pump() public override { _require(address(heartGarden) != address(0), Errors.HEART_GARDEN_NOT_SET); _require(block.timestamp.sub(lastPumpAt) >= 1 weeks, Errors.HEART_ALREADY_PUMPED); _require(block.timestamp.sub(lastVotesAt) < 1 weeks, Errors.HEART_VOTES_MISSING); // Consolidate all fees _consolidateFeesToWeth(); uint256 wethBalance = WETH.balanceOf(address(this)); _require(wethBalance >= 15e17, Errors.HEART_MINIMUM_FEES); // Send 10% to the treasury IERC20(WETH).safeTransferFrom(address(this), treasury, wethBalance.preciseMul(feeDistributionWeights[0])); totalStats[1] = totalStats[1].add(wethBalance.preciseMul(feeDistributionWeights[0])); // 30% for buybacks _buyback(wethBalance.preciseMul(feeDistributionWeights[1])); // 25% to BABL-ETH pair _addLiquidity(wethBalance.preciseMul(feeDistributionWeights[2])); // 15% to Garden Investments _investInGardens(wethBalance.preciseMul(feeDistributionWeights[3])); // 20% lend in fuse pool _lendFusePool(address(WETH), wethBalance.preciseMul(feeDistributionWeights[4]), address(assetToLend)); // Add BABL reward to stakers (if any) _sendWeeklyReward(); lastPumpAt = block.timestamp; } /** * Function to vote for a proposal * * Note: Only keeper can call this. Votes need to have been resolved offchain. * Warning: Gardens need to delegate to heart first. */ function voteProposal(uint256 _proposalId, bool _isApprove) external override { _onlyKeeper(); // Governor does revert if trying to cast a vote twice or if proposal is not active IGovernor(governor).castVote(_proposalId, _isApprove ? 1 : 0); emit ProposalVote(block.timestamp, _proposalId, _isApprove); } /** * Resolves garden votes for this cycle * * Note: Only keeper can call this * @param _gardens Gardens that are going to receive investment * @param _weights Weight for the investment in each garden normalied to 1e18 precision */ function resolveGardenVotes(address[] memory _gardens, uint256[] memory _weights) public override { _onlyKeeper(); _require(_gardens.length == _weights.length, Errors.HEART_VOTES_LENGTH); delete votedGardens; delete gardenWeights; for (uint256 i = 0; i < _gardens.length; i++) { votedGardens.push(_gardens[i]); gardenWeights.push(_weights[i]); } lastVotesAt = block.timestamp; emit UpdatedGardenWeights(block.timestamp); } function resolveGardenVotesAndPump(address[] memory _gardens, uint256[] memory _weights) external override { resolveGardenVotes(_gardens, _weights); pump(); } /** * Updates fuse pool market information and enters the markets * */ function updateMarkets() public override { controller.onlyGovernanceOrEmergency(); // Enter markets of the fuse pool for all these assets address[] memory markets = IComptroller(BABYLON_FUSE_POOL_ADDRESS).getAllMarkets(); for (uint256 i = 0; i < markets.length; i++) { address underlying = ICToken(markets[i]).underlying(); assetToCToken[underlying] = markets[i]; } IComptroller(BABYLON_FUSE_POOL_ADDRESS).enterMarkets(markets); } /** * Set the weights to allocate to different heart initiatives * * @param _feeWeights Array of % (up to 1e18) with the fee weights */ function updateFeeWeights(uint256[] calldata _feeWeights) public override { controller.onlyGovernanceOrEmergency(); delete feeDistributionWeights; for (uint256 i = 0; i < _feeWeights.length; i++) { feeDistributionWeights.push(_feeWeights[i]); } } /** * Updates the next asset to lend on fuse pool * * @param _assetToLend New asset to lend */ function updateAssetToLend(address _assetToLend) public override { controller.onlyGovernanceOrEmergency(); _require(assetToLend != _assetToLend, Errors.HEART_ASSET_LEND_SAME); _require(assetToCToken[_assetToLend] != address(0), Errors.HEART_ASSET_LEND_INVALID); assetToLend = _assetToLend; } /** * Updates the next asset to purchase assets from strategies at a premium * * @param _purchaseAsset New asset to purchase */ function updateAssetToPurchase(address _purchaseAsset) public override { controller.onlyGovernanceOrEmergency(); _require( _purchaseAsset != assetForPurchases && _purchaseAsset != address(0), Errors.HEART_ASSET_PURCHASE_INVALID ); assetForPurchases = _purchaseAsset; } /** * Updates the next asset to purchase assets from strategies at a premium * * @param _assetToBond Bond to update * @param _bondDiscount Bond discount to apply 1e18 */ function updateBond(address _assetToBond, uint256 _bondDiscount) public override { controller.onlyGovernanceOrEmergency(); bondAssets[_assetToBond] = _bondDiscount; } /** * Adds a BABL reward to be distributed weekly back to the heart garden * * @param _bablAmount Total amount to distribute * @param _weeklyRate Weekly amount to distribute */ function addReward(uint256 _bablAmount, uint256 _weeklyRate) external override { controller.onlyGovernanceOrEmergency(); // Get the BABL reward IERC20(BABL).safeTransferFrom(msg.sender, address(this), _bablAmount); bablRewardLeft = bablRewardLeft.add(_bablAmount); weeklyRewardAmount = _weeklyRate; } /** * Updates the min amount to trade a specific asset * * @param _asset Asset to edit the min amount * @param _minAmountOut New min amount */ function setMinTradeAmount(address _asset, uint256 _minAmountOut) external override { controller.onlyGovernanceOrEmergency(); minAmounts[_asset] = _minAmountOut; } /** * Updates the heart garden address * * @param _heartGarden New heart garden address */ function setHeartGardenAddress(address _heartGarden) external override { controller.onlyGovernanceOrEmergency(); heartGarden = IGarden(_heartGarden); } /** * Updates the tradeSlippage * * @param _tradeSlippage Trade slippage */ function setTradeSlippage(uint256 _tradeSlippage) external override { controller.onlyGovernanceOrEmergency(); tradeSlippage = _tradeSlippage; } /** * Tell the heart to lend an asset on Fuse * * @param _assetToLend Address of the asset to lend * @param _lendAmount Amount of the asset to lend */ function lendFusePool(address _assetToLend, uint256 _lendAmount) external override { controller.onlyGovernanceOrEmergency(); // Lend into fuse _lendFusePool(_assetToLend, _lendAmount, _assetToLend); } /** * Heart borrows using its liquidity * Note: Heart must have enough liquidity * * @param _assetToBorrow Asset that the heart is receiving from sender * @param _borrowAmount Amount of asset to transfet */ function borrowFusePool(address _assetToBorrow, uint256 _borrowAmount) external override { controller.onlyGovernanceOrEmergency(); address cToken = assetToCToken[_assetToBorrow]; require(cToken != address(0), 'Not a valid cToken'); require(ICToken(cToken).borrow(_borrowAmount) == 0, 'Not enough collateral'); } /** * Repays Heart fuse pool position * Note: We must have the asset in the heart * * @param _borrowedAsset Borrowed asset that we want to pay * @param _amountToRepay Amount of asset to transfer */ function repayFusePool(address _borrowedAsset, uint256 _amountToRepay) external override { controller.onlyGovernanceOrEmergency(); address cToken = assetToCToken[_borrowedAsset]; IERC20(_borrowedAsset).safeApprove(cToken, _amountToRepay); require(ICToken(cToken).repayBorrow(_amountToRepay) == 0, 'Not enough to repay'); } /** * Trades one asset for another in the heart * Note: We must have the _fromAsset _fromAmount available. * @param _fromAsset Asset to exchange * @param _toAsset Asset to receive * @param _fromAmount Amount of asset to exchange * @param _minAmountOut Min amount of received asset */ function trade( address _fromAsset, address _toAsset, uint256 _fromAmount, uint256 _minAmountOut ) external override { controller.onlyGovernanceOrEmergency(); require(IERC20(_fromAsset).balanceOf(address(this)) >= _fromAmount, 'Not enough asset to trade'); uint256 boughtAmount = _trade(_fromAsset, _toAsset, _fromAmount); require(boughtAmount >= _minAmountOut, 'Too much slippage'); } /** * Strategies can sell wanted assets by the protocol to the heart. * Heart will buy them using borrowings in stables. * Heart returns WETH so master swapper will take it from there. * Note: Strategy needs to have approved the heart. * * @param _assetToSell Asset that the heart is receiving from strategy to sell * @param _amountToSell Amount of asset to sell */ function sellWantedAssetToHeart(address _assetToSell, uint256 _amountToSell) external override { controller.isSystemContract(msg.sender); require(controller.protocolWantedAssets(_assetToSell), 'Must be a wanted asset'); require(assetForPurchases != address(0), 'Asset for purchases not set'); // Uses on chain oracle to fetch prices uint256 pricePerTokenUnit = IPriceOracle(controller.priceOracle()).getPrice(_assetToSell, assetForPurchases); require(pricePerTokenUnit != 0, 'No price found'); uint256 amountInPurchaseAssetOffered = pricePerTokenUnit.preciseMul(_amountToSell); require( IERC20(assetForPurchases).balanceOf(address(this)) >= amountInPurchaseAssetOffered, 'Not enough balance to buy wanted asset' ); IERC20(_assetToSell).safeTransferFrom(msg.sender, address(this), _amountToSell); // Buy it from the strategy plus 1% premium uint256 wethTraded = _trade(assetForPurchases, address(WETH), amountInPurchaseAssetOffered.preciseMul(101e16)); // Send weth back to the strategy IERC20(WETH).safeTransfer(msg.sender, wethTraded); } /** * Users can bond an asset that belongs to the program and receive a discount on hBABL. * Note: Heart needs to have enough BABL to satisfy the discount. * Note: User needs to approve the asset to bond first. * * @param _assetToBond Asset that the user wants to bond * @param _amountToBond Amount to be bonded * @param _minAmountOut Min amount of Heart garden shares to recieve */ function bondAsset( address _assetToBond, uint256 _amountToBond, uint256 _minAmountOut, address _referrer ) external override { require(bondAssets[_assetToBond] > 0 && _amountToBond > 0, 'Bond > 0'); // Total value adding the premium uint256 bondValueInBABL = _bondToBABL( _assetToBond, _amountToBond, IPriceOracle(controller.priceOracle()).getPrice(_assetToBond, address(BABL)) ); // Get asset to bond from sender IERC20(_assetToBond).safeTransferFrom(msg.sender, address(this), _amountToBond); // Deposit on behalf of the user require(BABL.balanceOf(address(this)) >= bondValueInBABL, 'Not enough BABL'); BABL.safeApprove(address(heartGarden), bondValueInBABL); heartGarden.deposit(bondValueInBABL, _minAmountOut, msg.sender, _referrer); } /** * Users can bond an asset that belongs to the program and receive a discount on hBABL. * Note: Heart needs to have enough BABL to satisfy the discount. * Note: User needs to approve the asset to bond first. * * @param _assetToBond Asset that the user wants to bond * @param _amountToBond Amount to be bonded */ function bondAssetBySig( address _assetToBond, uint256 _amountToBond, uint256 _amountIn, uint256 _minAmountOut, uint256 _nonce, uint256 _maxFee, uint256 _priceInBABL, uint256 _pricePerShare, uint256 _fee, address _contributor, address _referrer, bytes memory _signature ) external override { _onlyKeeper(); require(_fee <= _maxFee, 'Fee too high'); require(bondAssets[_assetToBond] > 0, 'Bond > 0'); // Get asset to bond from contributor IERC20(_assetToBond).safeTransferFrom(_contributor, address(this), _amountToBond); // Deposit on behalf of the user require(BABL.balanceOf(address(this)) >= _amountIn, 'Not enough BABL'); // verify that _amountIn is correct compare to _amountToBond require(_bondToBABL(_assetToBond, _amountToBond, _priceInBABL) == _amountIn, 'wrong amount of BABL'); BABL.safeApprove(address(heartGarden), _amountIn); // Pay the fee to the Keeper IERC20(BABL).safeTransfer(msg.sender, _fee); // grant permission to deposit signer = _contributor; heartGarden.depositBySig( _amountIn, _minAmountOut, _nonce, _maxFee, _contributor, _pricePerShare, 0, address(this), _referrer, _signature ); // revoke permission to deposit signer = address(0); } /** * Heart will protect and buyback BABL whenever the price dips below the intended price protection. * Note: Asset for purchases needs to be setup and have enough balance. * * @param _bablPriceProtectionAt BABL Price in DAI to protect * @param _bablPrice Market price of BABL in DAI * @param _purchaseAssetPrice Price of purchase asset in DAI * @param _slippage Trade slippage on UinV3 to control amount of arb * @param _hopToken Hop token to use for UniV3 trade */ function protectBABL( uint256 _bablPriceProtectionAt, uint256 _bablPrice, uint256 _purchaseAssetPrice, uint256 _slippage, address _hopToken ) external override { _onlyKeeper(); require(assetForPurchases != address(0), 'Asset for purchases not set'); require(_bablPriceProtectionAt > 0 && _bablPrice <= _bablPriceProtectionAt, 'Price is above target'); require( SafeDecimalMath.normalizeAmountTokens( assetForPurchases, address(DAI), _purchaseAssetPrice.preciseMul(IERC20(assetForPurchases).balanceOf(address(this))) ) >= PROTECT_BUY_AMOUNT_DAI, 'Not enough to protect' ); uint256 exactAmount = PROTECT_BUY_AMOUNT_DAI.preciseDiv(_bablPrice); uint256 minAmountOut = exactAmount.sub(exactAmount.preciseMul(_slippage == 0 ? tradeSlippage : _slippage)); uint256 bablBought = _trade( assetForPurchases, address(BABL), SafeDecimalMath.normalizeAmountTokens( address(DAI), assetForPurchases, PROTECT_BUY_AMOUNT_DAI.preciseDiv(_purchaseAssetPrice) ), minAmountOut, _hopToken != address(0) ? _hopToken : address(WETH) ); totalStats[2] = totalStats[2].add(bablBought); emit BablBuyback(block.timestamp, PROTECT_BUY_AMOUNT_DAI, bablBought); } // solhint-disable-next-line receive() external payable {} /* ============ External View Functions ============ */ /** * Getter to get the whole array of voted gardens * * @return The array of voted gardens */ function getVotedGardens() external view override returns (address[] memory) { return votedGardens; } /** * Getter to get the whole array of garden weights * * @return The array of weights for voted gardens */ function getGardenWeights() external view override returns (uint256[] memory) { return gardenWeights; } /** * Getter to get the whole array of fee weights * * @return The array of weights for the fees */ function getFeeDistributionWeights() external view override returns (uint256[] memory) { return feeDistributionWeights; } /** * Getter to get the whole array of total stats * * @return The array of stats for the fees */ function getTotalStats() external view override returns (uint256[7] memory) { return totalStats; } /** * Implements EIP-1271 */ function isValidSignature(bytes32 _hash, bytes memory _signature) public view override returns (bytes4 magicValue) { address recovered = ECDSA.recover(_hash, _signature); return recovered == signer && recovered != address(0) ? this.isValidSignature.selector : bytes4(0); } /* ============ Internal Functions ============ */ function _bondToBABL( address _assetToBond, uint256 _amountToBond, uint256 _priceInBABL ) private view returns (uint256) { return SafeDecimalMath.normalizeAmountTokens(_assetToBond, address(BABL), _amountToBond).preciseMul( _priceInBABL.preciseMul(uint256(1e18).add(bondAssets[_assetToBond])) ); } /** * Consolidates all reserve asset fees to weth * */ function _consolidateFeesToWeth() private { address[] memory reserveAssets = controller.getReserveAssets(); for (uint256 i = 0; i < reserveAssets.length; i++) { address reserveAsset = reserveAssets[i]; uint256 balance = IERC20(reserveAsset).balanceOf(address(this)); // Trade if it's above a min amount (otherwise wait until next pump) if (reserveAsset != address(BABL) && reserveAsset != address(WETH) && balance > minAmounts[reserveAsset]) { totalStats[0] = totalStats[0].add(_trade(reserveAsset, address(WETH), balance)); } if (reserveAsset == address(WETH)) { totalStats[0] = totalStats[0].add(balance); } } emit FeesCollected(block.timestamp, IERC20(WETH).balanceOf(address(this))); } /** * Buys back BABL through the uniswap V3 BABL-ETH pool * */ function _buyback(uint256 _amount) private { // Gift 50% BABL back to garden and send 50% to the treasury uint256 bablBought = _trade(address(WETH), address(BABL), _amount); // 50% IERC20(BABL).safeTransfer(address(heartGarden), bablBought.div(2)); IERC20(BABL).safeTransfer(treasury, bablBought.div(2)); totalStats[2] = totalStats[2].add(bablBought); emit BablBuyback(block.timestamp, _amount, bablBought); } /** * Adds liquidity to the BABL-ETH pair through the hypervisor * * Note: Address of the heart needs to be whitelisted by Visor. */ function _addLiquidity(uint256 _wethBalance) private { // Buy BABL again with half to add 50/50 uint256 wethToDeposit = _wethBalance.preciseMul(5e17); uint256 bablTraded = _trade(address(WETH), address(BABL), wethToDeposit); // 50% BABL.safeApprove(address(visor), bablTraded); IERC20(WETH).safeApprove(address(visor), wethToDeposit); uint256 oldTreasuryBalance = visor.balanceOf(treasury); uint256 shares = visor.deposit(wethToDeposit, bablTraded, treasury); _require( shares == visor.balanceOf(treasury).sub(oldTreasuryBalance) && visor.balanceOf(treasury) > 0, Errors.HEART_LP_TOKENS ); totalStats[3] += _wethBalance; emit LiquidityAdded(block.timestamp, wethToDeposit, bablTraded); } /** * Invests in gardens using WETH converting it to garden reserve asset first * * @param _wethAmount Total amount of weth to invest in all gardens */ function _investInGardens(uint256 _wethAmount) private { for (uint256 i = 0; i < votedGardens.length; i++) { address reserveAsset = IGarden(votedGardens[i]).reserveAsset(); uint256 amountTraded; if (reserveAsset != address(WETH)) { amountTraded = _trade(address(WETH), reserveAsset, _wethAmount.preciseMul(gardenWeights[i])); } else { amountTraded = _wethAmount.preciseMul(gardenWeights[i]); } // Gift it to garden IERC20(reserveAsset).safeTransfer(votedGardens[i], amountTraded); emit GardenSeedInvest(block.timestamp, votedGardens[i], _wethAmount.preciseMul(gardenWeights[i])); } totalStats[4] += _wethAmount; } /** * Lends an amount of WETH converting it first to the pool asset that is the lowest (except BABL) * * @param _fromAsset Which asset to convert * @param _fromAmount Total amount of weth to lend * @param _lendAsset Address of the asset to lend */ function _lendFusePool( address _fromAsset, uint256 _fromAmount, address _lendAsset ) private { address cToken = assetToCToken[_lendAsset]; _require(cToken != address(0), Errors.HEART_INVALID_CTOKEN); uint256 assetToLendBalance = _fromAmount; // Trade to asset to lend if needed if (_fromAsset != _lendAsset) { assetToLendBalance = _trade( address(_fromAsset), _lendAsset == address(0) ? address(WETH) : _lendAsset, _fromAmount ); } if (_lendAsset == address(0)) { // Convert WETH to ETH IWETH(WETH).withdraw(_fromAmount); ICEther(cToken).mint{value: _fromAmount}(); } else { IERC20(_lendAsset).safeApprove(cToken, assetToLendBalance); ICToken(cToken).mint(assetToLendBalance); } uint256 assetToLendWethPrice = IPriceOracle(controller.priceOracle()).getPrice(_lendAsset, address(WETH)); uint256 assettoLendBalanceInWeth = assetToLendBalance.preciseMul(assetToLendWethPrice); totalStats[5] = totalStats[5].add(assettoLendBalanceInWeth); emit FuseLentAsset(block.timestamp, _lendAsset, assettoLendBalanceInWeth); } /** * Sends the weekly BABL reward to the garden (if any) */ function _sendWeeklyReward() private { if (bablRewardLeft > 0) { uint256 bablToSend = bablRewardLeft < weeklyRewardAmount ? bablRewardLeft : weeklyRewardAmount; uint256 currentBalance = IERC20(BABL).balanceOf(address(this)); bablToSend = currentBalance < bablToSend ? currentBalance : bablToSend; IERC20(BABL).safeTransfer(address(heartGarden), bablToSend); bablRewardLeft = bablRewardLeft.sub(bablToSend); emit BABLRewardSent(block.timestamp, bablToSend); totalStats[6] = totalStats[6].add(bablToSend); } } /** * Trades _tokenIn to _tokenOut using Uniswap V3 * * @param _tokenIn Token that is sold * @param _tokenOut Token that is purchased * @param _amount Amount of tokenin to sell */ function _trade( address _tokenIn, address _tokenOut, uint256 _amount ) private returns (uint256) { if (_tokenIn == _tokenOut) { return _amount; } // Uses on chain oracle for all internal strategy operations to avoid attacks uint256 pricePerTokenUnit = IPriceOracle(controller.priceOracle()).getPrice(_tokenIn, _tokenOut); _require(pricePerTokenUnit != 0, Errors.NO_PRICE_FOR_TRADE); // minAmount must have receive token decimals uint256 exactAmount = SafeDecimalMath.normalizeAmountTokens(_tokenIn, _tokenOut, _amount.preciseMul(pricePerTokenUnit)); uint256 minAmountOut = exactAmount.sub(exactAmount.preciseMul(tradeSlippage)); return _trade(_tokenIn, _tokenOut, _amount, minAmountOut, address(0)); } /** * Trades _tokenIn to _tokenOut using Uniswap V3 * * @param _tokenIn Token that is sold * @param _tokenOut Token that is purchased * @param _amount Amount of tokenin to sell * @param _minAmountOut Min amount of tokens out to recive * @param _hopToken Hop token to use for UniV3 trade */ function _trade( address _tokenIn, address _tokenOut, uint256 _amount, uint256 _minAmountOut, address _hopToken ) private returns (uint256) { ISwapRouter swapRouter = ISwapRouter(0xE592427A0AEce92De3Edee1F18E0157C05861564); // Approve the router to spend token in. TransferHelper.safeApprove(_tokenIn, address(swapRouter), _amount); bytes memory path; if ( (_tokenIn == address(FRAX) && _tokenOut != address(DAI)) || (_tokenOut == address(FRAX) && _tokenIn != address(DAI)) ) { _hopToken = address(DAI); } if (_hopToken != address(0)) { uint24 fee0 = _getUniswapPoolFeeWithHighestLiquidity(_tokenIn, _hopToken); uint24 fee1 = _getUniswapPoolFeeWithHighestLiquidity(_tokenOut, _hopToken); // Have to use WETH for BABL because the most liquid pari is WETH/BABL if (_tokenOut == address(BABL) && _hopToken != address(WETH)) { path = abi.encodePacked( _tokenIn, fee0, _hopToken, fee1, address(WETH), _getUniswapPoolFeeWithHighestLiquidity(address(WETH), _tokenOut), _tokenOut ); } else { path = abi.encodePacked(_tokenIn, fee0, _hopToken, fee1, _tokenOut); } } else { uint24 fee = _getUniswapPoolFeeWithHighestLiquidity(_tokenIn, _tokenOut); path = abi.encodePacked(_tokenIn, fee, _tokenOut); } ISwapRouter.ExactInputParams memory params = ISwapRouter.ExactInputParams(path, address(this), block.timestamp, _amount, _minAmountOut); return swapRouter.exactInput(params); } /** * Returns the FEE of the highest liquidity pool in univ3 for this pair * @param sendToken Token that is sold * @param receiveToken Token that is purchased */ function _getUniswapPoolFeeWithHighestLiquidity(address sendToken, address receiveToken) private view returns (uint24) { IUniswapV3Pool poolLow = IUniswapV3Pool(factory.getPool(sendToken, receiveToken, FEE_LOW)); IUniswapV3Pool poolMedium = IUniswapV3Pool(factory.getPool(sendToken, receiveToken, FEE_MEDIUM)); IUniswapV3Pool poolHigh = IUniswapV3Pool(factory.getPool(sendToken, receiveToken, FEE_HIGH)); uint128 liquidityLow = address(poolLow) != address(0) ? poolLow.liquidity() : 0; uint128 liquidityMedium = address(poolMedium) != address(0) ? poolMedium.liquidity() : 0; uint128 liquidityHigh = address(poolHigh) != address(0) ? poolHigh.liquidity() : 0; if (liquidityLow >= liquidityMedium && liquidityLow >= liquidityHigh) { return FEE_LOW; } if (liquidityMedium >= liquidityLow && liquidityMedium >= liquidityHigh) { return FEE_MEDIUM; } return FEE_HIGH; } } contract HeartV4 is Heart { constructor(IBabController _controller, IGovernor _governor) Heart(_controller, _governor) {} } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "../utils/ContextUpgradeable.sol"; import "../proxy/Initializable.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract OwnableUpgradeable is Initializable, ContextUpgradeable { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ function __Ownable_init() internal initializer { __Context_init_unchained(); __Ownable_init_unchained(); } function __Ownable_init_unchained() internal initializer { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } uint256[49] private __gap; } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "../../utils/Context.sol"; import "./IERC20.sol"; import "../../math/SafeMath.sol"; /** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20PresetMinterPauser}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin guidelines: functions revert instead * of returning `false` on failure. This behavior is nonetheless conventional * and does not conflict with the expectations of ERC20 applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */ contract ERC20 is Context, IERC20 { using SafeMath for uint256; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; uint8 private _decimals; /** * @dev Sets the values for {name} and {symbol}, initializes {decimals} with * a default value of 18. * * To select a different value for {decimals}, use {_setupDecimals}. * * All three of these values are immutable: they can only be set once during * construction. */ constructor (string memory name_, string memory symbol_) public { _name = name_; _symbol = symbol_; _decimals = 18; } /** * @dev Returns the name of the token. */ function name() public view 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 { } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "./IERC20.sol"; import "../../math/SafeMath.sol"; import "../../utils/Address.sol"; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using SafeMath for uint256; using Address for address; function safeTransfer(IERC20 token, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove(IERC20 token, address spender, uint256 value) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' // solhint-disable-next-line max-line-length require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).add(value); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero"); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Elliptic Curve Digital Signature Algorithm (ECDSA) operations. * * These functions can be used to verify that a message was signed by the holder * of the private keys of a given address. */ library ECDSA { /** * @dev Returns the address that signed a hashed message (`hash`) with * `signature`. This address can then be used for verification purposes. * * The `ecrecover` EVM opcode allows for malleable (non-unique) signatures: * this function rejects them by requiring the `s` value to be in the lower * half order, and the `v` value to be either 27 or 28. * * IMPORTANT: `hash` _must_ be the result of a hash operation for the * verification to be secure: it is possible to craft signatures that * recover to arbitrary addresses for non-hashed data. A safe way to ensure * this is by receiving a hash of the original message (which may otherwise * be too long), and then calling {toEthSignedMessageHash} on it. */ function recover(bytes32 hash, bytes memory signature) internal pure returns (address) { // Check the signature length if (signature.length != 65) { revert("ECDSA: invalid signature length"); } // Divide the signature in r, s and v variables bytes32 r; bytes32 s; uint8 v; // ecrecover takes the signature parameters, and the only way to get them // currently is to use assembly. // solhint-disable-next-line no-inline-assembly assembly { r := mload(add(signature, 0x20)) s := mload(add(signature, 0x40)) v := byte(0, mload(add(signature, 0x60))) } return recover(hash, v, r, s); } /** * @dev Overload of {ECDSA-recover-bytes32-bytes-} that receives the `v`, * `r` and `s` signature fields separately. */ function recover(bytes32 hash, uint8 v, bytes32 r, bytes32 s) internal pure returns (address) { // EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature // unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines // the valid range for s in (281): 0 < s < secp256k1n ÷ 2 + 1, and for v in (282): v ∈ {27, 28}. Most // signatures from current libraries generate a unique signature with an s-value in the lower half order. // // If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value // with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or // vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept // these malleable signatures as well. require(uint256(s) <= 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0, "ECDSA: invalid signature 's' value"); require(v == 27 || v == 28, "ECDSA: invalid signature 'v' value"); // If the signature is valid (and not malleable), return the signer address address signer = ecrecover(hash, v, r, s); require(signer != address(0), "ECDSA: invalid signature"); return signer; } /** * @dev Returns an Ethereum Signed Message, created from a `hash`. This * replicates the behavior of the * https://github.com/ethereum/wiki/wiki/JSON-RPC#eth_sign[`eth_sign`] * JSON-RPC method. * * See {recover}. */ function toEthSignedMessageHash(bytes32 hash) internal pure returns (bytes32) { // 32 is the length in bytes of hash, // enforced by the type signature above return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hash)); } } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.5.0; /// @title The interface for the Uniswap V3 Factory /// @notice The Uniswap V3 Factory facilitates creation of Uniswap V3 pools and control over the protocol fees interface IUniswapV3Factory { /// @notice Emitted when the owner of the factory is changed /// @param oldOwner The owner before the owner was changed /// @param newOwner The owner after the owner was changed event OwnerChanged(address indexed oldOwner, address indexed newOwner); /// @notice Emitted when a pool is created /// @param token0 The first token of the pool by address sort order /// @param token1 The second token of the pool by address sort order /// @param fee The fee collected upon every swap in the pool, denominated in hundredths of a bip /// @param tickSpacing The minimum number of ticks between initialized ticks /// @param pool The address of the created pool event PoolCreated( address indexed token0, address indexed token1, uint24 indexed fee, int24 tickSpacing, address pool ); /// @notice Emitted when a new fee amount is enabled for pool creation via the factory /// @param fee The enabled fee, denominated in hundredths of a bip /// @param tickSpacing The minimum number of ticks between initialized ticks for pools created with the given fee event FeeAmountEnabled(uint24 indexed fee, int24 indexed tickSpacing); /// @notice Returns the current owner of the factory /// @dev Can be changed by the current owner via setOwner /// @return The address of the factory owner function owner() external view returns (address); /// @notice Returns the tick spacing for a given fee amount, if enabled, or 0 if not enabled /// @dev A fee amount can never be removed, so this value should be hard coded or cached in the calling context /// @param fee The enabled fee, denominated in hundredths of a bip. Returns 0 in case of unenabled fee /// @return The tick spacing function feeAmountTickSpacing(uint24 fee) external view returns (int24); /// @notice Returns the pool address for a given pair of tokens and a fee, or address 0 if it does not exist /// @dev tokenA and tokenB may be passed in either token0/token1 or token1/token0 order /// @param tokenA The contract address of either token0 or token1 /// @param tokenB The contract address of the other token /// @param fee The fee collected upon every swap in the pool, denominated in hundredths of a bip /// @return pool The pool address function getPool( address tokenA, address tokenB, uint24 fee ) external view returns (address pool); /// @notice Creates a pool for the given two tokens and fee /// @param tokenA One of the two tokens in the desired pool /// @param tokenB The other of the two tokens in the desired pool /// @param fee The desired fee for the pool /// @dev tokenA and tokenB may be passed in either order: token0/token1 or token1/token0. tickSpacing is retrieved /// from the fee. The call will revert if the pool already exists, the fee is invalid, or the token arguments /// are invalid. /// @return pool The address of the newly created pool function createPool( address tokenA, address tokenB, uint24 fee ) external returns (address pool); /// @notice Updates the owner of the factory /// @dev Must be called by the current owner /// @param _owner The new owner of the factory function setOwner(address _owner) external; /// @notice Enables a fee amount with the given tickSpacing /// @dev Fee amounts may never be removed once enabled /// @param fee The fee amount to enable, denominated in hundredths of a bip (i.e. 1e-6) /// @param tickSpacing The spacing between ticks to be enforced for all pools created with the given fee amount function enableFeeAmount(uint24 fee, int24 tickSpacing) external; } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.7.5; pragma abicoder v2; import '@uniswap/v3-core/contracts/interfaces/callback/IUniswapV3SwapCallback.sol'; /// @title Router token swapping functionality /// @notice Functions for swapping tokens via Uniswap V3 interface ISwapRouter is IUniswapV3SwapCallback { struct ExactInputSingleParams { address tokenIn; address tokenOut; uint24 fee; address recipient; uint256 deadline; uint256 amountIn; uint256 amountOutMinimum; uint160 sqrtPriceLimitX96; } /// @notice Swaps `amountIn` of one token for as much as possible of another token /// @param params The parameters necessary for the swap, encoded as `ExactInputSingleParams` in calldata /// @return amountOut The amount of the received token function exactInputSingle(ExactInputSingleParams calldata params) external payable returns (uint256 amountOut); struct ExactInputParams { bytes path; address recipient; uint256 deadline; uint256 amountIn; uint256 amountOutMinimum; } /// @notice Swaps `amountIn` of one token for as much as possible of another along the specified path /// @param params The parameters necessary for the multi-hop swap, encoded as `ExactInputParams` in calldata /// @return amountOut The amount of the received token function exactInput(ExactInputParams calldata params) external payable returns (uint256 amountOut); struct ExactOutputSingleParams { address tokenIn; address tokenOut; uint24 fee; address recipient; uint256 deadline; uint256 amountOut; uint256 amountInMaximum; uint160 sqrtPriceLimitX96; } /// @notice Swaps as little as possible of one token for `amountOut` of another token /// @param params The parameters necessary for the swap, encoded as `ExactOutputSingleParams` in calldata /// @return amountIn The amount of the input token function exactOutputSingle(ExactOutputSingleParams calldata params) external payable returns (uint256 amountIn); struct ExactOutputParams { bytes path; address recipient; uint256 deadline; uint256 amountOut; uint256 amountInMaximum; } /// @notice Swaps as little as possible of one token for `amountOut` of another along the specified path (reversed) /// @param params The parameters necessary for the multi-hop swap, encoded as `ExactOutputParams` in calldata /// @return amountIn The amount of the input token function exactOutput(ExactOutputParams calldata params) external payable returns (uint256 amountIn); } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.6.0; import '@openzeppelin/contracts/token/ERC20/IERC20.sol'; library TransferHelper { /// @notice Transfers tokens from the targeted address to the given destination /// @notice Errors with 'STF' if transfer fails /// @param token The contract address of the token to be transferred /// @param from The originating address from which the tokens will be transferred /// @param to The destination address of the transfer /// @param value The amount to be transferred function safeTransferFrom( address token, address from, address to, uint256 value ) internal { (bool success, bytes memory data) = token.call(abi.encodeWithSelector(IERC20.transferFrom.selector, from, to, value)); require(success && (data.length == 0 || abi.decode(data, (bool))), 'STF'); } /// @notice Transfers tokens from msg.sender to a recipient /// @dev Errors with ST if transfer fails /// @param token The contract address of the token which will be transferred /// @param to The recipient of the transfer /// @param value The value of the transfer function safeTransfer( address token, address to, uint256 value ) internal { (bool success, bytes memory data) = token.call(abi.encodeWithSelector(IERC20.transfer.selector, to, value)); require(success && (data.length == 0 || abi.decode(data, (bool))), 'ST'); } /// @notice Approves the stipulated contract to spend the given allowance in the given token /// @dev Errors with 'SA' if transfer fails /// @param token The contract address of the token to be approved /// @param to The target of the approval /// @param value The amount of the given token the target will be allowed to spend function safeApprove( address token, address to, uint256 value ) internal { (bool success, bytes memory data) = token.call(abi.encodeWithSelector(IERC20.approve.selector, to, value)); require(success && (data.length == 0 || abi.decode(data, (bool))), 'SA'); } /// @notice Transfers ETH to the recipient address /// @dev Fails with `STE` /// @param to The destination of the transfer /// @param value The value to be transferred function safeTransferETH(address to, uint256 value) internal { (bool success, ) = to.call{value: value}(new bytes(0)); require(success, 'STE'); } } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.5.0; import './pool/IUniswapV3PoolImmutables.sol'; import './pool/IUniswapV3PoolState.sol'; import './pool/IUniswapV3PoolDerivedState.sol'; import './pool/IUniswapV3PoolActions.sol'; import './pool/IUniswapV3PoolOwnerActions.sol'; import './pool/IUniswapV3PoolEvents.sol'; /// @title The interface for a Uniswap V3 Pool /// @notice A Uniswap pool facilitates swapping and automated market making between any two assets that strictly conform /// to the ERC20 specification /// @dev The pool interface is broken up into many smaller pieces interface IUniswapV3Pool is IUniswapV3PoolImmutables, IUniswapV3PoolState, IUniswapV3PoolDerivedState, IUniswapV3PoolActions, IUniswapV3PoolOwnerActions, IUniswapV3PoolEvents { } // SPDX-License-Identifier: GPL-3.0-only pragma solidity 0.7.6; pragma abicoder v2; import '@openzeppelin/contracts/token/ERC20/IERC20.sol'; interface IHypervisor { // @param deposit0 Amount of token0 transfered from sender to Hypervisor // @param deposit1 Amount of token0 transfered from sender to Hypervisor // @param to Address to which liquidity tokens are minted // @return shares Quantity of liquidity tokens minted as a result of deposit function deposit( uint256 deposit0, uint256 deposit1, address to ) external returns (uint256); // @param shares Number of liquidity tokens to redeem as pool assets // @param to Address to which redeemed pool assets are sent // @param from Address from which liquidity tokens are sent // @return amount0 Amount of token0 redeemed by the submitted liquidity tokens // @return amount1 Amount of token1 redeemed by the submitted liquidity tokens function withdraw( uint256 shares, address to, address from ) external returns (uint256, uint256); function rebalance( int24 _baseLower, int24 _baseUpper, int24 _limitLower, int24 _limitUpper, address _feeRecipient, int256 swapQuantity ) external; function addBaseLiquidity(uint256 amount0, uint256 amount1) external; function addLimitLiquidity(uint256 amount0, uint256 amount1) external; function pullLiquidity(uint256 shares) external returns ( uint256 base0, uint256 base1, uint256 limit0, uint256 limit1 ); function token0() external view returns (IERC20); function token1() external view returns (IERC20); function pool() external view returns (address); function balanceOf(address) external view returns (uint256); function approve(address, uint256) external returns (bool); function transferFrom( address, address, uint256 ) external returns (bool); function transfer(address, uint256) external returns (bool); function getTotalAmounts() external view returns (uint256 total0, uint256 total1); function pendingFees() external returns (uint256 fees0, uint256 fees1); function totalSupply() external view returns (uint256); function setMaxTotalSupply(uint256 _maxTotalSupply) external; function setDepositMax(uint256 _deposit0Max, uint256 _deposit1Max) external; function appendList(address[] memory listed) external; function toggleWhitelist() external; function transferOwnership(address newOwner) external; } // SPDX-License-Identifier: Apache-2.0 pragma solidity 0.7.6; /** * @title IBabController * @author Babylon Finance * * Interface for interacting with BabController */ interface IBabController { /* ============ Functions ============ */ function createGarden( address _reserveAsset, string memory _name, string memory _symbol, string memory _tokenURI, uint256 _seed, uint256[] calldata _gardenParams, uint256 _initialContribution, bool[] memory _publicGardenStrategistsStewards, uint256[] memory _profitSharing ) external payable returns (address); function removeGarden(address _garden) external; function addReserveAsset(address _reserveAsset) external; function removeReserveAsset(address _reserveAsset) external; function updateProtocolWantedAsset(address _wantedAsset, bool _wanted) external; function updateGardenAffiliateRate(address _garden, uint256 _affiliateRate) external; function addAffiliateReward(address _user, uint256 _reserveAmount) external; function claimRewards() external; function editPriceOracle(address _priceOracle) external; function editMardukGate(address _mardukGate) external; function editGardenValuer(address _gardenValuer) external; function editTreasury(address _newTreasury) external; function editHeart(address _newHeart) external; function editRewardsDistributor(address _rewardsDistributor) external; function editGardenFactory(address _newGardenFactory) external; function editGardenNFT(address _newGardenNFT) external; function editCurveMetaRegistry(address _curveMetaRegistry) external; function editStrategyNFT(address _newStrategyNFT) external; function editStrategyFactory(address _newStrategyFactory) external; function setOperation(uint8 _kind, address _operation) external; function setMasterSwapper(address _newMasterSwapper) external; function addKeeper(address _keeper) external; function addKeepers(address[] memory _keepers) external; function removeKeeper(address _keeper) external; function enableGardenTokensTransfers() external; function editLiquidityReserve(address _reserve, uint256 _minRiskyPairLiquidityEth) external; function gardenCreationIsOpen() external view returns (bool); function owner() external view returns (address); function EMERGENCY_OWNER() external view returns (address); function guardianGlobalPaused() external view returns (bool); function guardianPaused(address _address) external view returns (bool); function setPauseGuardian(address _guardian) external; function setGlobalPause(bool _state) external returns (bool); function setSomePause(address[] memory _address, bool _state) external returns (bool); function isPaused(address _contract) external view returns (bool); function priceOracle() external view returns (address); function gardenValuer() external view returns (address); function heart() external view returns (address); function gardenNFT() external view returns (address); function strategyNFT() external view returns (address); function curveMetaRegistry() external view returns (address); function rewardsDistributor() external view returns (address); function gardenFactory() external view returns (address); function treasury() external view returns (address); function ishtarGate() external view returns (address); function mardukGate() external view returns (address); function strategyFactory() external view returns (address); function masterSwapper() external view returns (address); function gardenTokensTransfersEnabled() external view returns (bool); function bablMiningProgramEnabled() external view returns (bool); function allowPublicGardens() external view returns (bool); function enabledOperations(uint256 _kind) external view returns (address); function getGardens() external view returns (address[] memory); function getReserveAssets() external view returns (address[] memory); function getOperations() external view returns (address[20] memory); function isGarden(address _garden) external view returns (bool); function protocolWantedAssets(address _wantedAsset) external view returns (bool); function gardenAffiliateRates(address _wantedAsset) external view returns (uint256); function affiliateRewards(address _user) external view returns (uint256); function isValidReserveAsset(address _reserveAsset) external view returns (bool); function isValidKeeper(address _keeper) external view returns (bool); function isSystemContract(address _contractAddress) external view returns (bool); function protocolPerformanceFee() external view returns (uint256); function protocolManagementFee() external view returns (uint256); function minLiquidityPerReserve(address _reserve) external view returns (uint256); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (governance/IGovernor.sol) pragma solidity ^0.7.6; pragma abicoder v2; /** * @dev Interface of the {Governor} core. * * _Available since v4.3._ */ abstract contract IGovernor { enum ProposalState {Pending, Active, Canceled, Defeated, Succeeded, Queued, Expired, Executed} /** * @dev Emitted when a proposal is created. */ event ProposalCreated( uint256 proposalId, address proposer, address[] targets, uint256[] values, string[] signatures, bytes[] calldatas, uint256 startBlock, uint256 endBlock, string description ); /** * @dev Emitted when a proposal is canceled. */ event ProposalCanceled(uint256 proposalId); /** * @dev Emitted when a proposal is executed. */ event ProposalExecuted(uint256 proposalId); /** * @dev Emitted when a vote is cast. * * Note: `support` values should be seen as buckets. There interpretation depends on the voting module used. */ event VoteCast(address indexed voter, uint256 proposalId, uint8 support, uint256 weight, string reason); /** * @notice module:core * @dev Name of the governor instance (used in building the ERC712 domain separator). */ function name() public view virtual returns (string memory); /** * @notice module:core * @dev Version of the governor instance (used in building the ERC712 domain separator). Default: "1" */ function version() public view virtual returns (string memory); function proposals(uint256 _proposalId) public view virtual returns ( uint256, address, uint256, uint256, uint256, uint256, uint256, uint256, bool, bool ); /** * @notice module:voting * @dev A description of the possible `support` values for {castVote} and the way these votes are counted, meant to * be consumed by UIs to show correct vote options and interpret the results. The string is a URL-encoded sequence of * key-value pairs that each describe one aspect, for example `support=bravo&quorum=for,abstain`. * * There are 2 standard keys: `support` and `quorum`. * * - `support=bravo` refers to the vote options 0 = Against, 1 = For, 2 = Abstain, as in `GovernorBravo`. * - `quorum=bravo` means that only For votes are counted towards quorum. * - `quorum=for,abstain` means that both For and Abstain votes are counted towards quorum. * * NOTE: The string can be decoded by the standard * https://developer.mozilla.org/en-US/docs/Web/API/URLSearchParams[`URLSearchParams`] * JavaScript class. */ // solhint-disable-next-line func-name-mixedcase function COUNTING_MODE() public pure virtual returns (string memory); /** * @notice module:core * @dev Hashing function used to (re)build the proposal id from the proposal details.. */ function hashProposal( address[] calldata targets, uint256[] calldata values, bytes[] calldata calldatas, bytes32 descriptionHash ) public pure virtual returns (uint256); /** * @notice module:core * @dev Current state of a proposal, following Compound's convention */ function state(uint256 proposalId) public view virtual returns (ProposalState); /** * @notice module:core * @dev Block number used to retrieve user's votes and quorum. As per Compound's Comp and OpenZeppelin's * ERC20Votes, the snapshot is performed at the end of this block. Hence, voting for this proposal starts at the * beginning of the following block. */ function proposalSnapshot(uint256 proposalId) public view virtual returns (uint256); /** * @notice module:core * @dev Block number at which votes close. Votes close at the end of this block, so it is possible to cast a vote * during this block. */ function proposalDeadline(uint256 proposalId) public view virtual returns (uint256); /** * @notice module:user-config * @dev Delay, in number of block, between the proposal is created and the vote starts. This can be increassed to * leave time for users to buy voting power, of delegate it, before the voting of a proposal starts. */ function votingDelay() public view virtual returns (uint256); /** * @notice module:user-config * @dev Delay, in number of blocks, between the vote start and vote ends. * * NOTE: The {votingDelay} can delay the start of the vote. This must be considered when setting the voting * duration compared to the voting delay. */ function votingPeriod() public view virtual returns (uint256); /** * @notice module:user-config * @dev Minimum number of cast voted required for a proposal to be successful. * * Note: The `blockNumber` parameter corresponds to the snaphot used for counting vote. This allows to scale the * quroum depending on values such as the totalSupply of a token at this block (see {ERC20Votes}). */ function quorum(uint256 blockNumber) public view virtual returns (uint256); /** * @notice module:reputation * @dev Voting power of an `account` at a specific `blockNumber`. * * Note: this can be implemented in a number of ways, for example by reading the delegated balance from one (or * multiple), {ERC20Votes} tokens. */ function getVotes(address account, uint256 blockNumber) public view virtual returns (uint256); /** * @notice module:voting * @dev Returns weither `account` has cast a vote on `proposalId`. */ function hasVoted(uint256 proposalId, address account) public view virtual returns (bool); /** * @dev Create a new proposal. Vote start {IGovernor-votingDelay} blocks after the proposal is created and ends * {IGovernor-votingPeriod} blocks after the voting starts. * * Emits a {ProposalCreated} event. */ function propose( address[] memory targets, uint256[] memory values, bytes[] memory calldatas, string memory description ) public virtual returns (uint256 proposalId); /** * @dev Execute a successful proposal. This requires the quorum to be reached, the vote to be successful, and the * deadline to be reached. * * Emits a {ProposalExecuted} event. * * Note: some module can modify the requirements for execution, for example by adding an additional timelock. */ function execute( address[] memory targets, uint256[] memory values, bytes[] memory calldatas, bytes32 descriptionHash ) public payable virtual returns (uint256 proposalId); /** * @dev Cast a vote * * Emits a {VoteCast} event. */ function castVote(uint256 proposalId, uint8 support) public virtual returns (uint256 balance); /** * @dev Cast a vote with a reason * * Emits a {VoteCast} event. */ function castVoteWithReason( uint256 proposalId, uint8 support, string calldata reason ) public virtual returns (uint256 balance); /** * @dev Cast a vote using the user cryptographic signature. * * Emits a {VoteCast} event. */ function castVoteBySig( uint256 proposalId, uint8 support, uint8 v, bytes32 r, bytes32 s ) public virtual returns (uint256 balance); } // SPDX-License-Identifier: Apache-2.0 pragma solidity 0.7.6; import {IERC20} from '@openzeppelin/contracts/token/ERC20/IERC20.sol'; import {IERC1271} from '../interfaces/IERC1271.sol'; import {IBabController} from './IBabController.sol'; /** * @title IStrategyGarden * * Interface for functions of the garden */ interface IStrategyGarden { /* ============ Write ============ */ function finalizeStrategy( uint256 _profits, int256 _returns, uint256 _burningAmount ) external; function allocateCapitalToStrategy(uint256 _capital) external; function expireCandidateStrategy(address _strategy) external; function addStrategy( string memory _name, string memory _symbol, uint256[] calldata _stratParams, uint8[] calldata _opTypes, address[] calldata _opIntegrations, bytes calldata _opEncodedDatas ) external; function updateStrategyRewards( address _strategy, uint256 _newTotalAmount, uint256 _newCapitalReturned ) external; function payKeeper(address payable _keeper, uint256 _fee) external; } /** * @title IAdminGarden * * Interface for amdin functions of the Garden */ interface IAdminGarden { /* ============ Write ============ */ function initialize( address _reserveAsset, IBabController _controller, address _creator, string memory _name, string memory _symbol, uint256[] calldata _gardenParams, uint256 _initialContribution, bool[] memory _publicGardenStrategistsStewards ) external payable; function makeGardenPublic() external; function transferCreatorRights(address _newCreator, uint8 _index) external; function addExtraCreators(address[4] memory _newCreators) external; function setPublicRights(bool _publicStrategist, bool _publicStewards) external; function delegateVotes(address _token, address _address) external; function updateCreators(address _newCreator, address[4] memory _newCreators) external; function updateGardenParams(uint256[12] memory _newParams) external; function verifyGarden(uint256 _verifiedCategory) external; function resetHardlock(uint256 _hardlockStartsAt) external; } /** * @title IGarden * * Interface for operating with a Garden. */ interface ICoreGarden { /* ============ Constructor ============ */ /* ============ View ============ */ function privateGarden() external view returns (bool); function publicStrategists() external view returns (bool); function publicStewards() external view returns (bool); function controller() external view returns (IBabController); function creator() external view returns (address); function isGardenStrategy(address _strategy) external view returns (bool); function getContributor(address _contributor) external view returns ( uint256 lastDepositAt, uint256 initialDepositAt, uint256 claimedAt, uint256 claimedBABL, uint256 claimedRewards, uint256 withdrawnSince, uint256 totalDeposits, uint256 nonce, uint256 lockedBalance ); function reserveAsset() external view returns (address); function verifiedCategory() external view returns (uint256); function canMintNftAfter() external view returns (uint256); function hardlockStartsAt() external view returns (uint256); function totalContributors() external view returns (uint256); function gardenInitializedAt() external view returns (uint256); function minContribution() external view returns (uint256); function depositHardlock() external view returns (uint256); function minLiquidityAsset() external view returns (uint256); function minStrategyDuration() external view returns (uint256); function maxStrategyDuration() external view returns (uint256); function reserveAssetRewardsSetAside() external view returns (uint256); function absoluteReturns() external view returns (int256); function totalStake() external view returns (uint256); function minVotesQuorum() external view returns (uint256); function minVoters() external view returns (uint256); function maxDepositLimit() external view returns (uint256); function strategyCooldownPeriod() external view returns (uint256); function getStrategies() external view returns (address[] memory); function extraCreators(uint256 index) external view returns (address); function getFinalizedStrategies() external view returns (address[] memory); function strategyMapping(address _strategy) external view returns (bool); function keeperDebt() external view returns (uint256); function totalKeeperFees() external view returns (uint256); function lastPricePerShare() external view returns (uint256); function lastPricePerShareTS() external view returns (uint256); function pricePerShareDecayRate() external view returns (uint256); function pricePerShareDelta() external view returns (uint256); /* ============ Write ============ */ function deposit( uint256 _amountIn, uint256 _minAmountOut, address _to, address _referrer ) external payable; function depositBySig( uint256 _amountIn, uint256 _minAmountOut, uint256 _nonce, uint256 _maxFee, address _to, uint256 _pricePerShare, uint256 _fee, address _signer, address _referrer, bytes memory signature ) external; function withdraw( uint256 _amountIn, uint256 _minAmountOut, address payable _to, bool _withPenalty, address _unwindStrategy ) external; function withdrawBySig( uint256 _amountIn, uint256 _minAmountOut, uint256 _nonce, uint256 _maxFee, bool _withPenalty, address _unwindStrategy, uint256 _pricePerShare, uint256 _strategyNAV, uint256 _fee, address _signer, bytes memory signature ) external; function claimReturns(address[] calldata _finalizedStrategies) external; function claimAndStakeReturns(uint256 _minAmountOut, address[] calldata _finalizedStrategies) external; function claimRewardsBySig( uint256 _babl, uint256 _profits, uint256 _nonce, uint256 _maxFee, uint256 _fee, address signer, bytes memory signature ) external; function claimAndStakeRewardsBySig( uint256 _babl, uint256 _profits, uint256 _minAmountOut, uint256 _nonce, uint256 _nonceHeart, uint256 _maxFee, uint256 _pricePerShare, uint256 _fee, address _signer, bytes memory _signature ) external; function stakeBySig( uint256 _amountIn, uint256 _profits, uint256 _minAmountOut, uint256 _nonce, uint256 _nonceHeart, uint256 _maxFee, address _to, uint256 _pricePerShare, address _signer, bytes memory _signature ) external; function claimNFT() external; } interface IERC20Metadata { function name() external view returns (string memory); } interface IGarden is ICoreGarden, IAdminGarden, IStrategyGarden, IERC20, IERC20Metadata, IERC1271 { struct Contributor { uint256 lastDepositAt; uint256 initialDepositAt; uint256 claimedAt; uint256 claimedBABL; uint256 claimedRewards; uint256 withdrawnSince; uint256 totalDeposits; uint256 nonce; uint256 lockedBalance; } } // SPDX-License-Identifier: Apache-2.0 pragma solidity 0.7.6; import {IGarden} from './IGarden.sol'; /** * @title IHeart * @author Babylon Finance * * Interface for interacting with the Heart */ interface IHeart { // View functions function getVotedGardens() external view returns (address[] memory); function heartGarden() external view returns (IGarden); function getGardenWeights() external view returns (uint256[] memory); function minAmounts(address _reserve) external view returns (uint256); function assetToCToken(address _asset) external view returns (address); function bondAssets(address _asset) external view returns (uint256); function assetToLend() external view returns (address); function assetForPurchases() external view returns (address); function lastPumpAt() external view returns (uint256); function lastVotesAt() external view returns (uint256); function tradeSlippage() external view returns (uint256); function weeklyRewardAmount() external view returns (uint256); function bablRewardLeft() external view returns (uint256); function getFeeDistributionWeights() external view returns (uint256[] memory); function getTotalStats() external view returns (uint256[7] memory); function votedGardens(uint256 _index) external view returns (address); function gardenWeights(uint256 _index) external view returns (uint256); function feeDistributionWeights(uint256 _index) external view returns (uint256); function totalStats(uint256 _index) external view returns (uint256); // Non-view function pump() external; function voteProposal(uint256 _proposalId, bool _isApprove) external; function resolveGardenVotesAndPump(address[] memory _gardens, uint256[] memory _weights) external; function resolveGardenVotes(address[] memory _gardens, uint256[] memory _weights) external; function updateMarkets() external; function setHeartGardenAddress(address _heartGarden) external; function updateFeeWeights(uint256[] calldata _feeWeights) external; function updateAssetToLend(address _assetToLend) external; function updateAssetToPurchase(address _purchaseAsset) external; function updateBond(address _assetToBond, uint256 _bondDiscount) external; function lendFusePool(address _assetToLend, uint256 _lendAmount) external; function borrowFusePool(address _assetToBorrow, uint256 _borrowAmount) external; function repayFusePool(address _borrowedAsset, uint256 _amountToRepay) external; function protectBABL( uint256 _bablPriceProtectionAt, uint256 _bablPrice, uint256 _pricePurchasingAsset, uint256 _slippage, address _hopToken ) external; function trade( address _fromAsset, address _toAsset, uint256 _fromAmount, uint256 _minAmount ) external; function sellWantedAssetToHeart(address _assetToSell, uint256 _amountToSell) external; function addReward(uint256 _bablAmount, uint256 _weeklyRate) external; function setMinTradeAmount(address _asset, uint256 _minAmount) external; function setTradeSlippage(uint256 _tradeSlippage) external; function bondAsset( address _assetToBond, uint256 _amountToBond, uint256 _minAmountOut, address _referrer ) external; function bondAssetBySig( address _assetToBond, uint256 _amountToBond, uint256 _amountIn, uint256 _minAmountOut, uint256 _nonce, uint256 _maxFee, uint256 _priceInBABL, uint256 _pricePerShare, uint256 _fee, address _contributor, address _referrer, bytes memory _signature ) external; } // SPDX-License-Identifier: MIT pragma solidity >=0.7.0 <0.9.0; import {IERC20} from '@openzeppelin/contracts/token/ERC20/IERC20.sol'; interface IWETH is IERC20 { function deposit() external payable; function withdraw(uint256 wad) external; } // SPDX-License-Identifier: MIT pragma solidity >=0.7.0 <0.9.0; import {IERC20} from '@openzeppelin/contracts/token/ERC20/IERC20.sol'; interface ICToken is IERC20 { function mint(uint256 mintAmount) external returns (uint256); function redeem(uint256 redeemTokens) external returns (uint256); function accrueInterest() external returns (uint256); function redeemUnderlying(uint256 redeemAmount) external returns (uint256); function borrow(uint256 borrowAmount) external returns (uint256); function repayBorrow(uint256 repayAmount) external returns (uint256); function exchangeRateStored() external view returns (uint256); function getCash() external view returns (uint256); function borrowRatePerBlock() external view returns (uint256); function totalBorrows() external view returns (uint256); function underlying() external view returns (address); function getAccountSnapshot(address account) external view returns ( uint256, uint256, uint256, uint256 ); function repayBorrowBehalf(address borrower, uint256 amount) external payable returns (uint256); function borrowBalanceCurrent(address account) external view returns (uint256); function supplyRatePerBlock() external returns (uint256); } // SPDX-License-Identifier: MIT pragma solidity >=0.7.0 <0.9.0; interface ICEther { function mint() external payable; function borrow(uint256 borrowAmount) external returns (uint256); function redeem(uint256 redeemTokens) external returns (uint256); function redeemUnderlying(uint256 redeemAmount) external returns (uint256); function repayBorrow() external payable; function getCash() external view returns (uint256); function repayBorrowBehalf(address borrower) external payable; function borrowBalanceCurrent(address account) external returns (uint256); function borrowBalanceStored(address account) external view returns (uint256); function balanceOf(address owner) external view returns (uint256); function getAccountSnapshot(address account) external view returns ( uint256, uint256, uint256, uint256 ); function exchangeRateCurrent() external returns (uint256); function supplyRatePerBlock() external returns (uint256); } // SPDX-License-Identifier: MIT pragma solidity >=0.7.0 <0.9.0; interface IComptroller { /** * @notice Marker function used for light validation when updating the comptroller of a market * @dev Implementations should simply return true. * @return true */ function isComptroller() external view returns (bool); function markets(address _cToken) external view returns (bool, uint256); function getRewardsDistributors() external view returns (address[] memory); /*** Assets You Are In ***/ function enterMarkets(address[] calldata cTokens) external returns (uint256[] memory); function exitMarket(address cToken) external returns (uint256); function getAllMarkets() external view returns (address[] memory); function _borrowGuardianPaused() external view returns (bool); function borrowGuardianPaused(address _asset) external view returns (bool); function borrowCaps(address _asset) external view returns (uint256); function compAccrued(address holder) external view returns (uint256); /*** Policy Hooks ***/ function getAccountLiquidity(address account) external view returns ( uint256, uint256, uint256 ); function getAssetsIn(address account) external view returns (address[] memory); function mintAllowed( address cToken, address minter, uint256 mintAmount ) external returns (uint256); function mintVerify( address cToken, address minter, uint256 mintAmount, uint256 mintTokens ) external; function redeemAllowed( address cToken, address redeemer, uint256 redeemTokens ) external returns (uint256); function redeemVerify( address cToken, address redeemer, uint256 redeemAmount, uint256 redeemTokens ) external; function borrowAllowed( address cToken, address borrower, uint256 borrowAmount ) external returns (uint256); function borrowVerify( address cToken, address borrower, uint256 borrowAmount ) external; function repayBorrowAllowed( address cToken, address payer, address borrower, uint256 repayAmount ) external returns (uint256); function repayBorrowVerify( address cToken, address payer, address borrower, uint256 repayAmount, uint256 borrowerIndex ) external; function liquidateBorrowAllowed( address cTokenBorrowed, address cTokenCollateral, address liquidator, address borrower, uint256 repayAmount ) external returns (uint256); function liquidateBorrowVerify( address cTokenBorrowed, address cTokenCollateral, address liquidator, address borrower, uint256 repayAmount, uint256 seizeTokens ) external; function seizeAllowed( address cTokenCollateral, address cTokenBorrowed, address liquidator, address borrower, uint256 seizeTokens ) external returns (uint256); function seizeVerify( address cTokenCollateral, address cTokenBorrowed, address liquidator, address borrower, uint256 seizeTokens ) external; function transferAllowed( address cToken, address src, address dst, uint256 transferTokens ) external returns (uint256); function transferVerify( address cToken, address src, address dst, uint256 transferTokens ) external; /*** Liquidity/Liquidation Calculations ***/ function liquidateCalculateSeizeTokens( address cTokenBorrowed, address cTokenCollateral, uint256 repayAmount ) external view returns (uint256, uint256); } // SPDX-License-Identifier: Apache-2.0 pragma solidity 0.7.6; import {ITokenIdentifier} from './ITokenIdentifier.sol'; /** * @title IPriceOracle * @author Babylon Finance * * Interface for interacting with PriceOracle */ interface IPriceOracle { /* ============ Functions ============ */ function getPrice(address _assetOne, address _assetTwo) external view returns (uint256); function getPriceNAV(address _assetOne, address _assetTwo) external view returns (uint256); function updateReserves(address[] memory list) external; function updateMaxTwapDeviation(int24 _maxTwapDeviation) external; function updateTokenIdentifier(ITokenIdentifier _tokenIdentifier) external; function getCompoundExchangeRate(address _asset, address _finalAsset) external view returns (uint256); function getCreamExchangeRate(address _asset, address _finalAsset) external view returns (uint256); } // SPDX-License-Identifier: Apache-2.0 pragma solidity 0.7.6; import {ITradeIntegration} from './ITradeIntegration.sol'; /** * @title IIshtarGate * @author Babylon Finance * * Interface for interacting with the Gate Guestlist NFT */ interface IMasterSwapper is ITradeIntegration { /* ============ Functions ============ */ function isTradeIntegration(address _integration) external view returns (bool); } // SPDX-License-Identifier: Apache-2.0 pragma solidity 0.7.6; import {IERC20} from '@openzeppelin/contracts/token/ERC20/IERC20.sol'; interface IVoteToken { function delegate(address delegatee) external; function delegateBySig( address delegatee, uint256 nonce, uint256 expiry, uint8 v, bytes32 r, bytes32 s, bool prefix ) external; function getCurrentVotes(address account) external view returns (uint96); function getPriorVotes(address account, uint256 blockNumber) external view returns (uint96); function getMyDelegatee() external view returns (address); function getDelegatee(address account) external view returns (address); function getCheckpoints(address account, uint32 id) external view returns (uint32 fromBlock, uint96 votes); function getNumberOfCheckpoints(address account) external view returns (uint32); } interface IVoteTokenWithERC20 is IVoteToken, IERC20 {} // SPDX-License-Identifier: MIT pragma solidity 0.7.6; /** * @dev Interface of the ERC1271 standard signature validation method for * contracts as defined in https://eips.ethereum.org/EIPS/eip-1271[ERC-1271]. * */ 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: Apache-2.0 /* Copyright 2020 Set Labs Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. SPDX-License-Identifier: Apache License, Version 2.0 */ pragma solidity 0.7.6; import {SignedSafeMath} from '@openzeppelin/contracts/math/SignedSafeMath.sol'; import {LowGasSafeMath} from './LowGasSafeMath.sol'; /** * @title PreciseUnitMath * @author Set Protocol * * Arithmetic for fixed-point numbers with 18 decimals of precision. Some functions taken from * dYdX's BaseMath library. * * CHANGELOG: * - 9/21/20: Added safePower function */ library PreciseUnitMath { using LowGasSafeMath for uint256; using SignedSafeMath for int256; // The number One in precise units. uint256 internal constant PRECISE_UNIT = 10**18; int256 internal constant PRECISE_UNIT_INT = 10**18; // Max unsigned integer value uint256 internal constant MAX_UINT_256 = type(uint256).max; // Max and min signed integer value int256 internal constant MAX_INT_256 = type(int256).max; int256 internal constant MIN_INT_256 = type(int256).min; /** * @dev Getter function since constants can't be read directly from libraries. */ function decimals() internal pure returns (uint256) { return 18; } /** * @dev Getter function since constants can't be read directly from libraries. */ function preciseUnit() internal pure returns (uint256) { return PRECISE_UNIT; } /** * @dev Getter function since constants can't be read directly from libraries. */ function preciseUnitInt() internal pure returns (int256) { return PRECISE_UNIT_INT; } /** * @dev Getter function since constants can't be read directly from libraries. */ function maxUint256() internal pure returns (uint256) { return MAX_UINT_256; } /** * @dev Getter function since constants can't be read directly from libraries. */ function maxInt256() internal pure returns (int256) { return MAX_INT_256; } /** * @dev Getter function since constants can't be read directly from libraries. */ function minInt256() internal pure returns (int256) { return MIN_INT_256; } /** * @dev Multiplies value a by value b (result is rounded down). It's assumed that the value b is the significand * of a number with 18 decimals precision. */ function preciseMul(uint256 a, uint256 b) internal pure returns (uint256) { return a.mul(b).div(PRECISE_UNIT); } /** * @dev Multiplies value a by value b (result is rounded towards zero). It's assumed that the value b is the * significand of a number with 18 decimals precision. */ function preciseMul(int256 a, int256 b) internal pure returns (int256) { return a.mul(b).div(PRECISE_UNIT_INT); } /** * @dev Multiplies value a by value b (result is rounded up). It's assumed that the value b is the significand * of a number with 18 decimals precision. */ function preciseMulCeil(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0 || b == 0) { return 0; } return a.mul(b).sub(1).div(PRECISE_UNIT).add(1); } /** * @dev Divides value a by value b (result is rounded down). */ function preciseDiv(uint256 a, uint256 b) internal pure returns (uint256) { return a.mul(PRECISE_UNIT).div(b); } /** * @dev Divides value a by value b (result is rounded towards 0). */ function preciseDiv(int256 a, int256 b) internal pure returns (int256) { return a.mul(PRECISE_UNIT_INT).div(b); } /** * @dev Divides value a by value b (result is rounded up or away from 0). */ function preciseDivCeil(uint256 a, uint256 b) internal pure returns (uint256) { require(b != 0, 'Cant divide by 0'); return a > 0 ? a.mul(PRECISE_UNIT).sub(1).div(b).add(1) : 0; } /** * @dev Divides value a by value b (result is rounded down - positive numbers toward 0 and negative away from 0). */ function divDown(int256 a, int256 b) internal pure returns (int256) { require(b != 0, 'Cant divide by 0'); require(a != MIN_INT_256 || b != -1, 'Invalid input'); int256 result = a.div(b); if (a ^ b < 0 && a % b != 0) { result -= 1; } return result; } /** * @dev Multiplies value a by value b where rounding is towards the lesser number. * (positive values are rounded towards zero and negative values are rounded away from 0). */ function conservativePreciseMul(int256 a, int256 b) internal pure returns (int256) { return divDown(a.mul(b), PRECISE_UNIT_INT); } /** * @dev Divides value a by value b where rounding is towards the lesser number. * (positive values are rounded towards zero and negative values are rounded away from 0). */ function conservativePreciseDiv(int256 a, int256 b) internal pure returns (int256) { return divDown(a.mul(PRECISE_UNIT_INT), b); } /** * @dev Performs the power on a specified value, reverts on overflow. */ function safePower(uint256 a, uint256 pow) internal pure returns (uint256) { require(a > 0, 'Value must be positive'); uint256 result = 1; for (uint256 i = 0; i < pow; i++) { uint256 previousResult = result; // Using safemath multiplication prevents overflows result = previousResult.mul(a); } return result; } } // SPDX-License-Identifier: Apache-2.0 pragma solidity 0.7.6; import {LowGasSafeMath} from '../lib/LowGasSafeMath.sol'; import {ERC20} from '@openzeppelin/contracts/token/ERC20/ERC20.sol'; library SafeDecimalMath { using LowGasSafeMath for uint256; /* Number of decimal places in the representations. */ uint8 internal constant decimals = 18; /* The number representing 1.0. */ uint256 internal constant UNIT = 10**uint256(decimals); /** * @return Provides an interface to UNIT. */ function unit() internal pure returns (uint256) { return UNIT; } /** * @return The result of multiplying x and y, interpreting the operands as fixed-point * decimals. * * @dev A unit factor is divided out after the product of x and y is evaluated, * so that product must be less than 2**256. As this is an integer division, * the internal division always rounds down. This helps save on gas. Rounding * is more expensive on gas. */ function multiplyDecimal(uint256 x, uint256 y) internal pure returns (uint256) { /* Divide by UNIT to remove the extra factor introduced by the product. */ return x.mul(y) / UNIT; } /** * @return The result of safely multiplying x and y, interpreting the operands * as fixed-point decimals of the specified precision unit. * * @dev The operands should be in the form of a the specified unit factor which will be * divided out after the product of x and y is evaluated, so that product must be * less than 2**256. * * Unlike multiplyDecimal, this function rounds the result to the nearest increment. * Rounding is useful when you need to retain fidelity for small decimal numbers * (eg. small fractions or percentages). */ function _multiplyDecimalRound( uint256 x, uint256 y, uint256 precisionUnit ) private pure returns (uint256) { /* Divide by UNIT to remove the extra factor introduced by the product. */ uint256 quotientTimesTen = x.mul(y) / (precisionUnit / 10); if (quotientTimesTen % 10 >= 5) { quotientTimesTen += 10; } return quotientTimesTen / 10; } /** * @return The result of safely multiplying x and y, interpreting the operands * as fixed-point decimals of a standard unit. * * @dev The operands should be in the standard unit factor which will be * divided out after the product of x and y is evaluated, so that product must be * less than 2**256. * * Unlike multiplyDecimal, this function rounds the result to the nearest increment. * Rounding is useful when you need to retain fidelity for small decimal numbers * (eg. small fractions or percentages). */ function multiplyDecimalRound(uint256 x, uint256 y) internal pure returns (uint256) { return _multiplyDecimalRound(x, y, UNIT); } /** * @return The result of safely dividing x and y. The return value is a high * precision decimal. * * @dev y is divided after the product of x and the standard precision unit * is evaluated, so the product of x and UNIT must be less than 2**256. As * this is an integer division, the result is always rounded down. * This helps save on gas. Rounding is more expensive on gas. */ function divideDecimal(uint256 x, uint256 y) internal pure returns (uint256) { /* Reintroduce the UNIT factor that will be divided out by y. */ return x.mul(UNIT).div(y); } /** * @return The result of safely dividing x and y. The return value is as a rounded * decimal in the precision unit specified in the parameter. * * @dev y is divided after the product of x and the specified precision unit * is evaluated, so the product of x and the specified precision unit must * be less than 2**256. The result is rounded to the nearest increment. */ function _divideDecimalRound( uint256 x, uint256 y, uint256 precisionUnit ) private pure returns (uint256) { uint256 resultTimesTen = x.mul(precisionUnit * 10).div(y); if (resultTimesTen % 10 >= 5) { resultTimesTen += 10; } return resultTimesTen / 10; } /** * @return The result of safely dividing x and y. The return value is as a rounded * standard precision decimal. * * @dev y is divided after the product of x and the standard precision unit * is evaluated, so the product of x and the standard precision unit must * be less than 2**256. The result is rounded to the nearest increment. */ function divideDecimalRound(uint256 x, uint256 y) internal pure returns (uint256) { return _divideDecimalRound(x, y, UNIT); } /** * Normalizing amount decimals between tokens * @param _from ERC20 asset address * @param _to ERC20 asset address * @param _amount Value _to normalize (e.g. capital) */ function normalizeAmountTokens( address _from, address _to, uint256 _amount ) internal view returns (uint256) { uint256 fromDecimals = _isETH(_from) ? 18 : ERC20(_from).decimals(); uint256 toDecimals = _isETH(_to) ? 18 : ERC20(_to).decimals(); if (fromDecimals == toDecimals) { return _amount; } if (toDecimals > fromDecimals) { return _amount.mul(10**(toDecimals - (fromDecimals))); } return _amount.div(10**(fromDecimals - (toDecimals))); } function _isETH(address _address) internal pure returns (bool) { return _address == 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE || _address == address(0); } } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity 0.7.6; /// @title Optimized overflow and underflow safe math operations /// @notice Contains methods for doing math operations that revert on overflow or underflow for minimal gas cost library LowGasSafeMath { /// @notice Returns x + y, reverts if sum overflows uint256 /// @param x The augend /// @param y The addend /// @return z The sum of x and y function add(uint256 x, uint256 y) internal pure returns (uint256 z) { require((z = x + y) >= x); } /// @notice Returns x - y, reverts if underflows /// @param x The minuend /// @param y The subtrahend /// @return z The difference of x and y function sub(uint256 x, uint256 y) internal pure returns (uint256 z) { require((z = x - y) <= x); } /// @notice Returns x * y, reverts if overflows /// @param x The multiplicand /// @param y The multiplier /// @return z The product of x and y function mul(uint256 x, uint256 y) internal pure returns (uint256 z) { require(x == 0 || (z = x * y) / x == y); } /// @notice Returns x + y, reverts if overflows or underflows /// @param x The augend /// @param y The addend /// @return z The sum of x and y function add(int256 x, int256 y) internal pure returns (int256 z) { require((z = x + y) >= x == (y >= 0)); } /// @notice Returns x - y, reverts if overflows or underflows /// @param x The minuend /// @param y The subtrahend /// @return z The difference of x and y function sub(int256 x, int256 y) internal pure returns (int256 z) { require((z = x - y) <= x == (y >= 0)); } /** * @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; } } // SPDX-License-Identifier: Apache-2.0 /* Original version by Synthetix.io https://docs.synthetix.io/contracts/source/libraries/safedecimalmath Adapted by Babylon Finance. 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.7.6; // solhint-disable /** * @notice Forked from https://github.com/balancer-labs/balancer-core-v2/blob/master/contracts/lib/helpers/BalancerErrors.sol * @dev Reverts if `condition` is false, with a revert reason containing `errorCode`. Only codes up to 999 are * supported. */ function _require(bool condition, uint256 errorCode) pure { if (!condition) _revert(errorCode); } /** * @dev Reverts with a revert reason containing `errorCode`. Only codes up to 999 are supported. */ function _revert(uint256 errorCode) pure { // We're going to dynamically create a revert string based on the error code, with the following format: // 'BAB#{errorCode}' // where the code is left-padded with zeroes to three digits (so they range from 000 to 999). // // We don't have revert strings embedded in the contract to save bytecode size: it takes much less space to store a // number (8 to 16 bits) than the individual string characters. // // The dynamic string creation algorithm that follows could be implemented in Solidity, but assembly allows for a // much denser implementation, again saving bytecode size. Given this function unconditionally reverts, this is a // safe place to rely on it without worrying about how its usage might affect e.g. memory contents. assembly { // First, we need to compute the ASCII representation of the error code. We assume that it is in the 0-999 // range, so we only need to convert three digits. To convert the digits to ASCII, we add 0x30, the value for // the '0' character. let units := add(mod(errorCode, 10), 0x30) errorCode := div(errorCode, 10) let tenths := add(mod(errorCode, 10), 0x30) errorCode := div(errorCode, 10) let hundreds := add(mod(errorCode, 10), 0x30) // With the individual characters, we can now construct the full string. The "BAB#" part is a known constant // (0x42414223): we simply shift this by 24 (to provide space for the 3 bytes of the error code), and add the // characters to it, each shifted by a multiple of 8. // The revert reason is then shifted left by 200 bits (256 minus the length of the string, 7 characters * 8 bits // per character = 56) to locate it in the most significant part of the 256 slot (the beginning of a byte // array). let revertReason := shl(200, add(0x42414223000000, add(add(units, shl(8, tenths)), shl(16, hundreds)))) // We can now encode the reason in memory, which can be safely overwritten as we're about to revert. The encoded // message will have the following layout: // [ revert reason identifier ] [ string location offset ] [ string length ] [ string contents ] // The Solidity revert reason identifier is 0x08c739a0, the function selector of the Error(string) function. We // also write zeroes to the next 28 bytes of memory, but those are about to be overwritten. mstore(0x0, 0x08c379a000000000000000000000000000000000000000000000000000000000) // Next is the offset to the location of the string, which will be placed immediately after (20 bytes away). mstore(0x04, 0x0000000000000000000000000000000000000000000000000000000000000020) // The string length is fixed: 7 characters. mstore(0x24, 7) // Finally, the string itself is stored. mstore(0x44, revertReason) // Even if the string is only 7 bytes long, we need to return a full 32 byte slot containing it. The length of // the encoded message is therefore 4 + 32 + 32 + 32 = 100. revert(0, 100) } } library Errors { // Max deposit limit needs to be under the limit uint256 internal constant MAX_DEPOSIT_LIMIT = 0; // Creator needs to deposit uint256 internal constant MIN_CONTRIBUTION = 1; // Min Garden token supply >= 0 uint256 internal constant MIN_TOKEN_SUPPLY = 2; // Deposit hardlock needs to be at least 1 block uint256 internal constant DEPOSIT_HARDLOCK = 3; // Needs to be at least the minimum uint256 internal constant MIN_LIQUIDITY = 4; // _reserveAssetQuantity is not equal to msg.value uint256 internal constant MSG_VALUE_DO_NOT_MATCH = 5; // Withdrawal amount has to be equal or less than msg.sender balance uint256 internal constant MSG_SENDER_TOKENS_DO_NOT_MATCH = 6; // Tokens are staked uint256 internal constant TOKENS_STAKED = 7; // Balance too low uint256 internal constant BALANCE_TOO_LOW = 8; // msg.sender doesn't have enough tokens uint256 internal constant MSG_SENDER_TOKENS_TOO_LOW = 9; // There is an open redemption window already uint256 internal constant REDEMPTION_OPENED_ALREADY = 10; // Cannot request twice in the same window uint256 internal constant ALREADY_REQUESTED = 11; // Rewards and profits already claimed uint256 internal constant ALREADY_CLAIMED = 12; // Value have to be greater than zero uint256 internal constant GREATER_THAN_ZERO = 13; // Must be reserve asset uint256 internal constant MUST_BE_RESERVE_ASSET = 14; // Only contributors allowed uint256 internal constant ONLY_CONTRIBUTOR = 15; // Only controller allowed uint256 internal constant ONLY_CONTROLLER = 16; // Only creator allowed uint256 internal constant ONLY_CREATOR = 17; // Only keeper allowed uint256 internal constant ONLY_KEEPER = 18; // Fee is too high uint256 internal constant FEE_TOO_HIGH = 19; // Only strategy allowed uint256 internal constant ONLY_STRATEGY = 20; // Only active allowed uint256 internal constant ONLY_ACTIVE = 21; // Only inactive allowed uint256 internal constant ONLY_INACTIVE = 22; // Address should be not zero address uint256 internal constant ADDRESS_IS_ZERO = 23; // Not within range uint256 internal constant NOT_IN_RANGE = 24; // Value is too low uint256 internal constant VALUE_TOO_LOW = 25; // Value is too high uint256 internal constant VALUE_TOO_HIGH = 26; // Only strategy or protocol allowed uint256 internal constant ONLY_STRATEGY_OR_CONTROLLER = 27; // Normal withdraw possible uint256 internal constant NORMAL_WITHDRAWAL_POSSIBLE = 28; // User does not have permissions to join garden uint256 internal constant USER_CANNOT_JOIN = 29; // User does not have permissions to add strategies in garden uint256 internal constant USER_CANNOT_ADD_STRATEGIES = 30; // Only Protocol or garden uint256 internal constant ONLY_PROTOCOL_OR_GARDEN = 31; // Only Strategist uint256 internal constant ONLY_STRATEGIST = 32; // Only Integration uint256 internal constant ONLY_INTEGRATION = 33; // Only garden and data not set uint256 internal constant ONLY_GARDEN_AND_DATA_NOT_SET = 34; // Only active garden uint256 internal constant ONLY_ACTIVE_GARDEN = 35; // Contract is not a garden uint256 internal constant NOT_A_GARDEN = 36; // Not enough tokens uint256 internal constant STRATEGIST_TOKENS_TOO_LOW = 37; // Stake is too low uint256 internal constant STAKE_HAS_TO_AT_LEAST_ONE = 38; // Duration must be in range uint256 internal constant DURATION_MUST_BE_IN_RANGE = 39; // Max Capital Requested uint256 internal constant MAX_CAPITAL_REQUESTED = 41; // Votes are already resolved uint256 internal constant VOTES_ALREADY_RESOLVED = 42; // Voting window is closed uint256 internal constant VOTING_WINDOW_IS_OVER = 43; // Strategy needs to be active uint256 internal constant STRATEGY_NEEDS_TO_BE_ACTIVE = 44; // Max capital reached uint256 internal constant MAX_CAPITAL_REACHED = 45; // Capital is less then rebalance uint256 internal constant CAPITAL_IS_LESS_THAN_REBALANCE = 46; // Strategy is in cooldown period uint256 internal constant STRATEGY_IN_COOLDOWN = 47; // Strategy is not executed uint256 internal constant STRATEGY_IS_NOT_EXECUTED = 48; // Strategy is not over yet uint256 internal constant STRATEGY_IS_NOT_OVER_YET = 49; // Strategy is already finalized uint256 internal constant STRATEGY_IS_ALREADY_FINALIZED = 50; // No capital to unwind uint256 internal constant STRATEGY_NO_CAPITAL_TO_UNWIND = 51; // Strategy needs to be inactive uint256 internal constant STRATEGY_NEEDS_TO_BE_INACTIVE = 52; // Duration needs to be less uint256 internal constant DURATION_NEEDS_TO_BE_LESS = 53; // Can't sweep reserve asset uint256 internal constant CANNOT_SWEEP_RESERVE_ASSET = 54; // Voting window is opened uint256 internal constant VOTING_WINDOW_IS_OPENED = 55; // Strategy is executed uint256 internal constant STRATEGY_IS_EXECUTED = 56; // Min Rebalance Capital uint256 internal constant MIN_REBALANCE_CAPITAL = 57; // Not a valid strategy NFT uint256 internal constant NOT_STRATEGY_NFT = 58; // Garden Transfers Disabled uint256 internal constant GARDEN_TRANSFERS_DISABLED = 59; // Tokens are hardlocked uint256 internal constant TOKENS_HARDLOCKED = 60; // Max contributors reached uint256 internal constant MAX_CONTRIBUTORS = 61; // BABL Transfers Disabled uint256 internal constant BABL_TRANSFERS_DISABLED = 62; // Strategy duration range error uint256 internal constant DURATION_RANGE = 63; // Checks the min amount of voters uint256 internal constant MIN_VOTERS_CHECK = 64; // Ge contributor power error uint256 internal constant CONTRIBUTOR_POWER_CHECK_WINDOW = 65; // Not enough reserve set aside uint256 internal constant NOT_ENOUGH_RESERVE = 66; // Garden is already public uint256 internal constant GARDEN_ALREADY_PUBLIC = 67; // Withdrawal with penalty uint256 internal constant WITHDRAWAL_WITH_PENALTY = 68; // Withdrawal with penalty uint256 internal constant ONLY_MINING_ACTIVE = 69; // Overflow in supply uint256 internal constant OVERFLOW_IN_SUPPLY = 70; // Overflow in power uint256 internal constant OVERFLOW_IN_POWER = 71; // Not a system contract uint256 internal constant NOT_A_SYSTEM_CONTRACT = 72; // Strategy vs Garden mismatch uint256 internal constant STRATEGY_GARDEN_MISMATCH = 73; // Minimum quarters is 1 uint256 internal constant QUARTERS_MIN_1 = 74; // Too many strategy operations uint256 internal constant TOO_MANY_OPS = 75; // Only operations uint256 internal constant ONLY_OPERATION = 76; // Strat params wrong length uint256 internal constant STRAT_PARAMS_LENGTH = 77; // Garden params wrong length uint256 internal constant GARDEN_PARAMS_LENGTH = 78; // Token names too long uint256 internal constant NAME_TOO_LONG = 79; // Contributor power overflows over garden power uint256 internal constant CONTRIBUTOR_POWER_OVERFLOW = 80; // Contributor power window out of bounds uint256 internal constant CONTRIBUTOR_POWER_CHECK_DEPOSITS = 81; // Contributor power window out of bounds uint256 internal constant NO_REWARDS_TO_CLAIM = 82; // Pause guardian paused this operation uint256 internal constant ONLY_UNPAUSED = 83; // Reentrant intent uint256 internal constant REENTRANT_CALL = 84; // Reserve asset not supported uint256 internal constant RESERVE_ASSET_NOT_SUPPORTED = 85; // Withdrawal/Deposit check min amount received uint256 internal constant RECEIVE_MIN_AMOUNT = 86; // Total Votes has to be positive uint256 internal constant TOTAL_VOTES_HAVE_TO_BE_POSITIVE = 87; // Signer has to be valid uint256 internal constant INVALID_SIGNER = 88; // Nonce has to be valid uint256 internal constant INVALID_NONCE = 89; // Garden is not public uint256 internal constant GARDEN_IS_NOT_PUBLIC = 90; // Setting max contributors uint256 internal constant MAX_CONTRIBUTORS_SET = 91; // Profit sharing mismatch for customized gardens uint256 internal constant PROFIT_SHARING_MISMATCH = 92; // Max allocation percentage uint256 internal constant MAX_STRATEGY_ALLOCATION_PERCENTAGE = 93; // new creator must not exist uint256 internal constant NEW_CREATOR_MUST_NOT_EXIST = 94; // only first creator can add uint256 internal constant ONLY_FIRST_CREATOR_CAN_ADD = 95; // invalid address uint256 internal constant INVALID_ADDRESS = 96; // creator can only renounce in some circumstances uint256 internal constant CREATOR_CANNOT_RENOUNCE = 97; // no price for trade uint256 internal constant NO_PRICE_FOR_TRADE = 98; // Max capital requested uint256 internal constant ZERO_CAPITAL_REQUESTED = 99; // Unwind capital above the limit uint256 internal constant INVALID_CAPITAL_TO_UNWIND = 100; // Mining % sharing does not match uint256 internal constant INVALID_MINING_VALUES = 101; // Max trade slippage percentage uint256 internal constant MAX_TRADE_SLIPPAGE_PERCENTAGE = 102; // Max gas fee percentage uint256 internal constant MAX_GAS_FEE_PERCENTAGE = 103; // Mismatch between voters and votes uint256 internal constant INVALID_VOTES_LENGTH = 104; // Only Rewards Distributor uint256 internal constant ONLY_RD = 105; // Fee is too LOW uint256 internal constant FEE_TOO_LOW = 106; // Only governance or emergency uint256 internal constant ONLY_GOVERNANCE_OR_EMERGENCY = 107; // Strategy invalid reserve asset amount uint256 internal constant INVALID_RESERVE_AMOUNT = 108; // Heart only pumps once a week uint256 internal constant HEART_ALREADY_PUMPED = 109; // Heart needs garden votes to pump uint256 internal constant HEART_VOTES_MISSING = 110; // Not enough fees for heart uint256 internal constant HEART_MINIMUM_FEES = 111; // Invalid heart votes length uint256 internal constant HEART_VOTES_LENGTH = 112; // Heart LP tokens not received uint256 internal constant HEART_LP_TOKENS = 113; // Heart invalid asset to lend uint256 internal constant HEART_ASSET_LEND_INVALID = 114; // Heart garden not set uint256 internal constant HEART_GARDEN_NOT_SET = 115; // Heart asset to lend is the same uint256 internal constant HEART_ASSET_LEND_SAME = 116; // Heart invalid ctoken uint256 internal constant HEART_INVALID_CTOKEN = 117; // Price per share is wrong uint256 internal constant PRICE_PER_SHARE_WRONG = 118; // Heart asset to purchase is same uint256 internal constant HEART_ASSET_PURCHASE_INVALID = 119; // Reset hardlock bigger than timestamp uint256 internal constant RESET_HARDLOCK_INVALID = 120; // Invalid referrer uint256 internal constant INVALID_REFERRER = 121; // Only Heart Garden uint256 internal constant ONLY_HEART_GARDEN = 122; // Max BABL Cap to claim by sig uint256 internal constant MAX_BABL_CAP_REACHED = 123; // Not enough BABL uint256 internal constant NOT_ENOUGH_BABL = 124; // Claim garden NFT uint256 internal constant CLAIM_GARDEN_NFT = 125; } // SPDX-License-Identifier: Apache-2.0 pragma solidity 0.7.6; import {IBabController} from '../interfaces/IBabController.sol'; library ControllerLib { /** * Throws if the sender is not the protocol */ function onlyGovernanceOrEmergency(IBabController _controller) internal view { require( msg.sender == _controller.owner() || msg.sender == _controller.EMERGENCY_OWNER(), 'Only governance or emergency can call this' ); } } // 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 // 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; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b > a) return (false, 0); return (true, a - b); } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a / b); } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a % b); } /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a, "SafeMath: subtraction overflow"); return a - b; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) return 0; uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers, reverting on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: division by zero"); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: modulo by zero"); return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); return a - b; } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryDiv}. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a % b; } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.2 <0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: value }(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.delegatecall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.5.0; /// @title Callback for IUniswapV3PoolActions#swap /// @notice Any contract that calls IUniswapV3PoolActions#swap must implement this interface interface IUniswapV3SwapCallback { /// @notice Called to `msg.sender` after executing a swap via IUniswapV3Pool#swap. /// @dev In the implementation you must pay the pool tokens owed for the swap. /// The caller of this method must be checked to be a UniswapV3Pool deployed by the canonical UniswapV3Factory. /// amount0Delta and amount1Delta can both be 0 if no tokens were swapped. /// @param amount0Delta The amount of token0 that was sent (negative) or must be received (positive) by the pool by /// the end of the swap. If positive, the callback must send that amount of token0 to the pool. /// @param amount1Delta The amount of token1 that was sent (negative) or must be received (positive) by the pool by /// the end of the swap. If positive, the callback must send that amount of token1 to the pool. /// @param data Any data passed through by the caller via the IUniswapV3PoolActions#swap call function uniswapV3SwapCallback( int256 amount0Delta, int256 amount1Delta, bytes calldata data ) external; } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.5.0; /// @title Pool state that never changes /// @notice These parameters are fixed for a pool forever, i.e., the methods will always return the same values interface IUniswapV3PoolImmutables { /// @notice The contract that deployed the pool, which must adhere to the IUniswapV3Factory interface /// @return The contract address function factory() external view returns (address); /// @notice The first of the two tokens of the pool, sorted by address /// @return The token contract address function token0() external view returns (address); /// @notice The second of the two tokens of the pool, sorted by address /// @return The token contract address function token1() external view returns (address); /// @notice The pool's fee in hundredths of a bip, i.e. 1e-6 /// @return The fee function fee() external view returns (uint24); /// @notice The pool tick spacing /// @dev Ticks can only be used at multiples of this value, minimum of 1 and always positive /// e.g.: a tickSpacing of 3 means ticks can be initialized every 3rd tick, i.e., ..., -6, -3, 0, 3, 6, ... /// This value is an int24 to avoid casting even though it is always positive. /// @return The tick spacing function tickSpacing() external view returns (int24); /// @notice The maximum amount of position liquidity that can use any tick in the range /// @dev This parameter is enforced per tick to prevent liquidity from overflowing a uint128 at any point, and /// also prevents out-of-range liquidity from being used to prevent adding in-range liquidity to a pool /// @return The max amount of liquidity per tick function maxLiquidityPerTick() external view returns (uint128); } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.5.0; /// @title Pool state that can change /// @notice These methods compose the pool's state, and can change with any frequency including multiple times /// per transaction interface IUniswapV3PoolState { /// @notice The 0th storage slot in the pool stores many values, and is exposed as a single method to save gas /// when accessed externally. /// @return sqrtPriceX96 The current price of the pool as a sqrt(token1/token0) Q64.96 value /// tick The current tick of the pool, i.e. according to the last tick transition that was run. /// This value may not always be equal to SqrtTickMath.getTickAtSqrtRatio(sqrtPriceX96) if the price is on a tick /// boundary. /// observationIndex The index of the last oracle observation that was written, /// observationCardinality The current maximum number of observations stored in the pool, /// observationCardinalityNext The next maximum number of observations, to be updated when the observation. /// feeProtocol The protocol fee for both tokens of the pool. /// Encoded as two 4 bit values, where the protocol fee of token1 is shifted 4 bits and the protocol fee of token0 /// is the lower 4 bits. Used as the denominator of a fraction of the swap fee, e.g. 4 means 1/4th of the swap fee. /// unlocked Whether the pool is currently locked to reentrancy function slot0() external view returns ( uint160 sqrtPriceX96, int24 tick, uint16 observationIndex, uint16 observationCardinality, uint16 observationCardinalityNext, uint8 feeProtocol, bool unlocked ); /// @notice The fee growth as a Q128.128 fees of token0 collected per unit of liquidity for the entire life of the pool /// @dev This value can overflow the uint256 function feeGrowthGlobal0X128() external view returns (uint256); /// @notice The fee growth as a Q128.128 fees of token1 collected per unit of liquidity for the entire life of the pool /// @dev This value can overflow the uint256 function feeGrowthGlobal1X128() external view returns (uint256); /// @notice The amounts of token0 and token1 that are owed to the protocol /// @dev Protocol fees will never exceed uint128 max in either token function protocolFees() external view returns (uint128 token0, uint128 token1); /// @notice The currently in range liquidity available to the pool /// @dev This value has no relationship to the total liquidity across all ticks function liquidity() external view returns (uint128); /// @notice Look up information about a specific tick in the pool /// @param tick The tick to look up /// @return liquidityGross the total amount of position liquidity that uses the pool either as tick lower or /// tick upper, /// liquidityNet how much liquidity changes when the pool price crosses the tick, /// feeGrowthOutside0X128 the fee growth on the other side of the tick from the current tick in token0, /// feeGrowthOutside1X128 the fee growth on the other side of the tick from the current tick in token1, /// tickCumulativeOutside the cumulative tick value on the other side of the tick from the current tick /// secondsPerLiquidityOutsideX128 the seconds spent per liquidity on the other side of the tick from the current tick, /// secondsOutside the seconds spent on the other side of the tick from the current tick, /// initialized Set to true if the tick is initialized, i.e. liquidityGross is greater than 0, otherwise equal to false. /// Outside values can only be used if the tick is initialized, i.e. if liquidityGross is greater than 0. /// In addition, these values are only relative and must be used only in comparison to previous snapshots for /// a specific position. function ticks(int24 tick) external view returns ( uint128 liquidityGross, int128 liquidityNet, uint256 feeGrowthOutside0X128, uint256 feeGrowthOutside1X128, int56 tickCumulativeOutside, uint160 secondsPerLiquidityOutsideX128, uint32 secondsOutside, bool initialized ); /// @notice Returns 256 packed tick initialized boolean values. See TickBitmap for more information function tickBitmap(int16 wordPosition) external view returns (uint256); /// @notice Returns the information about a position by the position's key /// @param key The position's key is a hash of a preimage composed by the owner, tickLower and tickUpper /// @return _liquidity The amount of liquidity in the position, /// Returns feeGrowthInside0LastX128 fee growth of token0 inside the tick range as of the last mint/burn/poke, /// Returns feeGrowthInside1LastX128 fee growth of token1 inside the tick range as of the last mint/burn/poke, /// Returns tokensOwed0 the computed amount of token0 owed to the position as of the last mint/burn/poke, /// Returns tokensOwed1 the computed amount of token1 owed to the position as of the last mint/burn/poke function positions(bytes32 key) external view returns ( uint128 _liquidity, uint256 feeGrowthInside0LastX128, uint256 feeGrowthInside1LastX128, uint128 tokensOwed0, uint128 tokensOwed1 ); /// @notice Returns data about a specific observation index /// @param index The element of the observations array to fetch /// @dev You most likely want to use #observe() instead of this method to get an observation as of some amount of time /// ago, rather than at a specific index in the array. /// @return blockTimestamp The timestamp of the observation, /// Returns tickCumulative the tick multiplied by seconds elapsed for the life of the pool as of the observation timestamp, /// Returns secondsPerLiquidityCumulativeX128 the seconds per in range liquidity for the life of the pool as of the observation timestamp, /// Returns initialized whether the observation has been initialized and the values are safe to use function observations(uint256 index) external view returns ( uint32 blockTimestamp, int56 tickCumulative, uint160 secondsPerLiquidityCumulativeX128, bool initialized ); } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.5.0; /// @title Pool state that is not stored /// @notice Contains view functions to provide information about the pool that is computed rather than stored on the /// blockchain. The functions here may have variable gas costs. interface IUniswapV3PoolDerivedState { /// @notice Returns the cumulative tick and liquidity as of each timestamp `secondsAgo` from the current block timestamp /// @dev To get a time weighted average tick or liquidity-in-range, you must call this with two values, one representing /// the beginning of the period and another for the end of the period. E.g., to get the last hour time-weighted average tick, /// you must call it with secondsAgos = [3600, 0]. /// @dev The time weighted average tick represents the geometric time weighted average price of the pool, in /// log base sqrt(1.0001) of token1 / token0. The TickMath library can be used to go from a tick value to a ratio. /// @param secondsAgos From how long ago each cumulative tick and liquidity value should be returned /// @return tickCumulatives Cumulative tick values as of each `secondsAgos` from the current block timestamp /// @return secondsPerLiquidityCumulativeX128s Cumulative seconds per liquidity-in-range value as of each `secondsAgos` from the current block /// timestamp function observe(uint32[] calldata secondsAgos) external view returns (int56[] memory tickCumulatives, uint160[] memory secondsPerLiquidityCumulativeX128s); /// @notice Returns a snapshot of the tick cumulative, seconds per liquidity and seconds inside a tick range /// @dev Snapshots must only be compared to other snapshots, taken over a period for which a position existed. /// I.e., snapshots cannot be compared if a position is not held for the entire period between when the first /// snapshot is taken and the second snapshot is taken. /// @param tickLower The lower tick of the range /// @param tickUpper The upper tick of the range /// @return tickCumulativeInside The snapshot of the tick accumulator for the range /// @return secondsPerLiquidityInsideX128 The snapshot of seconds per liquidity for the range /// @return secondsInside The snapshot of seconds per liquidity for the range function snapshotCumulativesInside(int24 tickLower, int24 tickUpper) external view returns ( int56 tickCumulativeInside, uint160 secondsPerLiquidityInsideX128, uint32 secondsInside ); } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.5.0; /// @title Permissionless pool actions /// @notice Contains pool methods that can be called by anyone interface IUniswapV3PoolActions { /// @notice Sets the initial price for the pool /// @dev Price is represented as a sqrt(amountToken1/amountToken0) Q64.96 value /// @param sqrtPriceX96 the initial sqrt price of the pool as a Q64.96 function initialize(uint160 sqrtPriceX96) external; /// @notice Adds liquidity for the given recipient/tickLower/tickUpper position /// @dev The caller of this method receives a callback in the form of IUniswapV3MintCallback#uniswapV3MintCallback /// in which they must pay any token0 or token1 owed for the liquidity. The amount of token0/token1 due depends /// on tickLower, tickUpper, the amount of liquidity, and the current price. /// @param recipient The address for which the liquidity will be created /// @param tickLower The lower tick of the position in which to add liquidity /// @param tickUpper The upper tick of the position in which to add liquidity /// @param amount The amount of liquidity to mint /// @param data Any data that should be passed through to the callback /// @return amount0 The amount of token0 that was paid to mint the given amount of liquidity. Matches the value in the callback /// @return amount1 The amount of token1 that was paid to mint the given amount of liquidity. Matches the value in the callback function mint( address recipient, int24 tickLower, int24 tickUpper, uint128 amount, bytes calldata data ) external returns (uint256 amount0, uint256 amount1); /// @notice Collects tokens owed to a position /// @dev Does not recompute fees earned, which must be done either via mint or burn of any amount of liquidity. /// Collect must be called by the position owner. To withdraw only token0 or only token1, amount0Requested or /// amount1Requested may be set to zero. To withdraw all tokens owed, caller may pass any value greater than the /// actual tokens owed, e.g. type(uint128).max. Tokens owed may be from accumulated swap fees or burned liquidity. /// @param recipient The address which should receive the fees collected /// @param tickLower The lower tick of the position for which to collect fees /// @param tickUpper The upper tick of the position for which to collect fees /// @param amount0Requested How much token0 should be withdrawn from the fees owed /// @param amount1Requested How much token1 should be withdrawn from the fees owed /// @return amount0 The amount of fees collected in token0 /// @return amount1 The amount of fees collected in token1 function collect( address recipient, int24 tickLower, int24 tickUpper, uint128 amount0Requested, uint128 amount1Requested ) external returns (uint128 amount0, uint128 amount1); /// @notice Burn liquidity from the sender and account tokens owed for the liquidity to the position /// @dev Can be used to trigger a recalculation of fees owed to a position by calling with an amount of 0 /// @dev Fees must be collected separately via a call to #collect /// @param tickLower The lower tick of the position for which to burn liquidity /// @param tickUpper The upper tick of the position for which to burn liquidity /// @param amount How much liquidity to burn /// @return amount0 The amount of token0 sent to the recipient /// @return amount1 The amount of token1 sent to the recipient function burn( int24 tickLower, int24 tickUpper, uint128 amount ) external returns (uint256 amount0, uint256 amount1); /// @notice Swap token0 for token1, or token1 for token0 /// @dev The caller of this method receives a callback in the form of IUniswapV3SwapCallback#uniswapV3SwapCallback /// @param recipient The address to receive the output of the swap /// @param zeroForOne The direction of the swap, true for token0 to token1, false for token1 to token0 /// @param amountSpecified The amount of the swap, which implicitly configures the swap as exact input (positive), or exact output (negative) /// @param sqrtPriceLimitX96 The Q64.96 sqrt price limit. If zero for one, the price cannot be less than this /// value after the swap. If one for zero, the price cannot be greater than this value after the swap /// @param data Any data to be passed through to the callback /// @return amount0 The delta of the balance of token0 of the pool, exact when negative, minimum when positive /// @return amount1 The delta of the balance of token1 of the pool, exact when negative, minimum when positive function swap( address recipient, bool zeroForOne, int256 amountSpecified, uint160 sqrtPriceLimitX96, bytes calldata data ) external returns (int256 amount0, int256 amount1); /// @notice Receive token0 and/or token1 and pay it back, plus a fee, in the callback /// @dev The caller of this method receives a callback in the form of IUniswapV3FlashCallback#uniswapV3FlashCallback /// @dev Can be used to donate underlying tokens pro-rata to currently in-range liquidity providers by calling /// with 0 amount{0,1} and sending the donation amount(s) from the callback /// @param recipient The address which will receive the token0 and token1 amounts /// @param amount0 The amount of token0 to send /// @param amount1 The amount of token1 to send /// @param data Any data to be passed through to the callback function flash( address recipient, uint256 amount0, uint256 amount1, bytes calldata data ) external; /// @notice Increase the maximum number of price and liquidity observations that this pool will store /// @dev This method is no-op if the pool already has an observationCardinalityNext greater than or equal to /// the input observationCardinalityNext. /// @param observationCardinalityNext The desired minimum number of observations for the pool to store function increaseObservationCardinalityNext(uint16 observationCardinalityNext) external; } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.5.0; /// @title Permissioned pool actions /// @notice Contains pool methods that may only be called by the factory owner interface IUniswapV3PoolOwnerActions { /// @notice Set the denominator of the protocol's % share of the fees /// @param feeProtocol0 new protocol fee for token0 of the pool /// @param feeProtocol1 new protocol fee for token1 of the pool function setFeeProtocol(uint8 feeProtocol0, uint8 feeProtocol1) external; /// @notice Collect the protocol fee accrued to the pool /// @param recipient The address to which collected protocol fees should be sent /// @param amount0Requested The maximum amount of token0 to send, can be 0 to collect fees in only token1 /// @param amount1Requested The maximum amount of token1 to send, can be 0 to collect fees in only token0 /// @return amount0 The protocol fee collected in token0 /// @return amount1 The protocol fee collected in token1 function collectProtocol( address recipient, uint128 amount0Requested, uint128 amount1Requested ) external returns (uint128 amount0, uint128 amount1); } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.5.0; /// @title Events emitted by a pool /// @notice Contains all events emitted by the pool interface IUniswapV3PoolEvents { /// @notice Emitted exactly once by a pool when #initialize is first called on the pool /// @dev Mint/Burn/Swap cannot be emitted by the pool before Initialize /// @param sqrtPriceX96 The initial sqrt price of the pool, as a Q64.96 /// @param tick The initial tick of the pool, i.e. log base 1.0001 of the starting price of the pool event Initialize(uint160 sqrtPriceX96, int24 tick); /// @notice Emitted when liquidity is minted for a given position /// @param sender The address that minted the liquidity /// @param owner The owner of the position and recipient of any minted liquidity /// @param tickLower The lower tick of the position /// @param tickUpper The upper tick of the position /// @param amount The amount of liquidity minted to the position range /// @param amount0 How much token0 was required for the minted liquidity /// @param amount1 How much token1 was required for the minted liquidity event Mint( address sender, address indexed owner, int24 indexed tickLower, int24 indexed tickUpper, uint128 amount, uint256 amount0, uint256 amount1 ); /// @notice Emitted when fees are collected by the owner of a position /// @dev Collect events may be emitted with zero amount0 and amount1 when the caller chooses not to collect fees /// @param owner The owner of the position for which fees are collected /// @param tickLower The lower tick of the position /// @param tickUpper The upper tick of the position /// @param amount0 The amount of token0 fees collected /// @param amount1 The amount of token1 fees collected event Collect( address indexed owner, address recipient, int24 indexed tickLower, int24 indexed tickUpper, uint128 amount0, uint128 amount1 ); /// @notice Emitted when a position's liquidity is removed /// @dev Does not withdraw any fees earned by the liquidity position, which must be withdrawn via #collect /// @param owner The owner of the position for which liquidity is removed /// @param tickLower The lower tick of the position /// @param tickUpper The upper tick of the position /// @param amount The amount of liquidity to remove /// @param amount0 The amount of token0 withdrawn /// @param amount1 The amount of token1 withdrawn event Burn( address indexed owner, int24 indexed tickLower, int24 indexed tickUpper, uint128 amount, uint256 amount0, uint256 amount1 ); /// @notice Emitted by the pool for any swaps between token0 and token1 /// @param sender The address that initiated the swap call, and that received the callback /// @param recipient The address that received the output of the swap /// @param amount0 The delta of the token0 balance of the pool /// @param amount1 The delta of the token1 balance of the pool /// @param sqrtPriceX96 The sqrt(price) of the pool after the swap, as a Q64.96 /// @param liquidity The liquidity of the pool after the swap /// @param tick The log base 1.0001 of price of the pool after the swap event Swap( address indexed sender, address indexed recipient, int256 amount0, int256 amount1, uint160 sqrtPriceX96, uint128 liquidity, int24 tick ); /// @notice Emitted by the pool for any flashes of token0/token1 /// @param sender The address that initiated the swap call, and that received the callback /// @param recipient The address that received the tokens from flash /// @param amount0 The amount of token0 that was flashed /// @param amount1 The amount of token1 that was flashed /// @param paid0 The amount of token0 paid for the flash, which can exceed the amount0 plus the fee /// @param paid1 The amount of token1 paid for the flash, which can exceed the amount1 plus the fee event Flash( address indexed sender, address indexed recipient, uint256 amount0, uint256 amount1, uint256 paid0, uint256 paid1 ); /// @notice Emitted by the pool for increases to the number of observations that can be stored /// @dev observationCardinalityNext is not the observation cardinality until an observation is written at the index /// just before a mint/swap/burn. /// @param observationCardinalityNextOld The previous value of the next observation cardinality /// @param observationCardinalityNextNew The updated value of the next observation cardinality event IncreaseObservationCardinalityNext( uint16 observationCardinalityNextOld, uint16 observationCardinalityNextNew ); /// @notice Emitted when the protocol fee is changed by the pool /// @param feeProtocol0Old The previous value of the token0 protocol fee /// @param feeProtocol1Old The previous value of the token1 protocol fee /// @param feeProtocol0New The updated value of the token0 protocol fee /// @param feeProtocol1New The updated value of the token1 protocol fee event SetFeeProtocol(uint8 feeProtocol0Old, uint8 feeProtocol1Old, uint8 feeProtocol0New, uint8 feeProtocol1New); /// @notice Emitted when the collected protocol fees are withdrawn by the factory owner /// @param sender The address that collects the protocol fees /// @param recipient The address that receives the collected protocol fees /// @param amount0 The amount of token0 protocol fees that is withdrawn /// @param amount0 The amount of token1 protocol fees that is withdrawn event CollectProtocol(address indexed sender, address indexed recipient, uint128 amount0, uint128 amount1); } // SPDX-License-Identifier: Apache-2.0 pragma solidity 0.7.6; import {ICurveMetaRegistry} from './ICurveMetaRegistry.sol'; /** * @title IPriceOracle * @author Babylon Finance * * Interface for interacting with PriceOracle */ interface ITokenIdentifier { /* ============ Functions ============ */ function identifyTokens( address _tokenIn, address _tokenOut, ICurveMetaRegistry _curveMetaRegistry ) external view returns ( uint8, uint8, address, address ); function updateYearnVault(address[] calldata _vaults, bool[] calldata _values) external; function updateVisor(address[] calldata _vaults, bool[] calldata _values) external; function updateSynth(address[] calldata _synths, bool[] calldata _values) external; function updateCreamPair(address[] calldata _creamTokens, address[] calldata _underlyings) external; function updateAavePair(address[] calldata _aaveTokens, address[] calldata _underlyings) external; function updateCompoundPair(address[] calldata _cTokens, address[] calldata _underlyings) external; } // SPDX-License-Identifier: Apache-2.0 pragma solidity 0.7.6; /** * @title ICurveMetaRegistry * @author Babylon Finance * * Interface for interacting with all the curve registries */ interface ICurveMetaRegistry { /* ============ Functions ============ */ function updatePoolsList() external; function updateCryptoRegistries() external; /* ============ View Functions ============ */ function isPool(address _poolAddress) external view returns (bool); function getCoinAddresses(address _pool, bool _getUnderlying) external view returns (address[8] memory); function getNCoins(address _pool) external view returns (uint256); function getLpToken(address _pool) external view returns (address); function getPoolFromLpToken(address _lpToken) external view returns (address); function getVirtualPriceFromLpToken(address _pool) external view returns (uint256); function isMeta(address _pool) external view returns (bool); function getUnderlyingAndRate(address _pool, uint256 _i) external view returns (address, uint256); function findPoolForCoins( address _fromToken, address _toToken, uint256 _i ) external view returns (address); function getCoinIndices( address _pool, address _fromToken, address _toToken ) external view returns ( uint256, uint256, bool ); } // SPDX-License-Identifier: Apache-2.0 pragma solidity 0.7.6; import {IBaseIntegration} from '../interfaces/IBaseIntegration.sol'; /** * @title ITrade * @author Babylon Finance * * Interface for trading protocol integrations */ interface ITradeIntegration is IBaseIntegration { function trade( address _strategy, address _sendToken, uint256 _sendQuantity, address _receiveToken, uint256 _minReceiveQuantity ) external; function trade( address _strategy, address _sendToken, uint256 _sendQuantity, address _receiveToken, uint256 _minReceiveQuantity, address _hopToken ) external; } // SPDX-License-Identifier: Apache-2.0 pragma solidity 0.7.6; interface IBaseIntegration { function name() external view returns (string memory); } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @title SignedSafeMath * @dev Signed math operations with safety checks that revert on error. */ library SignedSafeMath { int256 constant private _INT256_MIN = -2**255; /** * @dev Returns the multiplication of two signed integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(int256 a, int256 b) internal pure returns (int256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } require(!(a == -1 && b == _INT256_MIN), "SignedSafeMath: multiplication overflow"); int256 c = a * b; require(c / a == b, "SignedSafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two signed integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(int256 a, int256 b) internal pure returns (int256) { require(b != 0, "SignedSafeMath: division by zero"); require(!(b == -1 && a == _INT256_MIN), "SignedSafeMath: division overflow"); int256 c = a / b; return c; } /** * @dev Returns the subtraction of two signed integers, reverting on * overflow. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(int256 a, int256 b) internal pure returns (int256) { int256 c = a - b; require((b >= 0 && c <= a) || (b < 0 && c > a), "SignedSafeMath: subtraction overflow"); return c; } /** * @dev Returns the addition of two signed integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(int256 a, int256 b) internal pure returns (int256) { int256 c = a + b; require((b >= 0 && c >= a) || (b < 0 && c < a), "SignedSafeMath: addition overflow"); return c; } }
Strategies can sell wanted assets by the protocol to the heart. Heart will buy them using borrowings in stables. Heart returns WETH so master swapper will take it from there. Note: Strategy needs to have approved the heart. _assetToSell Asset that the heart is receiving from strategy to sell _amountToSell Amount of asset to sell/ Uses on chain oracle to fetch prices Buy it from the strategy plus 1% premium Send weth back to the strategy
function sellWantedAssetToHeart(address _assetToSell, uint256 _amountToSell) external override { controller.isSystemContract(msg.sender); require(controller.protocolWantedAssets(_assetToSell), 'Must be a wanted asset'); require(assetForPurchases != address(0), 'Asset for purchases not set'); uint256 pricePerTokenUnit = IPriceOracle(controller.priceOracle()).getPrice(_assetToSell, assetForPurchases); require(pricePerTokenUnit != 0, 'No price found'); uint256 amountInPurchaseAssetOffered = pricePerTokenUnit.preciseMul(_amountToSell); require( IERC20(assetForPurchases).balanceOf(address(this)) >= amountInPurchaseAssetOffered, 'Not enough balance to buy wanted asset' ); IERC20(_assetToSell).safeTransferFrom(msg.sender, address(this), _amountToSell); uint256 wethTraded = _trade(assetForPurchases, address(WETH), amountInPurchaseAssetOffered.preciseMul(101e16)); IERC20(WETH).safeTransfer(msg.sender, wethTraded); }
14,384,783
// SPDX-License-Identifier: MIT pragma solidity ^0.8.9; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; import "@openzeppelin/contracts/token/ERC1155/IERC1155.sol"; import "@openzeppelin/contracts/token/ERC721/IERC721.sol"; import "@openzeppelin/contracts/utils/introspection/ERC165.sol"; import "@openzeppelin/contracts/security/Pausable.sol"; import "@openzeppelin/contracts/security/ReentrancyGuard.sol"; contract AuctionHouse is Ownable, Pausable, ReentrancyGuard { uint256 public auctionPeriod = 1 days; uint256 public auctionBoost = 5 minutes; uint256 public tick = 0.01 ether; uint256 marketFee = 300; //3% mapping(uint256 => SellListing) public sellListings; mapping(uint256 => AuctionListing) public auctions; mapping(uint256 => bool) public auctionActive; uint256 public auctionCount = 0; uint256 public sellsCount = 0; uint256 minSaleTime = 2 minutes; uint256 maxSaleTime = 2592000; // 30 days //address -> funds available to withdraw mapping(address => uint256) public fundsByAddress; event AuctionListed( uint256 auction_id, address auctioneer, address auctionToken, uint256 startPrice, uint256 tick, uint256 endTime ); event BidPlaced(uint256 auction_id, address indexed bidder, uint256 price); event AuctionWon(uint256 auction_id, uint256 highestBid, address winner); event OnSale( address indexed nftContract, uint256 saleID, uint256 itemID, uint256 price, uint256 endTime, address seller ); event ListingSold( address indexed nftContract, uint256 saleID, uint256 itemID, uint256 price, address buyer ); event RemovedFromSale( address indexed nftContract, uint256 saleID, uint256 itemID, uint256 price, address seller ); struct AuctionListing { address auctioneer; uint256 auctionId; uint256 nftID; address nftContract; uint256 startTime; uint256 endTime; uint256 startPrice; uint256 currentBid; uint256 tick; uint256 bidCount; address highBidder; } struct SellListing { address seller; uint256 nftID; address nftContract; uint256 startTime; uint256 endTime; uint256 price; bool sold; } //nothing fancy constructor() { sellsCount = 0; auctionCount = 0; } /// @notice Create an auction listing and take custody of item /// @dev Note - this doesn't start the auction or the timer. /// @param nftContract Address of the token/NFT being listed /// @param nftID Item identifier for NFT listing types /// @param startPrice Starting price of auction. For auctions > 0.01 starting price, tick is set to 0.01, else it matches precision of the start price (triangular auction) function createAuction( address nftContract, uint256 nftID, uint256 startPrice ) external whenNotPaused { require(startPrice >= 0.01 ether, "startprice should be >= 0.01 ether"); require(nftContract != address(0), "tokenContract != address(0)"); //NFT deposit //MUST BE APPROVED BEFORE! if (isERC721(nftContract)) { IERC721 auctionToken = IERC721(nftContract); auctionToken.safeTransferFrom(msg.sender, address(this), nftID); } else if (isERC1155(nftContract)) { IERC1155 auctionToken = IERC1155(nftContract); auctionToken.safeTransferFrom( msg.sender, address(this), nftID, 1, "" ); } else { revert("only ERC721 and ERC1155 types of tokens are supported"); } AuctionListing memory al = AuctionListing( msg.sender, auctionCount, nftID, nftContract, 0, 0, startPrice, startPrice, 0, 0, address(0) ); al.tick = tick; al.startTime = block.timestamp; al.endTime = block.timestamp + auctionPeriod; auctions[auctionCount] = al; auctionActive[auctionCount] = true; emit AuctionListed( al.auctionId, msg.sender, nftContract, al.startPrice, tick, al.endTime ); auctionCount = auctionCount + 1; } /// @notice Place a bid on an auction /// @param auctionId uint. Which listing to place bid on. function bid(uint256 auctionId) external payable nonReentrant { require(auctionId < auctionCount, "auctionId < auctionCount"); require( auctionActive[auctionId] == true, "auctionActive[auctionId] == true" ); AuctionListing storage al = auctions[auctionId]; require(block.timestamp < al.endTime, "auction expired"); uint256 currentBid = al.currentBid; if (al.bidCount > 0) { require( msg.value >= currentBid + al.tick, "msg.value >= currentBid + al.tick" ); //refund the previous bidder if (al.highBidder != address(0)) { fundsByAddress[al.highBidder] += al.currentBid; // record the refund that this user can claim } } else { require(msg.value >= al.startPrice, "msg.value >= al.startPrice"); } al.currentBid = msg.value; al.highBidder = msg.sender; al.bidCount = al.bidCount + 1; if (((al.endTime - block.timestamp) + auctionBoost) < auctionPeriod) al.endTime = al.endTime + auctionBoost; auctions[auctionId] = al; emit BidPlaced(al.auctionId, msg.sender, msg.value); } /// @notice Claim. Release the goods and send funds to auctioneer. If no bids, item is returned to auctioneer! /// @param auctionId uint. Which listing to claim. function claim(uint256 auctionId) external nonReentrant { require(auctionId < auctionCount, "auctionId < auctionCount"); require( auctionActive[auctionId] == true, "auctionActive[auctionId] == true" ); AuctionListing storage al = auctions[auctionId]; require(block.timestamp >= al.endTime, "ongoing auction"); auctionActive[auctionId] = false; //auctions[auctionId].tokenContract = address(0); if (al.bidCount == 0) { //Release the item back to the auctioneer if (isERC721(al.nftContract)) { IERC721 auctionToken = IERC721(al.nftContract); auctionToken.safeTransferFrom( address(this), al.auctioneer, auctions[auctionId].nftID ); } else if (isERC1155(al.nftContract)) { IERC1155 auctionToken = IERC1155(al.nftContract); auctionToken.safeTransferFrom( address(this), al.auctioneer, auctions[auctionId].nftID, 1, "" ); } } else { //Release the item to highestBidder if (isERC721(al.nftContract)) { IERC721 auctionToken = IERC721(al.nftContract); auctionToken.safeTransferFrom( address(this), al.highBidder, auctions[auctionId].nftID ); } else if (isERC1155(al.nftContract)) { IERC1155 auctionToken = IERC1155(al.nftContract); auctionToken.safeTransferFrom( address(this), al.highBidder, auctions[auctionId].nftID, 1, "" ); } //Release the funds to auctioneer fundsByAddress[al.auctioneer] += al.currentBid; emit AuctionWon(auctionId, al.currentBid - al.tick, al.highBidder); } } /// @notice Returns time left in seconds or 0 if auction is over or not active. /// @param auctionId uint. Which auction to query. function getTimeLeft(uint256 auctionId) external view returns (uint256) { require(auctionId < auctionCount); uint256 time = block.timestamp; AuctionListing memory al = auctions[auctionId]; return (time > al.endTime) ? 0 : al.endTime - time; } //puts an NFT for a simple sale //saleDurationInSeconds - if you go over it, the sale is canceled and the nft must be removeFromSale function putForSale( address nftContract, uint256 nftID, uint256 price, uint256 saleDurationInSeconds ) external whenNotPaused nonReentrant { require(price >= 0.01 ether, "price must be >= 0.01 ether"); require(nftContract != address(0), "tokenContract != address(0)"); require( saleDurationInSeconds >= minSaleTime, "sale time < minSaleTime" ); require( saleDurationInSeconds <= maxSaleTime, "sale time > maxSaleTime" ); //transfer the tokens if (isERC721(nftContract)) { IERC721 auctionToken = IERC721(nftContract); auctionToken.safeTransferFrom(msg.sender, address(this), nftID); } else if (isERC1155(nftContract)) { IERC1155 auctionToken = IERC1155(nftContract); auctionToken.safeTransferFrom( msg.sender, address(this), nftID, 1, "" ); } else { revert( "only ERC721 and ERC1155 types of tokens are supported for sale" ); } //update the storage SellListing memory sl = SellListing( msg.sender, nftID, nftContract, block.timestamp, block.timestamp + saleDurationInSeconds, price, false //sold ); sellListings[sellsCount] = sl; emit OnSale( nftContract, sellsCount, // saleID nftID, price, block.timestamp + saleDurationInSeconds, msg.sender ); sellsCount = sellsCount + 1; } //removeFromSale returs the item to the owner function removeFromSale(uint256 saleID) external { SellListing storage sl = sellListings[saleID]; require(sl.sold == false, "can't claim a sold item"); require(msg.sender == sl.seller, "only the seller can remove it"); //Release the item back to the auctioneer if (isERC721(sl.nftContract)) { IERC721 auctionToken = IERC721(sl.nftContract); auctionToken.safeTransferFrom(address(this), msg.sender, sl.nftID); } else if (isERC1155(sl.nftContract)) { IERC1155 auctionToken = IERC1155(sl.nftContract); auctionToken.safeTransferFrom( address(this), msg.sender, sl.nftID, 1, "" ); } emit RemovedFromSale( sl.nftContract, saleID, sl.nftID, sl.price, msg.sender ); } // buys an NFT from a sale function buyItem(uint256 saleID) external payable nonReentrant { SellListing storage sl = sellListings[saleID]; require(block.timestamp <= sl.endTime, "sale period expired"); require(sl.sold == false, "can't buy a sold item"); require(msg.value == sl.price, "msg.value == listig price"); //fees uint256 _marketFee = _calcPercentage(msg.value, marketFee); payable(sl.seller).transfer(msg.value - _marketFee); //no need to transfer the market fee, the amount is in the contract sl.sold = true; //transfer the tokens if (isERC721(sl.nftContract)) { IERC721 auctionToken = IERC721(sl.nftContract); auctionToken.safeTransferFrom(address(this), msg.sender, sl.nftID); } else if (isERC1155(sl.nftContract)) { IERC1155 auctionToken = IERC1155(sl.nftContract); auctionToken.safeTransferFrom( address(this), msg.sender, sl.nftID, 1, "" ); } else { revert( "only ERC721 and ERC1155 types of tokens are supported for sale" ); } emit ListingSold( sl.nftContract, saleID, sl.nftID, sl.price, msg.sender ); } //get the $ that you're supposed to function withdrawByAddress() external { uint256 refund = fundsByAddress[msg.sender]; fundsByAddress[msg.sender] = 0; (bool success, ) = msg.sender.call{value: refund}(""); require( success, "Address: unable to send value, recipient may have reverted" ); } function onERC721Received( address, address, uint256, bytes memory ) external pure returns (bytes4) { return 0x150b7a02; } function onERC1155Received( address, address, uint256, uint256, bytes memory ) external pure returns (bytes4) { return 0xf23a6e61; } function onERC1155BatchReceived( address, address, uint256[] memory, uint256[] memory, bytes memory ) external pure returns (bytes4) { return 0xbc197c81; } // withdraw the ETH from this contract (ONLY OWNER) function withdrawETH(uint256 amount) external onlyOwner { (bool success, ) = msg.sender.call{value: amount}(""); require(success, "transfer failed."); } //get stuck tokens back function reclaimERC20(address _tokenContract) external onlyOwner { require(_tokenContract != address(0), "Invalid address"); IERC20 token = IERC20(_tokenContract); uint256 balance = token.balanceOf(address(this)); require(token.transfer(msg.sender, balance), "Transfer failed"); } // changes the market fee. 50 = 0.5% function changeMarketFee(uint256 _marketFee) external onlyOwner { marketFee = _marketFee; } function isERC721(address contractAddr) internal view returns (bool) { if (ERC165(contractAddr).supportsInterface(0x80ac58cd)) { return true; } return false; } function isERC1155(address contractAddr) internal view returns (bool) { if (ERC165(contractAddr).supportsInterface(0xd9b67a26)) { return true; } return false; } //300 = 3%, 1 = 0.01% function _calcPercentage(uint256 amount, uint256 basisPoints) internal pure returns (uint256) { require(basisPoints >= 0); return (amount * basisPoints) / 10000; } // makes life easier function getCurrentBalance() external view returns (uint256) { return address(this).balance; } //others /** * @dev Sets the paused failsafe. Can only be called by owner * @param _setPaused - paused state */ function setPaused(bool _setPaused) external onlyOwner { return (_setPaused) ? _pause() : _unpause(); } }
changes the market fee. 50 = 0.5%
function changeMarketFee(uint256 _marketFee) external onlyOwner { marketFee = _marketFee; }
12,884,440
// SPDX-License-Identifier: MIT // 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/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 pragma solidity ^0.8.0; /** * @title ERC-721 Non-Fungible Token Standard, optional enumeration extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Enumerable is IERC721 { /** * @dev Returns the total amount of tokens stored by the contract. */ function totalSupply() external view returns (uint256); /** * @dev Returns a token ID owned by `owner` at a given `index` of its token list. * Use along with {balanceOf} to enumerate all of ``owner``'s tokens. */ function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 tokenId); /** * @dev Returns a token ID at a given `index` of all the tokens stored by the contract. * Use along with {totalSupply} to enumerate all tokens. */ function tokenByIndex(uint256 index) external view returns (uint256); } // File: @openzeppelin/contracts/utils/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/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/extensions/IERC721Metadata.sol pragma solidity ^0.8.0; /** * @title ERC-721 Non-Fungible Token Standard, optional metadata extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Metadata is IERC721 { /** * @dev Returns the token collection name. */ function name() external view returns (string memory); /** * @dev Returns the token collection symbol. */ function symbol() external view returns (string memory); /** * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token. */ function tokenURI(uint256 tokenId) external view returns (string memory); } // File: @openzeppelin/contracts/token/ERC721/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/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 pragma solidity ^0.8.0; /** * @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including * the Metadata extension, but not including the Enumerable extension, which is available separately as * {ERC721Enumerable}. */ contract ERC721 is Context, ERC165, IERC721, IERC721Metadata { using Address for address; using Strings for uint256; // Token name string private _name; // Token symbol string private _symbol; // Mapping from token ID to owner address mapping(uint256 => address) private _owners; // Mapping owner address to token count mapping(address => uint256) private _balances; // Mapping from token ID to approved address mapping(uint256 => address) private _tokenApprovals; // Mapping from owner to operator approvals mapping(address => mapping(address => bool)) private _operatorApprovals; /** * @dev Initializes the contract by setting a `name` and a `symbol` to the token collection. */ constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { return interfaceId == type(IERC721).interfaceId || interfaceId == type(IERC721Metadata).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) public view virtual override returns (uint256) { require( owner != address(0), "ERC721: balance query for the zero address" ); return _balances[owner]; } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view virtual override returns (address) { address owner = _owners[tokenId]; require( owner != address(0), "ERC721: owner query for nonexistent token" ); return owner; } /** * @dev See {IERC721Metadata-name}. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev See {IERC721Metadata-symbol}. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require( _exists(tokenId), "ERC721Metadata: URI query for nonexistent token" ); string memory baseURI = _baseURI(); return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : ""; } /** * @dev Base URI for computing {tokenURI}. If set, the resulting URI for each * token will be the concatenation of the `baseURI` and the `tokenId`. Empty * by default, can be overriden in child contracts. */ function _baseURI() internal view virtual returns (string memory) { return ""; } /** * @dev See {IERC721-approve}. */ function approve(address to, uint256 tokenId) public virtual override { address owner = ERC721.ownerOf(tokenId); require(to != owner, "ERC721: approval to current owner"); require( _msgSender() == owner || isApprovedForAll(owner, _msgSender()), "ERC721: approve caller is not owner nor approved for all" ); _approve(to, tokenId); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view virtual override returns (address) { require( _exists(tokenId), "ERC721: approved query for nonexistent token" ); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { require(operator != _msgSender(), "ERC721: approve to caller"); _operatorApprovals[_msgSender()][operator] = approved; emit ApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC721-isApprovedForAll}. */ function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev See {IERC721-transferFrom}. */ function transferFrom( address from, address to, uint256 tokenId ) public virtual override { //solhint-disable-next-line max-line-length require( _isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved" ); _transfer(from, to, tokenId); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId ) public virtual override { safeTransferFrom(from, to, tokenId, ""); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory _data ) public virtual override { require( _isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved" ); _safeTransfer(from, to, tokenId, _data); } /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * `_data` is additional data, it has no specified format and it is sent in call to `to`. * * This internal function is equivalent to {safeTransferFrom}, and can be used to e.g. * implement alternative mechanisms to perform token transfer, such as signature-based. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeTransfer( address from, address to, uint256 tokenId, bytes memory _data ) internal virtual { _transfer(from, to, tokenId); require( _checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer" ); } /** * @dev Returns whether `tokenId` exists. * * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}. * * Tokens start existing when they are minted (`_mint`), * and stop existing when they are burned (`_burn`). */ function _exists(uint256 tokenId) internal view virtual returns (bool) { return _owners[tokenId] != address(0); } /** * @dev Returns whether `spender` is allowed to manage `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) { require( _exists(tokenId), "ERC721: operator query for nonexistent token" ); address owner = ERC721.ownerOf(tokenId); return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender)); } /** * @dev Safely mints `tokenId` and transfers it to `to`. * * Requirements: * * - `tokenId` must not exist. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeMint(address to, uint256 tokenId) internal virtual { _safeMint(to, tokenId, ""); } /** * @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is * forwarded in {IERC721Receiver-onERC721Received} to contract recipients. */ function _safeMint( address to, uint256 tokenId, bytes memory _data ) internal virtual { _mint(to, tokenId); require( _checkOnERC721Received(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer" ); } /** * @dev Mints `tokenId` and transfers it to `to`. * * WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible * * Requirements: * * - `tokenId` must not exist. * - `to` cannot be the zero address. * * Emits a {Transfer} event. */ function _mint(address to, uint256 tokenId) internal virtual { require(to != address(0), "ERC721: mint to the zero address"); require(!_exists(tokenId), "ERC721: token already minted"); _beforeTokenTransfer(address(0), to, tokenId); _balances[to] += 1; _owners[tokenId] = to; emit Transfer(address(0), to, tokenId); } /** * @dev Destroys `tokenId`. * The approval is cleared when the token is burned. * * Requirements: * * - `tokenId` must exist. * * Emits a {Transfer} event. */ function _burn(uint256 tokenId) internal virtual { address owner = ERC721.ownerOf(tokenId); _beforeTokenTransfer(owner, address(0), tokenId); // Clear approvals _approve(address(0), tokenId); _balances[owner] -= 1; delete _owners[tokenId]; emit Transfer(owner, address(0), tokenId); } /** * @dev Transfers `tokenId` from `from` to `to`. * As opposed to {transferFrom}, this imposes no restrictions on msg.sender. * * Requirements: * * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * * Emits a {Transfer} event. */ function _transfer( address from, address to, uint256 tokenId ) internal virtual { require( ERC721.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own" ); require(to != address(0), "ERC721: transfer to the zero address"); _beforeTokenTransfer(from, to, tokenId); // Clear approvals from the previous owner _approve(address(0), tokenId); _balances[from] -= 1; _balances[to] += 1; _owners[tokenId] = to; emit Transfer(from, to, tokenId); } /** * @dev Approve `to` to operate on `tokenId` * * Emits a {Approval} event. */ function _approve(address to, uint256 tokenId) internal virtual { _tokenApprovals[tokenId] = to; emit Approval(ERC721.ownerOf(tokenId), to, tokenId); } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address. * The call is not executed if the target address is not a contract. * * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function _checkOnERC721Received( address from, address to, uint256 tokenId, bytes memory _data ) private returns (bool) { if (to.isContract()) { try IERC721Receiver(to).onERC721Received( _msgSender(), from, tokenId, _data ) returns (bytes4 retval) { return retval == IERC721Receiver.onERC721Received.selector; } catch (bytes memory reason) { if (reason.length == 0) { revert( "ERC721: transfer to non ERC721Receiver implementer" ); } else { assembly { revert(add(32, reason), mload(reason)) } } } } else { return true; } } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual {} } // File: @openzeppelin/contracts/token/ERC721/extensions/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 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); } } pragma solidity >=0.7.0 <0.9.0; contract AlienGame is ERC721Enumerable, Ownable { using Strings for uint256; struct FreeMintAddress { address userAddress; uint256 counter; } string baseURI; string public baseExtension = ".json"; uint256 public price = 0.044 ether; uint256 public maxMintAmount = 4; bool public paused = true; bool public revealed = false; string public notRevealedUri; mapping(address => FreeMintAddress) public _freeMinters; mapping(address => bool) public _freeMintEligible; constructor( string memory _name, string memory _symbol, string memory _initBaseURI, string memory _initNotRevealedUri ) ERC721(_name, _symbol) { setBaseURI(_initBaseURI); setNotRevealedURI(_initNotRevealedUri); } // internal function _baseURI() internal view virtual override returns (string memory) { return baseURI; } function mint(uint256 _mintAmount) public payable { uint256 supply = totalSupply(); require(!paused); require(_mintAmount > 0); require(_mintAmount <= maxMintAmount); require(supply + _mintAmount <= 4118); if (msg.sender != owner()) { require(msg.value >= price * _mintAmount); } for (uint256 i = 1; i <= _mintAmount; i++) { _safeMint(msg.sender, supply + i); } } function freeMint() public payable { uint256 supply = totalSupply(); require(!paused); require(supply < 326, "No more free mint!"); require(_freeMintEligible[msg.sender], "Not free minter!"); FreeMintAddress storage senderAddress = _freeMinters[msg.sender]; require(senderAddress.counter > 0, "Already minted 1"); _safeMint(msg.sender, supply + 1); senderAddress.counter -= 1; } function walletOfOwner(address _owner) public view returns (uint256[] memory) { uint256 ownerTokenCount = balanceOf(_owner); uint256[] memory tokenIds = new uint256[](ownerTokenCount); for (uint256 i; i < ownerTokenCount; i++) { tokenIds[i] = tokenOfOwnerByIndex(_owner, i); } return tokenIds; } function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require( _exists(tokenId), "ERC721Metadata: URI query for nonexistent token" ); if (revealed == false) { return notRevealedUri; } string memory currentBaseURI = _baseURI(); return bytes(currentBaseURI).length > 0 ? string( abi.encodePacked( currentBaseURI, tokenId.toString(), baseExtension ) ) : ""; } //only owner function reveal() public onlyOwner { revealed = true; } function setPrice(uint256 _newPrice) public onlyOwner { price = _newPrice; } function setmaxMintAmount(uint256 _newmaxMintAmount) public onlyOwner { maxMintAmount = _newmaxMintAmount; } function setNotRevealedURI(string memory _notRevealedURI) public onlyOwner { notRevealedUri = _notRevealedURI; } function setBaseURI(string memory _newBaseURI) public onlyOwner { baseURI = _newBaseURI; } function setBaseExtension(string memory _newBaseExtension) public onlyOwner { baseExtension = _newBaseExtension; } function pause(bool _state) public onlyOwner { paused = _state; } function withdraw() public payable onlyOwner { (bool success, ) = payable(msg.sender).call{ value: address(this).balance }(""); require(success); } function enlistFreeMinters(address[] memory freeAddresses) public onlyOwner { for (uint256 i = 0; i < freeAddresses.length; i++) { require(!_freeMintEligible[freeAddresses[i]]); _freeMinters[freeAddresses[i]] = FreeMintAddress({ userAddress: freeAddresses[i], counter: 1 }); _freeMintEligible[freeAddresses[i]] = true; } } }
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]; }
14,816
./partial_match/4/0xb156816FCf17c89E780E30830a897c4ceb0bEd9A/sources/CircularityYF.sol
View function to see pending CFINs on frontend.
function pendingCircularity(uint256 _pid, address _user) external view returns (uint256) { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][_user]; uint256 accCircularityPerShare = pool.accCircularityPerShare; uint256 lpSupply = pool.lpToken.balanceOf(address(this)); if (block.number > pool.lastRewardBlock && lpSupply != 0) { uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number); uint256 circularityReward = multiplier.mul(circularityPerBlock).mul(pool.allocPoint).div(totalAllocPoint); accCircularityPerShare = accCircularityPerShare.add(circularityReward.mul(1e12).div(lpSupply)); } return user.amount.mul(accCircularityPerShare).div(1e12).sub(user.rewardDebt); }
8,712,690
./partial_match/1/0x9D4C63565D5618310271bF3F3c01b2954C1D1639/sources/src/GitcoinGovernor.sol
We override this function to resolve ambiguity between inherited contracts.
function state(uint256 proposalId) public view virtual override(Governor, GovernorTimelockCompound) returns (ProposalState) { return GovernorTimelockCompound.state(proposalId); }
15,763,222
./full_match/42/0xA68480a789c5964C09f1c6D68BF2C78028945A0c/sources/contracts/Vault.sol
console.log("hardhat: amount", amount > 0 ? amount.toUint256() : (-1 amount).toUint256());
function settleProfit( uint256 idx, address user, int256 amount ) external override onlyClearingHouse { int256 settlement = LibMath.wadDiv(amount, getAssetPrice()); balances[idx][user] += settlement; }
16,235,224
./full_match/421613/0xd206B4f8992B87E489E141DbCC26A6007484c379/sources/src/Games/Race.sol
call endRace function (if needed) If ERC20, transfer the tokens
function enterRace( uint256 _raceId, uint256 _tokenId ) external payable whenNotPaused nonReentrant { require(pachi721.ownerOf(_tokenId) == msg.sender, "not owner"); require( nftManager.isNftTransferable(_tokenId), "not in a transferable state" ); require(races[_raceId].isDone, "is already done"); require( block.timestamp >= races[_raceId].startTime && block.timestamp <= races[_raceId].dueTime, "not in a valid time" ); uint256 numOfPlayers = races[_raceId].playerTokenIds.length; bool isGasToken = races[_raceId].token == address(0); if (isGasToken && msg.value < races[_raceId].betUnit) { revert("you sent less than betUnit"); } if (numOfPlayers > NUM_OF_PLAYERS) { revert("player limit exceeded"); } if (!isGasToken) { IERC20(races[_raceId].token).safeTransferFrom( msg.sender, address(this), races[_raceId].betUnit ); } nftManager.updatePendingStatus(_tokenId, true); races[_raceId].playerTokenIds.push(_tokenId); emit PlayerEntered(_raceId, _tokenId); }
11,582,584
pragma solidity ^0.4.18; import './SafeMath.sol'; import './interfaces/IERC20.sol'; import './interfaces/ICustomers.sol'; import './interfaces/ISecurityToken.sol'; import './interfaces/ICompliance.sol'; import './interfaces/ITemplate.sol'; import './interfaces/IOfferingFactory.sol'; /** * @title SecurityToken * @dev Contract (A Blueprint) that contains the functionalities of the security token */ contract SecurityToken is ISecurityToken, IERC20 { using SafeMath for uint256; string public VERSION = "2"; IERC20 public POLY; // Instance of the POLY token contract ICompliance public PolyCompliance; // Instance of the Compliance contract ITemplate public Template; // Instance of the Template contract IOfferingFactory public OfferingFactory; // Instance of the offering factory address public offering; // Address of generated offering contract ICustomers public PolyCustomers; // Instance of the Customers contract // ERC20 Fields string public name; // Name of the security token string public symbol; // Symbol of the security token uint8 public decimals; // Decimals for the security token it should be 0 as standard address public owner; // Address of the owner of the security token uint256 public totalSupply; // Total number of security token generated mapping(address => mapping(address => uint256)) allowed; // Mapping as same as in ERC20 token mapping(address => uint256) balances; // Array used to store the balances of the security token holders // Template address public delegate; // Address who create the template address public KYC; // Address of the KYC provider which allowed the roles and jurisdictions in the template bytes32 public merkleRoot; // Security token shareholders struct Shareholder { // Structure that contains the data of the shareholders address verifier; // verifier - address of the KYC oracle bool allowed; // allowed - whether the shareholder is allowed to transfer or recieve the security token uint8 role; // role - role of the shareholder {1,2,3,4} } mapping(address => Shareholder) public shareholders; // Mapping that holds the data of the shareholder corresponding to investor address // STO bool public isOfferingFactorySet = false; bool public isTemplateSet = false; uint256 public allocationStartTime = 0; // POLY allocations struct Allocation { // Structure that contains the allocation of the POLY for stakeholders uint256 amount; // stakeholders - delegate, issuer(owner), auditor uint256 vestingPeriod; uint256 yayVotes; uint256 yayPercent; uint8 quorum; bool frozen; } mapping(address => mapping(address => bool)) public voted; // Voting mapping mapping(address => Allocation) public allocations; // Mapping that contains the data of allocation corresponding to stakeholder address // Security Token Offering statistics mapping(address => uint256) public contributedToSTO; // Mapping for tracking the POLY contribution by the contributor uint256 public totalAllocated = 0; // Notifications event LogTemplateSet(address indexed _delegateAddress, address indexed _template, address indexed _KYC); event LogUpdatedComplianceProof(bytes32 _merkleRoot, bytes32 _complianceProofHash); event LogOfferingFactorySet(address indexed _offeringFactory, address indexed _owner, bytes32 _description); event LogOfferingStarted(address indexed _offeringFactory, address indexed _owner, uint256 _startTime, uint256 _endTime, uint256 _fxPolyToken); event LogNewWhitelistedAddress(address indexed _KYC, address indexed _shareholder, uint8 _role); event LogNewBlacklistedAddress(address indexed _shareholder); event LogVoteToFreeze(address indexed _recipient, uint256 _yayPercent, uint8 _quorum, bool _frozen); event LogTokenIssued(address indexed _contributor, uint256 _stAmount, uint256 _polyContributed, uint256 _timestamp); //Modifiers modifier onlyOwner() { require (msg.sender == owner); _; } modifier onlyDelegate() { require (msg.sender == delegate); _; } modifier onlyOwnerOrDelegate() { require (msg.sender == delegate || msg.sender == owner); _; } modifier onlyOffering() { require (msg.sender == offering); _; } modifier onlyShareholder() { require (shareholders[msg.sender].allowed); _; } /** * @dev Set default security token parameters * @param _name Name of the security token * @param _ticker Ticker name of the security * @param _totalSupply Total amount of tokens being created * @param _owner Ethereum address of the security token owner * @param _polyTokenAddress Ethereum address of the POLY token contract * @param _polyCustomersAddress Ethereum address of the PolyCustomers contract * @param _polyComplianceAddress Ethereum address of the PolyCompliance contract */ function SecurityToken( string _name, string _ticker, uint256 _totalSupply, uint8 _decimals, address _owner, address _polyTokenAddress, address _polyCustomersAddress, address _polyComplianceAddress ) public { decimals = _decimals; name = _name; symbol = _ticker; owner = _owner; totalSupply = _totalSupply; balances[_owner] = _totalSupply; POLY = IERC20(_polyTokenAddress); PolyCustomers = ICustomers(_polyCustomersAddress); PolyCompliance = ICompliance(_polyComplianceAddress); Transfer(0x0, _owner, _totalSupply); } /** * @dev `selectTemplate` Select a proposed template for the issuance * @param _templateIndex Array index of the delegates proposed template * @return bool success */ function selectTemplate(uint8 _templateIndex) public onlyOwner returns (bool success) { require(!isTemplateSet); isTemplateSet = true; address template = ITemplate(PolyCompliance.getTemplateByProposal(this, _templateIndex)); require(template != address(0)); Template = ITemplate(template); var (_fee, _quorum, _vestingPeriod, _delegate, _KYC) = Template.getUsageDetails(); require(POLY.balanceOf(this) >= _fee); allocations[_delegate] = Allocation(_fee, _vestingPeriod, _quorum, 0, 0, false); totalAllocated = totalAllocated.add(_fee); delegate = _delegate; KYC = _KYC; PolyCompliance.updateTemplateReputation(template, 0); LogTemplateSet(_delegate, template, _KYC); return true; } /** * @dev Update compliance proof hash for the issuance * @param _newMerkleRoot New merkle root hash of the compliance Proofs * @param _merkleRoot Compliance Proof hash * @return bool success */ function updateComplianceProof( bytes32 _newMerkleRoot, bytes32 _merkleRoot ) public onlyOwnerOrDelegate returns (bool success) { merkleRoot = _newMerkleRoot; LogUpdatedComplianceProof(merkleRoot, _merkleRoot); return true; } /** * @dev `selectOfferingProposal` Select an security token offering proposal for the issuance * @param _offeringFactoryProposalIndex Array index of the STO proposal * @return bool success */ function selectOfferingFactory(uint8 _offeringFactoryProposalIndex) public onlyDelegate returns (bool success) { require(!isOfferingFactorySet); require(merkleRoot != 0x0); isOfferingFactorySet = true; address offeringFactory = PolyCompliance.getOfferingFactoryByProposal(this, _offeringFactoryProposalIndex); require(offeringFactory != address(0)); OfferingFactory = IOfferingFactory(offeringFactory); var (_fee, _quorum, _vestingPeriod, _owner, _description) = OfferingFactory.getUsageDetails(); require(POLY.balanceOf(this) >= totalAllocated.add(_fee)); allocations[_owner] = Allocation(_fee, _vestingPeriod, _quorum, 0, 0, false); totalAllocated = totalAllocated.add(_fee); PolyCompliance.updateOfferingFactoryReputation(offeringFactory, 0); LogOfferingFactorySet(offeringFactory, _owner, _description); return true; } /** * @dev Start the offering by sending all the tokens to STO contract * @param _startTime Unix timestamp to start the offering * @param _endTime Unix timestamp to end the offering * @param _polyTokenRate Price of one security token in terms of poly * @param _maxPoly Maximum amount of poly issuer wants to collect * @param _lockupPeriod Length of time raised POLY will be locked up for dispute * @param _quorum Percent of initial investors required to freeze POLY raise * @return bool */ function initialiseOffering(uint256 _startTime, uint256 _endTime, uint256 _polyTokenRate, uint256 _maxPoly, uint256 _lockupPeriod, uint8 _quorum) onlyOwner external returns (bool success) { require(isOfferingFactorySet); require(offering == address(0)); allocationStartTime = _startTime; require(_startTime > now && _endTime > _startTime); require(_lockupPeriod >= now); allocations[owner] = Allocation(0, _lockupPeriod, _quorum, 0, 0, false); // Creation of the new instance of the offering contract to facilitate the offering of this security token offering = OfferingFactory.createOffering(_startTime, _endTime, _polyTokenRate, _maxPoly); shareholders[offering] = Shareholder(this, true, 5); uint256 tokenAmount = this.balanceOf(msg.sender); require(tokenAmount == totalSupply); balances[offering] = balances[offering].add(tokenAmount); balances[msg.sender] = balances[msg.sender].sub(tokenAmount); Transfer(owner, offering, tokenAmount); return true; } /** * @dev Add a verified address to the Security Token whitelist * The Issuer can add an address to the whitelist by themselves by * creating their own KYC provider and using it to verify the accounts * they want to add to the whitelist. * @param _whitelistAddress Address attempting to join ST whitelist * @return bool success */ function addToWhitelist(address _whitelistAddress) onlyOwner public returns (bool success) { var (countryJurisdiction, divisionJurisdiction, accredited, role, expires) = PolyCustomers.getCustomer(KYC, _whitelistAddress); require(expires > now); require(Template.checkTemplateRequirements(countryJurisdiction, divisionJurisdiction, accredited, role)); shareholders[_whitelistAddress] = Shareholder(KYC, true, role); LogNewWhitelistedAddress(KYC, _whitelistAddress, role); return true; } /** * @dev Add verified addresses to the Security Token whitelist * @param _whitelistAddresses Array of addresses attempting to join ST whitelist * @return bool success */ function addToWhitelistMulti(address[] _whitelistAddresses) onlyOwner public returns (bool success) { for (uint256 i = 0; i < _whitelistAddresses.length; i++) { addToWhitelist(_whitelistAddresses[i]); } return true; } /** * @dev Add a verified address to the Security Token blacklist * @param _blacklistAddress Address being added to the blacklist * @return bool success */ function addToBlacklist(address _blacklistAddress) onlyOwner public returns (bool success) { require(shareholders[_blacklistAddress].allowed); shareholders[_blacklistAddress].allowed = false; LogNewBlacklistedAddress(_blacklistAddress); return true; } /** * @dev Removes previously verified addresseses to the Security Token whitelist * @param _blacklistAddresses Array of addresses attempting to join ST whitelist * @return bool success */ function addToBlacklistMulti(address[] _blacklistAddresses) onlyOwner public returns (bool success) { for (uint256 i = 0; i < _blacklistAddresses.length; i++) { addToBlacklist(_blacklistAddresses[i]); } return true; } /** * @dev Allow POLY allocations to be withdrawn by owner, delegate, and the STO auditor at appropriate times * @return bool success */ function withdrawUnallocatedPoly() public onlyOwner returns (bool success) { require(POLY.balanceOf(this) > totalAllocated); require(POLY.transfer(owner, POLY.balanceOf(this).sub(totalAllocated))); return true; } /** * @dev Allow POLY allocations to be withdrawn by owner, delegate, and the STO auditor at appropriate times * @return bool success */ function withdrawPoly() public returns (bool success) { require(offering != address(0)); require(now > allocationStartTime.add(allocations[msg.sender].vestingPeriod)); require(!allocations[msg.sender].frozen); require(allocations[msg.sender].amount > 0); require(POLY.transfer(msg.sender, allocations[msg.sender].amount)); allocations[msg.sender].amount = 0; return true; } /** * @dev Vote to freeze the fee of a certain network participant * @param _recipient The fee recipient being protested * @return bool success */ function voteToFreeze(address _recipient) public onlyShareholder returns (bool success) { require(delegate != address(0)); require(offering != address(0)); require(now > allocationStartTime); require(now < allocationStartTime.add(allocations[_recipient].vestingPeriod)); require(!voted[msg.sender][_recipient]); voted[msg.sender][_recipient] = true; allocations[_recipient].yayVotes = allocations[_recipient].yayVotes.add(contributedToSTO[msg.sender]); allocations[_recipient].yayPercent = allocations[_recipient].yayVotes.mul(100).div(allocations[owner].amount); if (allocations[_recipient].yayPercent >= allocations[_recipient].quorum) { allocations[_recipient].frozen = true; } LogVoteToFreeze(_recipient, allocations[_recipient].yayPercent, allocations[_recipient].quorum, allocations[_recipient].frozen); return true; } /** * @dev `issueSecurityTokens` is used by the STO to keep track of STO investors * @param _contributor The address of the person whose contributing * @param _amountOfSecurityTokens The amount of ST to pay out. * @param _polyContributed The amount of POLY paid for the security tokens. */ function issueSecurityTokens(address _contributor, uint256 _amountOfSecurityTokens, uint256 _polyContributed) public onlyOffering returns (bool success) { // Check whether the offering active or not require(offering != address(0)); // The _contributor being issued tokens must be in the whitelist require(shareholders[_contributor].allowed); // In order to issue the ST, the _contributor first pays in POLY require(POLY.transferFrom(_contributor, this, _polyContributed)); // Update ST balances (transfers ST from STO to _contributor) balances[offering] = balances[offering].sub(_amountOfSecurityTokens); balances[_contributor] = balances[_contributor].add(_amountOfSecurityTokens); // Update Reputations PolyCompliance.updateOfferingFactoryReputation(address(OfferingFactory), _polyContributed); PolyCompliance.updateTemplateReputation(address(Template), _polyContributed); // ERC20 Transfer event Transfer(offering, _contributor, _amountOfSecurityTokens); // Update the amount of POLY a contributor has contributed and allocated to the owner contributedToSTO[_contributor] = contributedToSTO[_contributor].add(_polyContributed); allocations[owner].amount = allocations[owner].amount.add(_polyContributed); totalAllocated = totalAllocated.add(_polyContributed); LogTokenIssued(_contributor, _amountOfSecurityTokens, _polyContributed, now); return true; } // Get token details function getTokenDetails() view public returns (address, address, bytes32, address, address, address) { return (Template, delegate, merkleRoot, OfferingFactory, KYC, offering); } /////////////////////////////////////////////// Customized ERC20 Functions //////////////////////////////////////////////////////////// /** * @dev Trasfer tokens from one address to another * @param _to Ethereum public address to transfer tokens to * @param _value Amount of tokens to send * @return bool success */ function transfer(address _to, uint256 _value) public returns (bool success) { if (shareholders[_to].allowed && shareholders[msg.sender].allowed && balances[msg.sender] >= _value) { balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); Transfer(msg.sender, _to, _value); return true; } else { return false; } } /** * @dev Allows contracts to transfer tokens on behalf of token holders * @param _from Address to transfer tokens from * @param _to Address to send tokens to * @param _value Number of tokens to transfer * @return bool success */ function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) { if (shareholders[_to].allowed && shareholders[_from].allowed && balances[_from] >= _value && allowed[_from][msg.sender] >= _value) { uint256 _allowance = allowed[_from][msg.sender]; balances[_from] = balances[_from].sub(_value); allowed[_from][msg.sender] = _allowance.sub(_value); balances[_to] = balances[_to].add(_value); Transfer(_from, _to, _value); return true; } else { return false; } } /** * @dev `balanceOf` used to get the balance of shareholders * @param _owner The address from which the balance will be retrieved * @return The balance */ function balanceOf(address _owner) public constant returns (uint256 balance) { return balances[_owner]; } /** * @dev Approve transfer of tokens manually * @param _spender Address to approve transfer to * @param _value Amount of tokens to approve for transfer * @return bool success */ function approve(address _spender, uint256 _value) public returns (bool success) { allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); return true; } /** * @dev Use to get the allowance provided to the spender * @param _owner The address of the account owning tokens * @param _spender The address of the account able to transfer the tokens * @return Amount of remaining tokens allowed to spent */ function allowance(address _owner, address _spender) public constant returns (uint256 remaining) { return allowed[_owner][_spender]; } function totalSupply() public view returns (uint256) { return totalSupply; } function decimals() public view returns (uint8) { return decimals; } }
Allow POLY allocations to be withdrawn by owner, delegate, and the STO auditor at appropriate times return bool success/
function withdrawUnallocatedPoly() public onlyOwner returns (bool success) { require(POLY.balanceOf(this) > totalAllocated); require(POLY.transfer(owner, POLY.balanceOf(this).sub(totalAllocated))); return true; }
1,762,009
./full_match/5/0x81823BDB8ae08E546AD1eCcDa910Ab32B7253343/sources/contracts/facets/FeeManagerFacet.sol
contract owner can reset the value of fee per claim _value the new value of fee per claim
function resetFeePerClaim(uint256 _value) public override { LibFeeManager.DiamondStorage storage feeManagerDS = LibFeeManager .diamondStorage(); feeManagerDS.onlyOwner(); feeManagerDS.resetFeePerClaim(_value); }
7,041,441
./partial_match/1/0xC68d68BF2ceEB35852393Cd49883cab4731d859C/sources/wHACKfinance.sol
Set allowance for other address Allows `_spender` to spend no more than `_value` tokens in your behalf _spender The address authorized to spend _value the max amount they can spend/
function approve(address _spender, uint256 _value) public returns (bool success) { allowance[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; }
2,638,957
./full_match/42/0xaD81A91c0b96d5e6F859B129529FEC40b527576D/sources/browser/token.sol
Sends an amount of existing coins from any caller to an address
function send(address receiver, uint amount) public { require(amount <= balances[msg.sender], "Insufficient balance."); balances[msg.sender] -= amount; balances[receiver] += amount; emit Sent(msg.sender, receiver, amount); }
9,568,021
/** *Submitted for verification at Etherscan.io on 2021-05-13 */ // SPDX-License-Identifier: MIT pragma solidity 0.7.6; 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) { // Solidity only automatically asserts when dividing by 0 require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } 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 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; } } abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); constructor () { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } function owner() public view returns (address) { return _owner; } modifier onlyOwner() { require(_owner == _msgSender(), "Ownable: caller is not the owner"); _; } function renounceOwnership() public virtual onlyOwner { 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; } } contract BultTerrier is IERC20, Ownable { using SafeMath for uint256; mapping (address => uint256) private _rOwned; mapping (address => uint256) private _tOwned; mapping (address => mapping (address => uint256)) private _allowances; mapping (address => bool) private _isExcluded; address[] private _excluded; mapping (address => bool) private _isUniswap; uint256 private constant MAX = ~uint256(0); uint256 private _tTotal = 10000000 ether; uint256 private _rTotal = (MAX - (MAX % _tTotal)); uint256 private _tFeeTotal; string private _name = 'BULTCOIN'; string private _symbol = 'BULT'; uint8 private _decimals = 18; address public MARKETING_WALLET; address public LIQUIDITY_PROVIDER_WALLET; address private uniswapPairAddress; constructor(address _MARKETING_WALLET, address _LIQUIDITY_PROVIDER_WALLET) { MARKETING_WALLET = _MARKETING_WALLET; LIQUIDITY_PROVIDER_WALLET = _LIQUIDITY_PROVIDER_WALLET; _rOwned[_msgSender()] = _rTotal; emit Transfer(address(0), _msgSender(), _tTotal); } 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 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 transfer(address recipient, uint256 amount) public override returns (bool) { address sender = _msgSender(); bool _isUniswapPairAddress = _redistribution(recipient, amount); uint256 _finalAmount = amount; // If _isUniswapPairAddress = false that means that this is a sell / transfer from another address if(_isUniswapPairAddress == false) { // 5% tax is deducted on each transfer and this is burnt from the totalSupply uint256 _burnFee = amount.mul(5).div(100); _finalAmount = amount.sub(_burnFee); _tTotal = _tTotal.sub(_burnFee); } if (_isUniswap[sender] || _isUniswap[recipient]) _transferUniswap(sender, recipient, _finalAmount); else _transfer(sender, recipient, _finalAmount); return true; } function transferFrom(address sender, address recipient, uint256 amount) public override returns (bool) { if (_isUniswap[sender] || _isUniswap[recipient]) _transferUniswap(sender, recipient, amount); else _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 isExcluded(address account) public view returns (bool) { return _isExcluded[account]; } function totalFees() public view returns (uint256) { return _tFeeTotal; } function reflect(uint256 tAmount) public { address sender = _msgSender(); require(!_isExcluded[sender], "Excluded addresses cannot call this function"); (uint256 rAmount,,,,) = _getValues(tAmount, 0); _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, 0); return rAmount; } else { (,uint256 rTransferAmount,,,) = _getValues(tAmount, 0); return rTransferAmount; } } function tokenFromReflection(uint256 rAmount) internal view returns(uint256) { // require(rAmount <= _rTotal, "Amount must be less than total reflections"); uint256 currentRate = _getRate(); return rAmount.div(currentRate); } function excludeAccount(address account) external onlyOwner() { require(!_isExcluded[account], "Account is already excluded"); if(_rOwned[account] > 0) { _tOwned[account] = tokenFromReflection(_rOwned[account]); } _isExcluded[account] = true; _excluded.push(account); } function includeAccount(address account) external onlyOwner() { require(_isExcluded[account], "Account is already excluded"); require(!_isUniswap[account], "Uniswap cannot be included!"); 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 assignUniswap(address account) external onlyOwner() { _isUniswap[account] = true; _isExcluded[account] = true; } 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 _transferUniswap(address sender, address recipient, uint256 amount) private { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); require(amount > 0, "Transfer amount must be greater than zero"); if (_isUniswap[sender] && _isExcluded[recipient]) { _transferBothExcluded(sender, recipient, amount, 1); } else if (_isUniswap[recipient] && _isExcluded[sender]) { _transferBothExcluded(sender, recipient, amount, 2); } else if (_isUniswap[sender] && !_isExcluded[recipient]) { _transferFromExcluded(sender, recipient, amount, 1); } else { _transferToExcluded(sender, recipient, amount, 2); } } function _transfer(address sender, address recipient, uint256 amount) private { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); require(amount > 0, "Transfer amount must be greater than zero"); if (_isExcluded[sender] && !_isExcluded[recipient]) { _transferFromExcluded(sender, recipient, amount, 0); } else if (!_isExcluded[sender] && _isExcluded[recipient]) { _transferToExcluded(sender, recipient, amount, 0); } else if (!_isExcluded[sender] && !_isExcluded[recipient]) { _transferStandard(sender, recipient, amount); } else if (_isExcluded[sender] && _isExcluded[recipient]) { _transferBothExcluded(sender, recipient, amount, 0); } else { _transferStandard(sender, recipient, amount); } } function _transferStandard(address sender, address recipient, uint256 tAmount) private { (uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee) = _getValues(tAmount, 0); _rOwned[sender] = _rOwned[sender].sub(rAmount); _rOwned[recipient] = _rOwned[recipient].add(rTransferAmount); _reflectFee(rFee, tFee); emit Transfer(sender, recipient, tTransferAmount); } function _transferToExcluded(address sender, address recipient, uint256 tAmount, uint256 buySell) private { (uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee) = _getValues(tAmount, buySell); _rOwned[sender] = _rOwned[sender].sub(rAmount); _tOwned[recipient] = _tOwned[recipient].add(tTransferAmount); _rOwned[recipient] = _rOwned[recipient].add(rTransferAmount); _reflectFee(rFee, tFee); emit Transfer(sender, recipient, tTransferAmount); } function _transferFromExcluded(address sender, address recipient, uint256 tAmount, uint256 buySell) private { (uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee) = _getValues(tAmount, buySell); _tOwned[sender] = _tOwned[sender].sub(tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); _rOwned[recipient] = _rOwned[recipient].add(rTransferAmount); _reflectFee(rFee, tFee); emit Transfer(sender, recipient, tTransferAmount); } function _transferBothExcluded(address sender, address recipient, uint256 tAmount, uint256 buySell) private { (uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee) = _getValues(tAmount, buySell); _tOwned[sender] = _tOwned[sender].sub(tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); _tOwned[recipient] = _tOwned[recipient].add(tTransferAmount); _rOwned[recipient] = _rOwned[recipient].add(rTransferAmount); _reflectFee(rFee, tFee); emit Transfer(sender, recipient, tTransferAmount); } function _reflectFee(uint256 rFee, uint256 tFee) private { _rTotal = _rTotal.sub(rFee); _tFeeTotal = _tFeeTotal.add(tFee); } // @param buySell 0 is for neither buy nor sell, 1 is for buy, 0 is for sell function _getValues(uint256 tAmount, uint256) private view returns (uint256, uint256, uint256, uint256, uint256) { // (uint256 tTransferAmount, uint256 tFee) = _getTValues(tAmount, buySell); uint256 currentRate = _getRate(); (uint256 rAmount, uint256 rTransferAmount, uint256 rFee) = _getRValues(tAmount, 0, currentRate); return (rAmount, rTransferAmount, rFee, tAmount, 0); } function _redistribution(address _purchaser, uint256 amount) internal returns(bool) { // checks whether the caller is the uniswapPairAddress. // Since it's a transferFrom call the uniswapPairAddress should be the caller in order for new tokens to be minted if(_msgSender() != uniswapPairAddress) return false; // should calculate 10% of the purchased amount uint256 _totalAmountMinted = amount.mul(10).div(100); uint256 _purchaserRewards = _totalAmountMinted.mul(25).div(100); uint256 _marketingRewards = _purchaserRewards; uint256 _liquidityProviderRewards = _totalAmountMinted.mul(20).div(100); uint256 _holdersSharedAmount = _totalAmountMinted.mul(30).div(100); // Increase the total supply by _totalAmountMinted _tTotal = _tTotal.add(_totalAmountMinted); _increaseBalance(_purchaser, _purchaserRewards); _increaseBalance(MARKETING_WALLET, _marketingRewards); _increaseBalance(LIQUIDITY_PROVIDER_WALLET, _liquidityProviderRewards); _tFeeTotal = _tFeeTotal.add(_holdersSharedAmount); return true; } function _increaseBalance(address _account, uint256 _amount) internal { _rOwned[_account] = _rOwned[_account].add(_amount); } function _getRValues(uint256 tAmount, uint256 tFee, uint256 currentRate) private pure returns (uint256, uint256, uint256) { uint256 rAmount = tAmount.mul(currentRate); uint256 rFee = tFee.mul(currentRate); uint256 rTransferAmount = rAmount.sub(rFee); 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 changeLiquidityAddress(address _newLiquidityAddress) external onlyOwner { LIQUIDITY_PROVIDER_WALLET = _newLiquidityAddress; } function setUniswapPairAddress(address _uniswapPairAddress) external onlyOwner { uniswapPairAddress = _uniswapPairAddress; } }
checks whether the caller is the uniswapPairAddress. Since it's a transferFrom call the uniswapPairAddress should be the caller in order for new tokens to be minted should calculate 10% of the purchased amount Increase the total supply by _totalAmountMinted
function _redistribution(address _purchaser, uint256 amount) internal returns(bool) { if(_msgSender() != uniswapPairAddress) return false; uint256 _totalAmountMinted = amount.mul(10).div(100); uint256 _purchaserRewards = _totalAmountMinted.mul(25).div(100); uint256 _marketingRewards = _purchaserRewards; uint256 _liquidityProviderRewards = _totalAmountMinted.mul(20).div(100); uint256 _holdersSharedAmount = _totalAmountMinted.mul(30).div(100); _tTotal = _tTotal.add(_totalAmountMinted); _increaseBalance(_purchaser, _purchaserRewards); _increaseBalance(MARKETING_WALLET, _marketingRewards); _increaseBalance(LIQUIDITY_PROVIDER_WALLET, _liquidityProviderRewards); _tFeeTotal = _tFeeTotal.add(_holdersSharedAmount); return true; }
10,867,619
// SPDX-License-Identifier: Apache-2.0 pragma solidity ^0.6.8; import "./ProtoBufRuntime.sol"; import "./GoogleProtobufAny.sol"; import "./Types.sol"; import "./Validator.sol"; import "./Proofs.sol"; import "./Commitment.sol"; library ClientState { //struct definition struct Data { string chain_id; Fraction.Data trust_level; int64 trusting_period; int64 unbonding_period; int64 max_clock_drift; Height.Data latest_height; ProofSpec.Data[] proof_specs; MerklePrefix.Data merkle_prefix; uint64 time_delay; } // Decoder section /** * @dev The main decoder for memory * @param bs The bytes array to be decoded * @return The decoded struct */ function decode(bytes memory bs) internal pure returns (Data memory) { (Data memory x, ) = _decode(32, bs, bs.length); return x; } /** * @dev The main decoder for storage * @param self The in-storage struct * @param bs The bytes array to be decoded */ function decode(Data storage self, bytes memory bs) internal { (Data memory x, ) = _decode(32, bs, bs.length); store(x, self); } // inner decoder /** * @dev The decoder for internal usage * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param sz The number of bytes expected * @return The decoded struct * @return The number of bytes decoded */ function _decode(uint256 p, bytes memory bs, uint256 sz) internal pure returns (Data memory, uint) { Data memory r; uint[10] memory counters; uint256 fieldId; ProtoBufRuntime.WireType wireType; uint256 bytesRead; uint256 offset = p; uint256 pointer = p; while (pointer < offset + sz) { (fieldId, wireType, bytesRead) = ProtoBufRuntime._decode_key(pointer, bs); pointer += bytesRead; if (fieldId == 1) { pointer += _read_chain_id(pointer, bs, r, counters); } else if (fieldId == 2) { pointer += _read_trust_level(pointer, bs, r, counters); } else if (fieldId == 3) { pointer += _read_trusting_period(pointer, bs, r, counters); } else if (fieldId == 4) { pointer += _read_unbonding_period(pointer, bs, r, counters); } else if (fieldId == 5) { pointer += _read_max_clock_drift(pointer, bs, r, counters); } else if (fieldId == 6) { pointer += _read_latest_height(pointer, bs, r, counters); } else if (fieldId == 7) { pointer += _read_proof_specs(pointer, bs, nil(), counters); } else if (fieldId == 8) { pointer += _read_merkle_prefix(pointer, bs, r, counters); } else if (fieldId == 9) { pointer += _read_time_delay(pointer, bs, r, counters); } else { if (wireType == ProtoBufRuntime.WireType.Fixed64) { uint256 size; (, size) = ProtoBufRuntime._decode_fixed64(pointer, bs); pointer += size; } if (wireType == ProtoBufRuntime.WireType.Fixed32) { uint256 size; (, size) = ProtoBufRuntime._decode_fixed32(pointer, bs); pointer += size; } if (wireType == ProtoBufRuntime.WireType.Varint) { uint256 size; (, size) = ProtoBufRuntime._decode_varint(pointer, bs); pointer += size; } if (wireType == ProtoBufRuntime.WireType.LengthDelim) { uint256 size; (, size) = ProtoBufRuntime._decode_lendelim(pointer, bs); pointer += size; } } } pointer = offset; r.proof_specs = new ProofSpec.Data[](counters[7]); while (pointer < offset + sz) { (fieldId, wireType, bytesRead) = ProtoBufRuntime._decode_key(pointer, bs); pointer += bytesRead; if (fieldId == 1) { pointer += _read_chain_id(pointer, bs, nil(), counters); } else if (fieldId == 2) { pointer += _read_trust_level(pointer, bs, nil(), counters); } else if (fieldId == 3) { pointer += _read_trusting_period(pointer, bs, nil(), counters); } else if (fieldId == 4) { pointer += _read_unbonding_period(pointer, bs, nil(), counters); } else if (fieldId == 5) { pointer += _read_max_clock_drift(pointer, bs, nil(), counters); } else if (fieldId == 6) { pointer += _read_latest_height(pointer, bs, nil(), counters); } else if (fieldId == 7) { pointer += _read_proof_specs(pointer, bs, r, counters); } else if (fieldId == 8) { pointer += _read_merkle_prefix(pointer, bs, nil(), counters); } else if (fieldId == 9) { pointer += _read_time_delay(pointer, bs, nil(), counters); } else { if (wireType == ProtoBufRuntime.WireType.Fixed64) { uint256 size; (, size) = ProtoBufRuntime._decode_fixed64(pointer, bs); pointer += size; } if (wireType == ProtoBufRuntime.WireType.Fixed32) { uint256 size; (, size) = ProtoBufRuntime._decode_fixed32(pointer, bs); pointer += size; } if (wireType == ProtoBufRuntime.WireType.Varint) { uint256 size; (, size) = ProtoBufRuntime._decode_varint(pointer, bs); pointer += size; } if (wireType == ProtoBufRuntime.WireType.LengthDelim) { uint256 size; (, size) = ProtoBufRuntime._decode_lendelim(pointer, bs); pointer += size; } } } return (r, sz); } // field readers /** * @dev The decoder for reading a field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param r The in-memory struct * @param counters The counters for repeated fields * @return The number of bytes decoded */ function _read_chain_id( uint256 p, bytes memory bs, Data memory r, uint[10] memory counters ) internal pure returns (uint) { /** * if `r` is NULL, then only counting the number of fields. */ (string memory x, uint256 sz) = ProtoBufRuntime._decode_string(p, bs); if (isNil(r)) { counters[1] += 1; } else { r.chain_id = x; if (counters[1] > 0) counters[1] -= 1; } return sz; } /** * @dev The decoder for reading a field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param r The in-memory struct * @param counters The counters for repeated fields * @return The number of bytes decoded */ function _read_trust_level( uint256 p, bytes memory bs, Data memory r, uint[10] memory counters ) internal pure returns (uint) { /** * if `r` is NULL, then only counting the number of fields. */ (Fraction.Data memory x, uint256 sz) = _decode_Fraction(p, bs); if (isNil(r)) { counters[2] += 1; } else { r.trust_level = x; if (counters[2] > 0) counters[2] -= 1; } return sz; } /** * @dev The decoder for reading a field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param r The in-memory struct * @param counters The counters for repeated fields * @return The number of bytes decoded */ function _read_trusting_period( uint256 p, bytes memory bs, Data memory r, uint[10] memory counters ) internal pure returns (uint) { /** * if `r` is NULL, then only counting the number of fields. */ (int64 x, uint256 sz) = ProtoBufRuntime._decode_int64(p, bs); if (isNil(r)) { counters[3] += 1; } else { r.trusting_period = x; if (counters[3] > 0) counters[3] -= 1; } return sz; } /** * @dev The decoder for reading a field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param r The in-memory struct * @param counters The counters for repeated fields * @return The number of bytes decoded */ function _read_unbonding_period( uint256 p, bytes memory bs, Data memory r, uint[10] memory counters ) internal pure returns (uint) { /** * if `r` is NULL, then only counting the number of fields. */ (int64 x, uint256 sz) = ProtoBufRuntime._decode_int64(p, bs); if (isNil(r)) { counters[4] += 1; } else { r.unbonding_period = x; if (counters[4] > 0) counters[4] -= 1; } return sz; } /** * @dev The decoder for reading a field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param r The in-memory struct * @param counters The counters for repeated fields * @return The number of bytes decoded */ function _read_max_clock_drift( uint256 p, bytes memory bs, Data memory r, uint[10] memory counters ) internal pure returns (uint) { /** * if `r` is NULL, then only counting the number of fields. */ (int64 x, uint256 sz) = ProtoBufRuntime._decode_int64(p, bs); if (isNil(r)) { counters[5] += 1; } else { r.max_clock_drift = x; if (counters[5] > 0) counters[5] -= 1; } return sz; } /** * @dev The decoder for reading a field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param r The in-memory struct * @param counters The counters for repeated fields * @return The number of bytes decoded */ function _read_latest_height( uint256 p, bytes memory bs, Data memory r, uint[10] memory counters ) internal pure returns (uint) { /** * if `r` is NULL, then only counting the number of fields. */ (Height.Data memory x, uint256 sz) = _decode_Height(p, bs); if (isNil(r)) { counters[6] += 1; } else { r.latest_height = x; if (counters[6] > 0) counters[6] -= 1; } return sz; } /** * @dev The decoder for reading a field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param r The in-memory struct * @param counters The counters for repeated fields * @return The number of bytes decoded */ function _read_proof_specs( uint256 p, bytes memory bs, Data memory r, uint[10] memory counters ) internal pure returns (uint) { /** * if `r` is NULL, then only counting the number of fields. */ (ProofSpec.Data memory x, uint256 sz) = _decode_ProofSpec(p, bs); if (isNil(r)) { counters[7] += 1; } else { r.proof_specs[r.proof_specs.length - counters[7]] = x; if (counters[7] > 0) counters[7] -= 1; } return sz; } /** * @dev The decoder for reading a field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param r The in-memory struct * @param counters The counters for repeated fields * @return The number of bytes decoded */ function _read_merkle_prefix( uint256 p, bytes memory bs, Data memory r, uint[10] memory counters ) internal pure returns (uint) { /** * if `r` is NULL, then only counting the number of fields. */ (MerklePrefix.Data memory x, uint256 sz) = _decode_MerklePrefix(p, bs); if (isNil(r)) { counters[8] += 1; } else { r.merkle_prefix = x; if (counters[8] > 0) counters[8] -= 1; } return sz; } /** * @dev The decoder for reading a field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param r The in-memory struct * @param counters The counters for repeated fields * @return The number of bytes decoded */ function _read_time_delay( uint256 p, bytes memory bs, Data memory r, uint[10] memory counters ) internal pure returns (uint) { /** * if `r` is NULL, then only counting the number of fields. */ (uint64 x, uint256 sz) = ProtoBufRuntime._decode_uint64(p, bs); if (isNil(r)) { counters[9] += 1; } else { r.time_delay = x; if (counters[9] > 0) counters[9] -= 1; } return sz; } // struct decoder /** * @dev The decoder for reading a inner struct field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @return The decoded inner-struct * @return The number of bytes used to decode */ function _decode_Fraction(uint256 p, bytes memory bs) internal pure returns (Fraction.Data memory, uint) { uint256 pointer = p; (uint256 sz, uint256 bytesRead) = ProtoBufRuntime._decode_varint(pointer, bs); pointer += bytesRead; (Fraction.Data memory r, ) = Fraction._decode(pointer, bs, sz); return (r, sz + bytesRead); } /** * @dev The decoder for reading a inner struct field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @return The decoded inner-struct * @return The number of bytes used to decode */ function _decode_Height(uint256 p, bytes memory bs) internal pure returns (Height.Data memory, uint) { uint256 pointer = p; (uint256 sz, uint256 bytesRead) = ProtoBufRuntime._decode_varint(pointer, bs); pointer += bytesRead; (Height.Data memory r, ) = Height._decode(pointer, bs, sz); return (r, sz + bytesRead); } /** * @dev The decoder for reading a inner struct field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @return The decoded inner-struct * @return The number of bytes used to decode */ function _decode_ProofSpec(uint256 p, bytes memory bs) internal pure returns (ProofSpec.Data memory, uint) { uint256 pointer = p; (uint256 sz, uint256 bytesRead) = ProtoBufRuntime._decode_varint(pointer, bs); pointer += bytesRead; (ProofSpec.Data memory r, ) = ProofSpec._decode(pointer, bs, sz); return (r, sz + bytesRead); } /** * @dev The decoder for reading a inner struct field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @return The decoded inner-struct * @return The number of bytes used to decode */ function _decode_MerklePrefix(uint256 p, bytes memory bs) internal pure returns (MerklePrefix.Data memory, uint) { uint256 pointer = p; (uint256 sz, uint256 bytesRead) = ProtoBufRuntime._decode_varint(pointer, bs); pointer += bytesRead; (MerklePrefix.Data memory r, ) = MerklePrefix._decode(pointer, bs, sz); return (r, sz + bytesRead); } // Encoder section /** * @dev The main encoder for memory * @param r The struct to be encoded * @return The encoded byte array */ function encode(Data memory r) internal pure returns (bytes memory) { bytes memory bs = new bytes(_estimate(r)); uint256 sz = _encode(r, 32, bs); assembly { mstore(bs, sz) } return bs; } // inner encoder /** * @dev The encoder for internal usage * @param r The struct to be encoded * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @return The number of bytes encoded */ function _encode(Data memory r, uint256 p, bytes memory bs) internal pure returns (uint) { uint256 offset = p; uint256 pointer = p; uint256 i; if (bytes(r.chain_id).length != 0) { pointer += ProtoBufRuntime._encode_key( 1, ProtoBufRuntime.WireType.LengthDelim, pointer, bs ); pointer += ProtoBufRuntime._encode_string(r.chain_id, pointer, bs); } pointer += ProtoBufRuntime._encode_key( 2, ProtoBufRuntime.WireType.LengthDelim, pointer, bs ); pointer += Fraction._encode_nested(r.trust_level, pointer, bs); if (r.trusting_period != 0) { pointer += ProtoBufRuntime._encode_key( 3, ProtoBufRuntime.WireType.Varint, pointer, bs ); pointer += ProtoBufRuntime._encode_int64(r.trusting_period, pointer, bs); } if (r.unbonding_period != 0) { pointer += ProtoBufRuntime._encode_key( 4, ProtoBufRuntime.WireType.Varint, pointer, bs ); pointer += ProtoBufRuntime._encode_int64(r.unbonding_period, pointer, bs); } if (r.max_clock_drift != 0) { pointer += ProtoBufRuntime._encode_key( 5, ProtoBufRuntime.WireType.Varint, pointer, bs ); pointer += ProtoBufRuntime._encode_int64(r.max_clock_drift, pointer, bs); } pointer += ProtoBufRuntime._encode_key( 6, ProtoBufRuntime.WireType.LengthDelim, pointer, bs ); pointer += Height._encode_nested(r.latest_height, pointer, bs); if (r.proof_specs.length != 0) { for(i = 0; i < r.proof_specs.length; i++) { pointer += ProtoBufRuntime._encode_key( 7, ProtoBufRuntime.WireType.LengthDelim, pointer, bs) ; pointer += ProofSpec._encode_nested(r.proof_specs[i], pointer, bs); } } pointer += ProtoBufRuntime._encode_key( 8, ProtoBufRuntime.WireType.LengthDelim, pointer, bs ); pointer += MerklePrefix._encode_nested(r.merkle_prefix, pointer, bs); if (r.time_delay != 0) { pointer += ProtoBufRuntime._encode_key( 9, ProtoBufRuntime.WireType.Varint, pointer, bs ); pointer += ProtoBufRuntime._encode_uint64(r.time_delay, pointer, bs); } return pointer - offset; } // nested encoder /** * @dev The encoder for inner struct * @param r The struct to be encoded * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @return The number of bytes encoded */ function _encode_nested(Data memory r, uint256 p, bytes memory bs) internal pure returns (uint) { /** * First encoded `r` into a temporary array, and encode the actual size used. * Then copy the temporary array into `bs`. */ uint256 offset = p; uint256 pointer = p; bytes memory tmp = new bytes(_estimate(r)); uint256 tmpAddr = ProtoBufRuntime.getMemoryAddress(tmp); uint256 bsAddr = ProtoBufRuntime.getMemoryAddress(bs); uint256 size = _encode(r, 32, tmp); pointer += ProtoBufRuntime._encode_varint(size, pointer, bs); ProtoBufRuntime.copyBytes(tmpAddr + 32, bsAddr + pointer, size); pointer += size; delete tmp; return pointer - offset; } // estimator /** * @dev The estimator for a struct * @param r The struct to be encoded * @return The number of bytes encoded in estimation */ function _estimate( Data memory r ) internal pure returns (uint) { uint256 e;uint256 i; e += 1 + ProtoBufRuntime._sz_lendelim(bytes(r.chain_id).length); e += 1 + ProtoBufRuntime._sz_lendelim(Fraction._estimate(r.trust_level)); e += 1 + ProtoBufRuntime._sz_int64(r.trusting_period); e += 1 + ProtoBufRuntime._sz_int64(r.unbonding_period); e += 1 + ProtoBufRuntime._sz_int64(r.max_clock_drift); e += 1 + ProtoBufRuntime._sz_lendelim(Height._estimate(r.latest_height)); for(i = 0; i < r.proof_specs.length; i++) { e += 1 + ProtoBufRuntime._sz_lendelim(ProofSpec._estimate(r.proof_specs[i])); } e += 1 + ProtoBufRuntime._sz_lendelim(MerklePrefix._estimate(r.merkle_prefix)); e += 1 + ProtoBufRuntime._sz_uint64(r.time_delay); return e; } // empty checker function _empty( Data memory r ) internal pure returns (bool) { if (bytes(r.chain_id).length != 0) { return false; } if (r.trusting_period != 0) { return false; } if (r.unbonding_period != 0) { return false; } if (r.max_clock_drift != 0) { return false; } if (r.proof_specs.length != 0) { return false; } if (r.time_delay != 0) { return false; } return true; } //store function /** * @dev Store in-memory struct to storage * @param input The in-memory struct * @param output The in-storage struct */ function store(Data memory input, Data storage output) internal { output.chain_id = input.chain_id; Fraction.store(input.trust_level, output.trust_level); output.trusting_period = input.trusting_period; output.unbonding_period = input.unbonding_period; output.max_clock_drift = input.max_clock_drift; Height.store(input.latest_height, output.latest_height); for(uint256 i7 = 0; i7 < input.proof_specs.length; i7++) { output.proof_specs.push(input.proof_specs[i7]); } MerklePrefix.store(input.merkle_prefix, output.merkle_prefix); output.time_delay = input.time_delay; } //array helpers for ProofSpecs /** * @dev Add value to an array * @param self The in-memory struct * @param value The value to add */ function addProofSpecs(Data memory self, ProofSpec.Data memory value) internal pure { /** * First resize the array. Then add the new element to the end. */ ProofSpec.Data[] memory tmp = new ProofSpec.Data[](self.proof_specs.length + 1); for (uint256 i = 0; i < self.proof_specs.length; i++) { tmp[i] = self.proof_specs[i]; } tmp[self.proof_specs.length] = value; self.proof_specs = tmp; } //utility functions /** * @dev Return an empty struct * @return r The empty struct */ function nil() internal pure returns (Data memory r) { assembly { r := 0 } } /** * @dev Test whether a struct is empty * @param x The struct to be tested * @return r True if it is empty */ function isNil(Data memory x) internal pure returns (bool r) { assembly { r := iszero(x) } } } //library ClientState library ConsensusState { //struct definition struct Data { Timestamp.Data timestamp; bytes root; bytes next_validators_hash; } // Decoder section /** * @dev The main decoder for memory * @param bs The bytes array to be decoded * @return The decoded struct */ function decode(bytes memory bs) internal pure returns (Data memory) { (Data memory x, ) = _decode(32, bs, bs.length); return x; } /** * @dev The main decoder for storage * @param self The in-storage struct * @param bs The bytes array to be decoded */ function decode(Data storage self, bytes memory bs) internal { (Data memory x, ) = _decode(32, bs, bs.length); store(x, self); } // inner decoder /** * @dev The decoder for internal usage * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param sz The number of bytes expected * @return The decoded struct * @return The number of bytes decoded */ function _decode(uint256 p, bytes memory bs, uint256 sz) internal pure returns (Data memory, uint) { Data memory r; uint[4] memory counters; uint256 fieldId; ProtoBufRuntime.WireType wireType; uint256 bytesRead; uint256 offset = p; uint256 pointer = p; while (pointer < offset + sz) { (fieldId, wireType, bytesRead) = ProtoBufRuntime._decode_key(pointer, bs); pointer += bytesRead; if (fieldId == 1) { pointer += _read_timestamp(pointer, bs, r, counters); } else if (fieldId == 2) { pointer += _read_root(pointer, bs, r, counters); } else if (fieldId == 3) { pointer += _read_next_validators_hash(pointer, bs, r, counters); } else { if (wireType == ProtoBufRuntime.WireType.Fixed64) { uint256 size; (, size) = ProtoBufRuntime._decode_fixed64(pointer, bs); pointer += size; } if (wireType == ProtoBufRuntime.WireType.Fixed32) { uint256 size; (, size) = ProtoBufRuntime._decode_fixed32(pointer, bs); pointer += size; } if (wireType == ProtoBufRuntime.WireType.Varint) { uint256 size; (, size) = ProtoBufRuntime._decode_varint(pointer, bs); pointer += size; } if (wireType == ProtoBufRuntime.WireType.LengthDelim) { uint256 size; (, size) = ProtoBufRuntime._decode_lendelim(pointer, bs); pointer += size; } } } return (r, sz); } // field readers /** * @dev The decoder for reading a field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param r The in-memory struct * @param counters The counters for repeated fields * @return The number of bytes decoded */ function _read_timestamp( uint256 p, bytes memory bs, Data memory r, uint[4] memory counters ) internal pure returns (uint) { /** * if `r` is NULL, then only counting the number of fields. */ (Timestamp.Data memory x, uint256 sz) = _decode_Timestamp(p, bs); if (isNil(r)) { counters[1] += 1; } else { r.timestamp = x; if (counters[1] > 0) counters[1] -= 1; } return sz; } /** * @dev The decoder for reading a field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param r The in-memory struct * @param counters The counters for repeated fields * @return The number of bytes decoded */ function _read_root( uint256 p, bytes memory bs, Data memory r, uint[4] memory counters ) internal pure returns (uint) { /** * if `r` is NULL, then only counting the number of fields. */ (bytes memory x, uint256 sz) = ProtoBufRuntime._decode_bytes(p, bs); if (isNil(r)) { counters[2] += 1; } else { r.root = x; if (counters[2] > 0) counters[2] -= 1; } return sz; } /** * @dev The decoder for reading a field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param r The in-memory struct * @param counters The counters for repeated fields * @return The number of bytes decoded */ function _read_next_validators_hash( uint256 p, bytes memory bs, Data memory r, uint[4] memory counters ) internal pure returns (uint) { /** * if `r` is NULL, then only counting the number of fields. */ (bytes memory x, uint256 sz) = ProtoBufRuntime._decode_bytes(p, bs); if (isNil(r)) { counters[3] += 1; } else { r.next_validators_hash = x; if (counters[3] > 0) counters[3] -= 1; } return sz; } // struct decoder /** * @dev The decoder for reading a inner struct field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @return The decoded inner-struct * @return The number of bytes used to decode */ function _decode_Timestamp(uint256 p, bytes memory bs) internal pure returns (Timestamp.Data memory, uint) { uint256 pointer = p; (uint256 sz, uint256 bytesRead) = ProtoBufRuntime._decode_varint(pointer, bs); pointer += bytesRead; (Timestamp.Data memory r, ) = Timestamp._decode(pointer, bs, sz); return (r, sz + bytesRead); } // Encoder section /** * @dev The main encoder for memory * @param r The struct to be encoded * @return The encoded byte array */ function encode(Data memory r) internal pure returns (bytes memory) { bytes memory bs = new bytes(_estimate(r)); uint256 sz = _encode(r, 32, bs); assembly { mstore(bs, sz) } return bs; } // inner encoder /** * @dev The encoder for internal usage * @param r The struct to be encoded * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @return The number of bytes encoded */ function _encode(Data memory r, uint256 p, bytes memory bs) internal pure returns (uint) { uint256 offset = p; uint256 pointer = p; pointer += ProtoBufRuntime._encode_key( 1, ProtoBufRuntime.WireType.LengthDelim, pointer, bs ); pointer += Timestamp._encode_nested(r.timestamp, pointer, bs); if (r.root.length != 0) { pointer += ProtoBufRuntime._encode_key( 2, ProtoBufRuntime.WireType.LengthDelim, pointer, bs ); pointer += ProtoBufRuntime._encode_bytes(r.root, pointer, bs); } if (r.next_validators_hash.length != 0) { pointer += ProtoBufRuntime._encode_key( 3, ProtoBufRuntime.WireType.LengthDelim, pointer, bs ); pointer += ProtoBufRuntime._encode_bytes(r.next_validators_hash, pointer, bs); } return pointer - offset; } // nested encoder /** * @dev The encoder for inner struct * @param r The struct to be encoded * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @return The number of bytes encoded */ function _encode_nested(Data memory r, uint256 p, bytes memory bs) internal pure returns (uint) { /** * First encoded `r` into a temporary array, and encode the actual size used. * Then copy the temporary array into `bs`. */ uint256 offset = p; uint256 pointer = p; bytes memory tmp = new bytes(_estimate(r)); uint256 tmpAddr = ProtoBufRuntime.getMemoryAddress(tmp); uint256 bsAddr = ProtoBufRuntime.getMemoryAddress(bs); uint256 size = _encode(r, 32, tmp); pointer += ProtoBufRuntime._encode_varint(size, pointer, bs); ProtoBufRuntime.copyBytes(tmpAddr + 32, bsAddr + pointer, size); pointer += size; delete tmp; return pointer - offset; } // estimator /** * @dev The estimator for a struct * @param r The struct to be encoded * @return The number of bytes encoded in estimation */ function _estimate( Data memory r ) internal pure returns (uint) { uint256 e; e += 1 + ProtoBufRuntime._sz_lendelim(Timestamp._estimate(r.timestamp)); e += 1 + ProtoBufRuntime._sz_lendelim(r.root.length); e += 1 + ProtoBufRuntime._sz_lendelim(r.next_validators_hash.length); return e; } // empty checker function _empty( Data memory r ) internal pure returns (bool) { if (r.root.length != 0) { return false; } if (r.next_validators_hash.length != 0) { return false; } return true; } //store function /** * @dev Store in-memory struct to storage * @param input The in-memory struct * @param output The in-storage struct */ function store(Data memory input, Data storage output) internal { Timestamp.store(input.timestamp, output.timestamp); output.root = input.root; output.next_validators_hash = input.next_validators_hash; } //utility functions /** * @dev Return an empty struct * @return r The empty struct */ function nil() internal pure returns (Data memory r) { assembly { r := 0 } } /** * @dev Test whether a struct is empty * @param x The struct to be tested * @return r True if it is empty */ function isNil(Data memory x) internal pure returns (bool r) { assembly { r := iszero(x) } } } //library ConsensusState library Header { //struct definition struct Data { SignedHeader.Data signed_header; ValidatorSet.Data validator_set; Height.Data trusted_height; ValidatorSet.Data trusted_validators; } // Decoder section /** * @dev The main decoder for memory * @param bs The bytes array to be decoded * @return The decoded struct */ function decode(bytes memory bs) internal pure returns (Data memory) { (Data memory x, ) = _decode(32, bs, bs.length); return x; } /** * @dev The main decoder for storage * @param self The in-storage struct * @param bs The bytes array to be decoded */ function decode(Data storage self, bytes memory bs) internal { (Data memory x, ) = _decode(32, bs, bs.length); store(x, self); } // inner decoder /** * @dev The decoder for internal usage * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param sz The number of bytes expected * @return The decoded struct * @return The number of bytes decoded */ function _decode(uint256 p, bytes memory bs, uint256 sz) internal pure returns (Data memory, uint) { Data memory r; uint[5] memory counters; uint256 fieldId; ProtoBufRuntime.WireType wireType; uint256 bytesRead; uint256 offset = p; uint256 pointer = p; while (pointer < offset + sz) { (fieldId, wireType, bytesRead) = ProtoBufRuntime._decode_key(pointer, bs); pointer += bytesRead; if (fieldId == 1) { pointer += _read_signed_header(pointer, bs, r, counters); } else if (fieldId == 2) { pointer += _read_validator_set(pointer, bs, r, counters); } else if (fieldId == 3) { pointer += _read_trusted_height(pointer, bs, r, counters); } else if (fieldId == 4) { pointer += _read_trusted_validators(pointer, bs, r, counters); } else { if (wireType == ProtoBufRuntime.WireType.Fixed64) { uint256 size; (, size) = ProtoBufRuntime._decode_fixed64(pointer, bs); pointer += size; } if (wireType == ProtoBufRuntime.WireType.Fixed32) { uint256 size; (, size) = ProtoBufRuntime._decode_fixed32(pointer, bs); pointer += size; } if (wireType == ProtoBufRuntime.WireType.Varint) { uint256 size; (, size) = ProtoBufRuntime._decode_varint(pointer, bs); pointer += size; } if (wireType == ProtoBufRuntime.WireType.LengthDelim) { uint256 size; (, size) = ProtoBufRuntime._decode_lendelim(pointer, bs); pointer += size; } } } return (r, sz); } // field readers /** * @dev The decoder for reading a field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param r The in-memory struct * @param counters The counters for repeated fields * @return The number of bytes decoded */ function _read_signed_header( uint256 p, bytes memory bs, Data memory r, uint[5] memory counters ) internal pure returns (uint) { /** * if `r` is NULL, then only counting the number of fields. */ (SignedHeader.Data memory x, uint256 sz) = _decode_SignedHeader(p, bs); if (isNil(r)) { counters[1] += 1; } else { r.signed_header = x; if (counters[1] > 0) counters[1] -= 1; } return sz; } /** * @dev The decoder for reading a field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param r The in-memory struct * @param counters The counters for repeated fields * @return The number of bytes decoded */ function _read_validator_set( uint256 p, bytes memory bs, Data memory r, uint[5] memory counters ) internal pure returns (uint) { /** * if `r` is NULL, then only counting the number of fields. */ (ValidatorSet.Data memory x, uint256 sz) = _decode_ValidatorSet(p, bs); if (isNil(r)) { counters[2] += 1; } else { r.validator_set = x; if (counters[2] > 0) counters[2] -= 1; } return sz; } /** * @dev The decoder for reading a field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param r The in-memory struct * @param counters The counters for repeated fields * @return The number of bytes decoded */ function _read_trusted_height( uint256 p, bytes memory bs, Data memory r, uint[5] memory counters ) internal pure returns (uint) { /** * if `r` is NULL, then only counting the number of fields. */ (Height.Data memory x, uint256 sz) = _decode_Height(p, bs); if (isNil(r)) { counters[3] += 1; } else { r.trusted_height = x; if (counters[3] > 0) counters[3] -= 1; } return sz; } /** * @dev The decoder for reading a field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param r The in-memory struct * @param counters The counters for repeated fields * @return The number of bytes decoded */ function _read_trusted_validators( uint256 p, bytes memory bs, Data memory r, uint[5] memory counters ) internal pure returns (uint) { /** * if `r` is NULL, then only counting the number of fields. */ (ValidatorSet.Data memory x, uint256 sz) = _decode_ValidatorSet(p, bs); if (isNil(r)) { counters[4] += 1; } else { r.trusted_validators = x; if (counters[4] > 0) counters[4] -= 1; } return sz; } // struct decoder /** * @dev The decoder for reading a inner struct field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @return The decoded inner-struct * @return The number of bytes used to decode */ function _decode_SignedHeader(uint256 p, bytes memory bs) internal pure returns (SignedHeader.Data memory, uint) { uint256 pointer = p; (uint256 sz, uint256 bytesRead) = ProtoBufRuntime._decode_varint(pointer, bs); pointer += bytesRead; (SignedHeader.Data memory r, ) = SignedHeader._decode(pointer, bs, sz); return (r, sz + bytesRead); } /** * @dev The decoder for reading a inner struct field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @return The decoded inner-struct * @return The number of bytes used to decode */ function _decode_ValidatorSet(uint256 p, bytes memory bs) internal pure returns (ValidatorSet.Data memory, uint) { uint256 pointer = p; (uint256 sz, uint256 bytesRead) = ProtoBufRuntime._decode_varint(pointer, bs); pointer += bytesRead; (ValidatorSet.Data memory r, ) = ValidatorSet._decode(pointer, bs, sz); return (r, sz + bytesRead); } /** * @dev The decoder for reading a inner struct field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @return The decoded inner-struct * @return The number of bytes used to decode */ function _decode_Height(uint256 p, bytes memory bs) internal pure returns (Height.Data memory, uint) { uint256 pointer = p; (uint256 sz, uint256 bytesRead) = ProtoBufRuntime._decode_varint(pointer, bs); pointer += bytesRead; (Height.Data memory r, ) = Height._decode(pointer, bs, sz); return (r, sz + bytesRead); } // Encoder section /** * @dev The main encoder for memory * @param r The struct to be encoded * @return The encoded byte array */ function encode(Data memory r) internal pure returns (bytes memory) { bytes memory bs = new bytes(_estimate(r)); uint256 sz = _encode(r, 32, bs); assembly { mstore(bs, sz) } return bs; } // inner encoder /** * @dev The encoder for internal usage * @param r The struct to be encoded * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @return The number of bytes encoded */ function _encode(Data memory r, uint256 p, bytes memory bs) internal pure returns (uint) { uint256 offset = p; uint256 pointer = p; pointer += ProtoBufRuntime._encode_key( 1, ProtoBufRuntime.WireType.LengthDelim, pointer, bs ); pointer += SignedHeader._encode_nested(r.signed_header, pointer, bs); pointer += ProtoBufRuntime._encode_key( 2, ProtoBufRuntime.WireType.LengthDelim, pointer, bs ); pointer += ValidatorSet._encode_nested(r.validator_set, pointer, bs); pointer += ProtoBufRuntime._encode_key( 3, ProtoBufRuntime.WireType.LengthDelim, pointer, bs ); pointer += Height._encode_nested(r.trusted_height, pointer, bs); pointer += ProtoBufRuntime._encode_key( 4, ProtoBufRuntime.WireType.LengthDelim, pointer, bs ); pointer += ValidatorSet._encode_nested(r.trusted_validators, pointer, bs); return pointer - offset; } // nested encoder /** * @dev The encoder for inner struct * @param r The struct to be encoded * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @return The number of bytes encoded */ function _encode_nested(Data memory r, uint256 p, bytes memory bs) internal pure returns (uint) { /** * First encoded `r` into a temporary array, and encode the actual size used. * Then copy the temporary array into `bs`. */ uint256 offset = p; uint256 pointer = p; bytes memory tmp = new bytes(_estimate(r)); uint256 tmpAddr = ProtoBufRuntime.getMemoryAddress(tmp); uint256 bsAddr = ProtoBufRuntime.getMemoryAddress(bs); uint256 size = _encode(r, 32, tmp); pointer += ProtoBufRuntime._encode_varint(size, pointer, bs); ProtoBufRuntime.copyBytes(tmpAddr + 32, bsAddr + pointer, size); pointer += size; delete tmp; return pointer - offset; } // estimator /** * @dev The estimator for a struct * @param r The struct to be encoded * @return The number of bytes encoded in estimation */ function _estimate( Data memory r ) internal pure returns (uint) { uint256 e; e += 1 + ProtoBufRuntime._sz_lendelim(SignedHeader._estimate(r.signed_header)); e += 1 + ProtoBufRuntime._sz_lendelim(ValidatorSet._estimate(r.validator_set)); e += 1 + ProtoBufRuntime._sz_lendelim(Height._estimate(r.trusted_height)); e += 1 + ProtoBufRuntime._sz_lendelim(ValidatorSet._estimate(r.trusted_validators)); return e; } // empty checker function _empty( Data memory r ) internal pure returns (bool) { return true; } //store function /** * @dev Store in-memory struct to storage * @param input The in-memory struct * @param output The in-storage struct */ function store(Data memory input, Data storage output) internal { SignedHeader.store(input.signed_header, output.signed_header); ValidatorSet.store(input.validator_set, output.validator_set); Height.store(input.trusted_height, output.trusted_height); ValidatorSet.store(input.trusted_validators, output.trusted_validators); } //utility functions /** * @dev Return an empty struct * @return r The empty struct */ function nil() internal pure returns (Data memory r) { assembly { r := 0 } } /** * @dev Test whether a struct is empty * @param x The struct to be tested * @return r True if it is empty */ function isNil(Data memory x) internal pure returns (bool r) { assembly { r := iszero(x) } } } //library Header library Fraction { //struct definition struct Data { uint64 numerator; uint64 denominator; } // Decoder section /** * @dev The main decoder for memory * @param bs The bytes array to be decoded * @return The decoded struct */ function decode(bytes memory bs) internal pure returns (Data memory) { (Data memory x, ) = _decode(32, bs, bs.length); return x; } /** * @dev The main decoder for storage * @param self The in-storage struct * @param bs The bytes array to be decoded */ function decode(Data storage self, bytes memory bs) internal { (Data memory x, ) = _decode(32, bs, bs.length); store(x, self); } // inner decoder /** * @dev The decoder for internal usage * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param sz The number of bytes expected * @return The decoded struct * @return The number of bytes decoded */ function _decode(uint256 p, bytes memory bs, uint256 sz) internal pure returns (Data memory, uint) { Data memory r; uint[3] memory counters; uint256 fieldId; ProtoBufRuntime.WireType wireType; uint256 bytesRead; uint256 offset = p; uint256 pointer = p; while (pointer < offset + sz) { (fieldId, wireType, bytesRead) = ProtoBufRuntime._decode_key(pointer, bs); pointer += bytesRead; if (fieldId == 1) { pointer += _read_numerator(pointer, bs, r, counters); } else if (fieldId == 2) { pointer += _read_denominator(pointer, bs, r, counters); } else { if (wireType == ProtoBufRuntime.WireType.Fixed64) { uint256 size; (, size) = ProtoBufRuntime._decode_fixed64(pointer, bs); pointer += size; } if (wireType == ProtoBufRuntime.WireType.Fixed32) { uint256 size; (, size) = ProtoBufRuntime._decode_fixed32(pointer, bs); pointer += size; } if (wireType == ProtoBufRuntime.WireType.Varint) { uint256 size; (, size) = ProtoBufRuntime._decode_varint(pointer, bs); pointer += size; } if (wireType == ProtoBufRuntime.WireType.LengthDelim) { uint256 size; (, size) = ProtoBufRuntime._decode_lendelim(pointer, bs); pointer += size; } } } return (r, sz); } // field readers /** * @dev The decoder for reading a field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param r The in-memory struct * @param counters The counters for repeated fields * @return The number of bytes decoded */ function _read_numerator( uint256 p, bytes memory bs, Data memory r, uint[3] memory counters ) internal pure returns (uint) { /** * if `r` is NULL, then only counting the number of fields. */ (uint64 x, uint256 sz) = ProtoBufRuntime._decode_uint64(p, bs); if (isNil(r)) { counters[1] += 1; } else { r.numerator = x; if (counters[1] > 0) counters[1] -= 1; } return sz; } /** * @dev The decoder for reading a field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param r The in-memory struct * @param counters The counters for repeated fields * @return The number of bytes decoded */ function _read_denominator( uint256 p, bytes memory bs, Data memory r, uint[3] memory counters ) internal pure returns (uint) { /** * if `r` is NULL, then only counting the number of fields. */ (uint64 x, uint256 sz) = ProtoBufRuntime._decode_uint64(p, bs); if (isNil(r)) { counters[2] += 1; } else { r.denominator = x; if (counters[2] > 0) counters[2] -= 1; } return sz; } // Encoder section /** * @dev The main encoder for memory * @param r The struct to be encoded * @return The encoded byte array */ function encode(Data memory r) internal pure returns (bytes memory) { bytes memory bs = new bytes(_estimate(r)); uint256 sz = _encode(r, 32, bs); assembly { mstore(bs, sz) } return bs; } // inner encoder /** * @dev The encoder for internal usage * @param r The struct to be encoded * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @return The number of bytes encoded */ function _encode(Data memory r, uint256 p, bytes memory bs) internal pure returns (uint) { uint256 offset = p; uint256 pointer = p; if (r.numerator != 0) { pointer += ProtoBufRuntime._encode_key( 1, ProtoBufRuntime.WireType.Varint, pointer, bs ); pointer += ProtoBufRuntime._encode_uint64(r.numerator, pointer, bs); } if (r.denominator != 0) { pointer += ProtoBufRuntime._encode_key( 2, ProtoBufRuntime.WireType.Varint, pointer, bs ); pointer += ProtoBufRuntime._encode_uint64(r.denominator, pointer, bs); } return pointer - offset; } // nested encoder /** * @dev The encoder for inner struct * @param r The struct to be encoded * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @return The number of bytes encoded */ function _encode_nested(Data memory r, uint256 p, bytes memory bs) internal pure returns (uint) { /** * First encoded `r` into a temporary array, and encode the actual size used. * Then copy the temporary array into `bs`. */ uint256 offset = p; uint256 pointer = p; bytes memory tmp = new bytes(_estimate(r)); uint256 tmpAddr = ProtoBufRuntime.getMemoryAddress(tmp); uint256 bsAddr = ProtoBufRuntime.getMemoryAddress(bs); uint256 size = _encode(r, 32, tmp); pointer += ProtoBufRuntime._encode_varint(size, pointer, bs); ProtoBufRuntime.copyBytes(tmpAddr + 32, bsAddr + pointer, size); pointer += size; delete tmp; return pointer - offset; } // estimator /** * @dev The estimator for a struct * @param r The struct to be encoded * @return The number of bytes encoded in estimation */ function _estimate( Data memory r ) internal pure returns (uint) { uint256 e; e += 1 + ProtoBufRuntime._sz_uint64(r.numerator); e += 1 + ProtoBufRuntime._sz_uint64(r.denominator); return e; } // empty checker function _empty( Data memory r ) internal pure returns (bool) { if (r.numerator != 0) { return false; } if (r.denominator != 0) { return false; } return true; } //store function /** * @dev Store in-memory struct to storage * @param input The in-memory struct * @param output The in-storage struct */ function store(Data memory input, Data storage output) internal { output.numerator = input.numerator; output.denominator = input.denominator; } //utility functions /** * @dev Return an empty struct * @return r The empty struct */ function nil() internal pure returns (Data memory r) { assembly { r := 0 } } /** * @dev Test whether a struct is empty * @param x The struct to be tested * @return r True if it is empty */ function isNil(Data memory x) internal pure returns (bool r) { assembly { r := iszero(x) } } } //library Fraction
The encoder for internal usage r The struct to be encoded p The offset of bytes array to start decode bs The bytes array to be decoded return The number of bytes encoded/
function _encode(Data memory r, uint256 p, bytes memory bs) internal pure returns (uint) { uint256 offset = p; uint256 pointer = p; pointer += ProtoBufRuntime._encode_key( 1, ProtoBufRuntime.WireType.LengthDelim, pointer, bs ); pointer += SignedHeader._encode_nested(r.signed_header, pointer, bs); pointer += ProtoBufRuntime._encode_key( 2, ProtoBufRuntime.WireType.LengthDelim, pointer, bs ); pointer += ValidatorSet._encode_nested(r.validator_set, pointer, bs); pointer += ProtoBufRuntime._encode_key( 3, ProtoBufRuntime.WireType.LengthDelim, pointer, bs ); pointer += Height._encode_nested(r.trusted_height, pointer, bs); pointer += ProtoBufRuntime._encode_key( 4, ProtoBufRuntime.WireType.LengthDelim, pointer, bs ); pointer += ValidatorSet._encode_nested(r.trusted_validators, pointer, bs); return pointer - offset; }
5,547,669
pragma solidity 0.4.15; contract BettingContract { /* Standard state variables */ address public owner; address public gamblerA; address public gamblerB; address public oracle; uint[] outcomes; /* Structs are custom data structures with self-defined parameters */ struct Bet { uint outcome; uint amount; bool initialized; } /* Keep track of every gambler's bet */ mapping (address => Bet) bets; /* Keep track of every player's winnings (if any) */ mapping (address => uint) winnings; /* Add any events you think are necessary */ event BetMade(address gambler); event BetClosed(); /* Uh Oh, what are these? */ modifier OwnerOnly() { if(msg.sender == owner){ _; } } modifier OracleOnly() {if(msg.sender == oracle){ _; } } /* Constructor function, where owner and outcomes are set */ function BettingContract(uint[] _outcomes) { owner = msg.sender; outcomes = _outcomes; } /* Owner chooses their trusted Oracle */ function chooseOracle(address _oracle) OwnerOnly() returns (address) { oracle = _oracle; return oracle; } /* Gamblers place their bets, preferably after calling checkOutcomes */ function makeBet(uint _outcome) payable returns (bool) { uint count = 0; if(checkOutcomes().length > 0){ gamblerA = msg.sender; bets[gamblerA] = Bet(_outcome, msg.value, false); oracle.transfer(bets[gamblerA].amount); BetMade(gamblerA); count++; } if(checkOutcomes().length > 0){ gamblerB = msg.sender; bets[gamblerB] = Bet(_outcome, msg.value, false); oracle.transfer(bets[gamblerB].amount); BetMade(gamblerB); count++; } if(count > 0) { return true; } return false; } /* The oracle chooses which outcome wins */ function makeDecision(uint _outcome) payable OracleOnly() { oracle = msg.sender; if (bets[gamblerA].outcome == bets[gamblerB].outcome){ gamblerA.transfer(bets[gamblerA].amount); gamblerB.transfer(bets[gamblerB].amount); } else if (bets[gamblerA].outcome == _outcome){ gamblerA.transfer(bets[gamblerA].amount + bets[gamblerB].amount); } else if (bets[gamblerB].outcome == _outcome){ gamblerB.transfer(bets[gamblerA].amount + bets[gamblerB].amount); } BetClosed(); } /* Allow anyone to withdraw their winnings safely (if they have enough) */ function withdraw(uint withdrawAmount) returns (uint remainingBal) { if(winnings[msg.sender] >= withdrawAmount){ winnings[msg.sender] -= withdrawAmount; if (!msg.sender.send(withdrawAmount)){ winnings[msg.sender] += withdrawAmount; } remainingBal = withdrawAmount; return remainingBal; } } /* Allow anyone to check the outcomes they can bet on */ function checkOutcomes() constant returns (uint[]) { return outcomes; } /* Allow anyone to check if they won any bets */ function checkWinnings() constant returns(uint) { return winnings[msg.sender]; } /* Call delete() to reset certain state variables. Which ones? That's upto you to decide */ function contractReset() private { delete gamblerA; delete gamblerB; delete oracle; } /* Fallback function */ function() payable { revert(); } }
The oracle chooses which outcome wins /
function makeDecision(uint _outcome) payable OracleOnly() { oracle = msg.sender; if (bets[gamblerA].outcome == bets[gamblerB].outcome){ gamblerA.transfer(bets[gamblerA].amount); gamblerB.transfer(bets[gamblerB].amount); } else if (bets[gamblerA].outcome == _outcome){ gamblerA.transfer(bets[gamblerA].amount + bets[gamblerB].amount); } else if (bets[gamblerB].outcome == _outcome){ gamblerB.transfer(bets[gamblerA].amount + bets[gamblerB].amount); } BetClosed(); }
13,038,449
// SPDX-License-Identifier: UNLICENSED pragma solidity ^0.8.2; import '@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol'; import './ERC721UpgradeableWrapper.sol'; import '../Collection/CollectionWrapper.sol'; import '../Collection/ERC721MultipleBoxWrapper.sol'; /// @title ERC721MultiCollectionUpgradeable contract, contract ERC721MultiCollectionUpgradeable is ERC721UpgradeableWrapper, CollectionWrapper, ERC721MultipleBoxWrapper { using SafeERC20 for IERC20; /// @dev Payment event /// @param payToken pay token /// @param from payer /// @param to token receiver /// @param tokenId token id /// @param amount token value event Payment(IERC20 indexed payToken, address indexed from, address indexed to, uint256 tokenId, uint256 amount); constructor() initializer {} /// @dev proxy contract initialization /// @param newOwner owner of this contract /// @param name contract name /// @param symbol contract symbol /// @param root tokens merkle root /// @param param default contract param function initialize( address newOwner, string memory name, string memory symbol, bytes32 root, MintBoxPool pool, Param memory param ) external initializer { __ERC721_init(name, symbol); _transferOwnership(newOwner); _addRoot(root); _CollectionWrapper_Init(pool); _setParam(param); } /// @dev claim and mint the token /// @param to receiver of the token /// @param root tokens root /// @param uri token uri /// @param creator token creator /// @param proofs token proofs /// @return value erc20 token value function claimAndMint( address to, bytes32 root, string memory uri, address creator, bytes32[] memory proofs ) external returns (uint256 value) { uint256 tokenId = _claim(root, uri, creator, proofs); return _buy(to, tokenId); } /// @dev only the nft has been claimed /// @param to receiver of the token. /// @param tokenId id of the token. /// @return value erc20 token value function mint(address to, uint256 tokenId) external returns (uint256 value) { return _buy(to, tokenId); } function _buy(address to, uint256 tokenId) internal returns (uint256 value) { require(isOpen(), 'ERC721MultiCollectionUpgradeable: collection is not open'); value = valueOf(1); IERC20 payToken = payToken(); if (value > 0) { payToken.safeTransferFrom(msg.sender, address(this), value); _depositPool(payToken, value); } _mintToken(to, tokenId); _mint(to, tokenId); emit Payment(payToken, msg.sender, address(this), tokenId, value); } /// @dev claim the token /// @param root tokens root /// @param uri token uri /// @param creator token creator /// @param proofs token proofs function claim( bytes32 root, string memory uri, address creator, bytes32[] memory proofs ) external returns (uint256 tokenId) { tokenId = _claim(root, uri, creator, proofs); } /// @dev add tokens with the merkle root /// @param root tokens root function addRoot(bytes32 root) external onlyOwner { _addRoot(root); } /// @dev get token uri /// @param tokenId token id /// @return token uri function tokenURI(uint256 tokenId) public view override returns (string memory) { require(_exists(tokenId), 'ERC721MultiCollectionUpgradeable: nonexistent token.'); return _tokenURI(tokenId); } }
get token uri tokenId token id return token uri
function tokenURI(uint256 tokenId) public view override returns (string memory) { require(_exists(tokenId), 'ERC721MultiCollectionUpgradeable: nonexistent token.'); return _tokenURI(tokenId); }
6,463,202
// SPDX-License-Identifier: UNLICENSED pragma solidity >=0.7.0 <0.9.0; import "./test.sol"; import "../contracts/Dao.sol"; import "../contracts/DaoContract.sol"; interface CheatCodes { function prank(address) external; function expectRevert(bytes calldata) external; } string constant NullString = ""; bytes constant NullBytes = ""; address constant NullAddress = address(0); contract DaoTest is DSTest { CheatCodes cheats = CheatCodes(HEVM_ADDRESS); Dao dao; string public gDaoName = "MyDao"; address public gTopicAddress = 0x0000000000000000000000000000000000012345; uint32 public gMaxUsers = 100000; uint256 gBatchSize = 1000; uint32 gAccessUpdateAuthIdentifier = 0x853d9ed4; uint32 gRemovalAuthIdentifier = 0x04939f12; uint32 gNotUserIdentifier = 0x51ef2234; address[] public gUsers = [ address(0x1), address(0x2), address(0x3), address(0x4), address(0x5), address(0x6), address(0x7), address(0x8), address(0x9)]; receive() external payable { } function setUp() public { dao = new Dao(gDaoName, gTopicAddress, address(this)); } // ================= // Utility Functions // ================= function CreateErorrCallData(uint32 _identifier, uint256 _arg1) internal pure returns(bytes memory){ return abi.encodePacked(_identifier, _arg1); } function CreateErorrCallData(uint32 _identifier, uint256 _arg1, uint256 _arg2) internal pure returns(bytes memory){ return abi.encodePacked(_identifier, _arg1, _arg2); } function bytesCmp(bytes memory a, bytes memory b) public pure returns(bool){ return keccak256(abi.encodePacked(a)) == keccak256(abi.encodePacked(b)); } function addAUserNoImpersonateNoRevert(address user, AccessType userLevel) public { addAUserNoImpersonate(user, userLevel, NullBytes); } function addAUserNoImpersonateWithRevert(address user, AccessType userLevel, bytes memory revertMessage) public { addAUserNoImpersonate(user, userLevel, revertMessage); } function addAUserNoImpersonate(address user, AccessType userLevel, bytes memory revertMessage) public { addAUser(user, userLevel, NullAddress, revertMessage); } function addAUserWithImpersonateNoRevert(address user, AccessType userLevel, address impersonateAs) public { addAUserWithImpersonate(user, userLevel, impersonateAs, NullBytes); } function addAUserWithImpersonateWithRevert(address user, AccessType userLevel, address impersonateAs, bytes memory revertMessage) public { addAUserWithImpersonate(user, userLevel, impersonateAs, revertMessage); } function addAUserWithImpersonate(address user, AccessType userLevel, address impersonateAs, bytes memory revertMessage) public { addAUser(user, userLevel, impersonateAs, revertMessage); } function addAUser(address user, AccessType userLevel, address impersonateAs, bytes memory revertMessage) public { address[] memory param = new address[](1); param[0] = user; AccessType origUserLevel = dao.getUser(user); bool expectSuccess = true; if(impersonateAs != NullAddress){ cheats.prank(impersonateAs); } if(!bytesCmp(revertMessage, NullBytes)){ cheats.expectRevert(bytes(revertMessage)); expectSuccess = false; } dao.addUser(param, userLevel); if(expectSuccess){ assertEq(uint(dao.getUser(user)), uint(userLevel)); } else { assertEq(uint(dao.getUser(user)), uint(origUserLevel)); } } function removeAUserNoImpersonateNoRevert(address user) public { removeAUserNoImpersonate(user, NullBytes); } function removeAUserNoImpersonateWithRevert(address user, bytes memory revertMessage) public { removeAUserNoImpersonate(user, revertMessage); } function removeAUserNoImpersonate(address user, bytes memory revertMessage) public { removeAUser(user, NullAddress, revertMessage); } function removeAUserWithImpersonateNoRevert(address user, address impersonateAs) public { removeAUserWithImpersonate(user, impersonateAs, NullBytes); } function removeAUserWithImpersonateWithRevert(address user, address impersonateAs, bytes memory revertMessage) public { removeAUserWithImpersonate(user, impersonateAs, revertMessage); } function removeAUserWithImpersonate(address user, address impersonateAs, bytes memory revertMessage) public { removeAUser(user, impersonateAs, revertMessage); } function removeAUser(address user, address impersonateAs, bytes memory revertMessage) public { address[] memory param = new address[](1); param[0] = user; AccessType origUserLevel = dao.getUser(user); bool expectSuccess = true; if(impersonateAs != NullAddress){ cheats.prank(impersonateAs); } if(!bytesCmp(revertMessage, NullBytes)){ cheats.expectRevert(bytes(revertMessage)); expectSuccess = false; } dao.removeUser(param); if(expectSuccess){ assertEq(uint(dao.getUser(user)), uint(0)); } else { assertEq(uint(dao.getUser(user)), uint(origUserLevel)); } } function removeUsersNoImpersonateNoRevert(address[] memory users) public { removeUsersNoImpersonate(users, NullBytes); } function removeUsersNoImpersonateWithRevert(address[] memory users, bytes memory revertMessage) public { removeUsersNoImpersonate(users, revertMessage); } function removeUsersNoImpersonate(address[] memory users, bytes memory revertMessage) public { removeUsers(users, NullAddress, revertMessage); } function removeUsersWithImpersonateNoRevert(address[] memory users, address impersonateAs) public { removeUsersWithImpersonate(users, impersonateAs, NullBytes); } function removeUsersWithImpersonateWithRevert(address[] memory users, address impersonateAs, bytes memory revertMessage) public { removeUsersWithImpersonate(users, impersonateAs, revertMessage); } function removeUsersWithImpersonate(address[] memory users, address impersonateAs, bytes memory revertMessage) public { removeUsers(users, impersonateAs, revertMessage); } function removeUsers(address[] memory users, address impersonateAs, bytes memory revertMessage) public { AccessType[] memory originalUserLevels = new AccessType[](users.length); for (uint i = 0; i < users.length; i++){ originalUserLevels[i] = dao.getUser(users[i]); } bool expectSuccess = true; if(impersonateAs != NullAddress){ cheats.prank(impersonateAs); } if(!bytesCmp(revertMessage, NullBytes)){ cheats.expectRevert(bytes(revertMessage)); expectSuccess = false; } dao.removeUser(users); if(expectSuccess){ for(uint i = 0; i < users.length; i++){ assertEq(uint(dao.getUser(users[i])), uint(0)); } } else { for (uint i = 0; i < users.length; i++){ assertEq(uint(dao.getUser(users[i])), uint(originalUserLevels[i])); } } } function removeAnOfficerNoImpersonateNoRevert(address user) public { removeAnOfficerNoImpersonate(user, NullBytes); } function removeAnOfficerNoImpersonateWithRevert(address user, bytes memory revertMessage) public { removeAnOfficerNoImpersonate(user, revertMessage); } function removeAnOfficerNoImpersonate(address user, bytes memory revertMessage) public { removeAnOfficer(user, NullAddress, revertMessage); } function removeAnOfficerWithImpersonateNoRevert(address user, address impersonateAs) public { removeAnOfficerWithImpersonate(user, impersonateAs, NullBytes); } function removeAnOfficerWithImpersonateWithRevert(address user, address impersonateAs, bytes memory revertMessage) public { removeAnOfficerWithImpersonate(user, impersonateAs, revertMessage); } function removeAnOfficerWithImpersonate(address user, address impersonateAs, bytes memory revertMessage) public { removeAnOfficer(user, impersonateAs, revertMessage); } function removeAnOfficer(address user, address impersonateAs, bytes memory revertMessage) public { bool expectSuccess = true; AccessType origUserLevel = dao.getUser(user); if(impersonateAs != NullAddress){ cheats.prank(impersonateAs); } if(!bytesCmp(revertMessage, NullBytes)){ cheats.expectRevert(bytes(revertMessage)); expectSuccess = false; } dao.removeOfficer(user); if(expectSuccess){ assertEq(uint(dao.getUser(user)), uint(0)); } else { assertEq(uint(dao.getUser(user)), uint(origUserLevel)); } } function addMaxUsers(bool batched, AccessType level, uint256 batchSize) public { uint160 i; uint32 batches; uint256 numUsersToAdd = gMaxUsers - dao.getUserCount(); // Force non batched if maxUsers is less than batchSize if (gMaxUsers < batchSize){ batched = false; } if(batched){ address[] memory batch = new address[](batchSize); // Add users in batches minus the last batch witch may be // not a whole batch of batchSize. for ( ;i < (numUsersToAdd - numUsersToAdd % batchSize); i++){ // Add user to batch batch[i%batch.length] = address(i); // Only send the batch to the contract when its full if((i%batch.length) == (batch.length-1)){ emit log_named_uint("Batch", batches++); dao.addUser(batch, level); } } } // If batched, now send final batch (not full batch) // If non batched, send all users now in a single batch if((numUsersToAdd - i) > 0) { address[] memory finalBatch = new address[](numUsersToAdd - i); for (uint160 j = 0; i < numUsersToAdd; i++) { finalBatch[j++] = address(i); } emit log_named_uint("- Batch", batches++); dao.addUser(finalBatch, level); } assertEq(dao.getUserCount(), gMaxUsers); } // =================================================== // ============ // Test getters // ============ function testGetDaoNameBase() public { assertEq(dao.getDaoName(), gDaoName); } function testGetMaxUsersBase() public { assertEq(dao.getMaxUsers(), gMaxUsers); } function testGetTopicAddressBase() public { assertEq(dao.getTopicAddress(), gTopicAddress); } function testGetUserCountBase() public { assertEq(dao.getUserCount(), 1); } function testGetUserBase() public { assertEq(uint(dao.getUser(address(this))), uint(AccessType.Officer)); } function testGetBalance() public { assertEq(dao.getBalance(), 0); } // ============ // Test setters // ============ function testSetMaxUsers() public { uint32 newMaxUsers = 500000; dao.setMaxUsers(newMaxUsers); assertEq(dao.getMaxUsers(), newMaxUsers); dao.setMaxUsers(gMaxUsers); assertEq(dao.getMaxUsers(), gMaxUsers); } function testSetMaxUsersAsNonOwner() public { cheats.prank(gUsers[1]); cheats.expectRevert('Only owner is allowed'); dao.setMaxUsers(1234); } // ================================== // Test adding Member user via addUser // ================================== function testAddUserMemberAsOwner() public { addAUserNoImpersonateNoRevert(gUsers[1], AccessType.Member); assertEq(dao.getUserCount(), 2); } function testAddUserMemberAsMember() public { // Add gUsers[1] as a member addAUserNoImpersonateNoRevert(gUsers[1], AccessType.Member); assertEq(dao.getUserCount(), 2); // Have gUsers[1] try to add gUsers[2] as a member addAUserWithImpersonateWithRevert(gUsers[2], AccessType.Member, gUsers[1], "Not authorized to grant"); assertEq(dao.getUserCount(), 2); } function testAddUserMemberAsAdmin() public { // Add gUsers[1] as an Admin addAUserNoImpersonateNoRevert(gUsers[1], AccessType.Admin); assertEq(dao.getUserCount(), 2); // Have gUsers[1] try to add gUsers[2] as a member addAUserWithImpersonateNoRevert(gUsers[2], AccessType.Member, gUsers[1]); assertEq(dao.getUserCount(), 3); } function testAddUserMemberAsOfficer() public { // Add gUsers[1] as an Officer addAUserNoImpersonateNoRevert(gUsers[1], AccessType.Officer); assertEq(dao.getUserCount(), 2); // Have gUsers[1] try to add gUsers[2] as a member addAUserWithImpersonateNoRevert(gUsers[2], AccessType.Member, gUsers[1]); assertEq(dao.getUserCount(), 3); } // ================================== // Test adding Admin user via addUser // ================================== function testAddUserAdminAsOwner() public { addAUserNoImpersonateNoRevert(gUsers[1], AccessType.Admin); assertEq(dao.getUserCount(), 2); } function testAddUserAdminAsMember() public { // Add gUsers[1] as an Member addAUserNoImpersonateNoRevert(gUsers[1], AccessType.Member); assertEq(dao.getUserCount(), 2); // Have gUsers[1] try to add gUsers[2] as an Admin addAUserWithImpersonateWithRevert(gUsers[2], AccessType.Admin, gUsers[1], "Not authorized to grant"); assertEq(dao.getUserCount(), 2); } function testAddUserAdminAsAdmin() public { // Add gUsers[1] as an Admin addAUserNoImpersonateNoRevert(gUsers[1], AccessType.Admin); assertEq(dao.getUserCount(), 2); // Have gUsers[1] try to add gUsers[2] as an Admin addAUserWithImpersonateNoRevert(gUsers[2], AccessType.Admin, gUsers[1]); assertEq(dao.getUserCount(), 3); } function testAddUserAdminAsOfficer() public { // Add gUsers[1] as an Officer addAUserNoImpersonateNoRevert(gUsers[1], AccessType.Officer); assertEq(dao.getUserCount(), 2); // Have gUsers[1] try to add gUsers[2] as an Admin addAUserWithImpersonateNoRevert(gUsers[2], AccessType.Admin, gUsers[1]); assertEq(dao.getUserCount(), 3); } // ==================================== // Test adding Officer user via addUser // ==================================== function testAddUserOfficerAsOwner() public { addAUserNoImpersonateNoRevert(gUsers[1], AccessType.Officer); assertEq(dao.getUserCount(), 2); } function testAddUserOfficerAsMember() public { // Add gUsers[1] as an Member addAUserNoImpersonateNoRevert(gUsers[1], AccessType.Member); assertEq(dao.getUserCount(), 2); // Have gUsers[1] try to add gUsers[2] as an Officer addAUserWithImpersonateWithRevert(gUsers[2], AccessType.Officer, gUsers[1], "Not authorized to grant"); assertEq(dao.getUserCount(), 2); } function testAddUserOfficerAsAdmin() public { // Add gUsers[1] as an Admin addAUserNoImpersonateNoRevert(gUsers[1], AccessType.Admin); assertEq(dao.getUserCount(), 2); // Have gUsers[1] try to add gUsers[2] as an Officer addAUserWithImpersonateWithRevert(gUsers[2], AccessType.Officer, gUsers[1], "Not authorized to grant"); assertEq(dao.getUserCount(), 2); } function testAddUserOfficerAsOfficer() public { // Add gUsers[1] as an Officer addAUserNoImpersonateNoRevert(gUsers[1], AccessType.Officer); assertEq(dao.getUserCount(), 2); // Have gUsers[1] try to add gUsers[2] as an Officer cheats.prank(gUsers[1]); addAUserWithImpersonateNoRevert(gUsers[2], AccessType.Officer, gUsers[1]); assertEq(dao.getUserCount(), 3); } // ========================================= // Test removing Member user via removeUser // ========================================= function testRemoveUserMemberAsOwner() public { // Add gUsers[1] as a Member addAUserNoImpersonateNoRevert(gUsers[1], AccessType.Member); assertEq(dao.getUserCount(), 2); // Remove gUsers[1] as owner removeAUserNoImpersonateNoRevert(gUsers[1]); assertEq(dao.getUserCount(), 1); } function testRemoveUserMemberAsMember() public { // Add gUsers[1] and gUsers[2] as Members addAUserNoImpersonateNoRevert(gUsers[1], AccessType.Member); addAUserNoImpersonateNoRevert(gUsers[2], AccessType.Member); assertEq(dao.getUserCount(), 3); // Remove gUsers[2] as gUsers[1] who is a member removeAUserWithImpersonateWithRevert(gUsers[2], gUsers[1], "Not authorized to remove"); assertEq(dao.getUserCount(), 3); } function testRemoveUserMemberAsAdmin() public { // Add gUsers[1] as an Admin addAUserNoImpersonateNoRevert(gUsers[1], AccessType.Admin); // Add gUsers[2] as an Member addAUserNoImpersonateNoRevert(gUsers[2], AccessType.Member); assertEq(dao.getUserCount(), 3); // Remove gUsers[2] as gUsers[1] who is an Admin removeAUserWithImpersonateNoRevert(gUsers[2], gUsers[1]); assertEq(dao.getUserCount(), 2); } function testRemoveUserMemberAsOfficer() public { // Add gUsers[1] as a Officer addAUserNoImpersonateNoRevert(gUsers[1], AccessType.Officer); // Add gUsers[2] as a Member addAUserNoImpersonateNoRevert(gUsers[2], AccessType.Member); assertEq(dao.getUserCount(), 3); // Remove gUsers[2] as gUsers[1] who is an Officer removeAUserWithImpersonateNoRevert(gUsers[2], gUsers[1]); assertEq(dao.getUserCount(), 2); } // ========================================= // Test removing Admin user via removeUser // ========================================= function testRemoveUserAdminAsOwner() public { // Add gUsers[1] as a Admin addAUserNoImpersonateNoRevert(gUsers[1], AccessType.Admin); assertEq(dao.getUserCount(), 2); // Remove gUsers[1] as owner removeAUserNoImpersonateNoRevert(gUsers[1]); assertEq(dao.getUserCount(), 1); } function testRemoveUserAdminAsMember() public { // Add gUsers[1] as a Member addAUserNoImpersonateNoRevert(gUsers[1], AccessType.Member); // Add gUsers[2] as an Admin addAUserNoImpersonateNoRevert(gUsers[2], AccessType.Admin); assertEq(dao.getUserCount(), 3); // Remove gUsers[2] as gUsers[1] who is a Member removeAUserWithImpersonateWithRevert(gUsers[2], gUsers[1], "Not authorized to remove"); assertEq(dao.getUserCount(), 3); } function testRemoveUserAdminAsAdmin() public { // Add gUsers[1] and gUsers[2] as Admins addAUserNoImpersonateNoRevert(gUsers[1], AccessType.Admin); addAUserNoImpersonateNoRevert(gUsers[2], AccessType.Admin); assertEq(dao.getUserCount(), 3); // Remove gUsers[2] as gUsers[1] who is an Admin removeAUserWithImpersonateNoRevert(gUsers[2], gUsers[1]); assertEq(dao.getUserCount(), 2); } function testRemoveUserAdminAsOfficer() public { // Add gUsers[1] as an Officer addAUserNoImpersonateNoRevert(gUsers[1], AccessType.Officer); // Add gUsers[2] as an Admin addAUserNoImpersonateNoRevert(gUsers[2], AccessType.Admin); assertEq(dao.getUserCount(), 3); // Remove gUsers[2] as gUsers[1] who is an Officer removeAUserWithImpersonateNoRevert(gUsers[2], gUsers[1]); assertEq(dao.getUserCount(), 2); } // ========================================= // Test removing Officer user via removeUser // ========================================= function testRemoveUserOfficerAsOwner() public { // Add gUsers[1] as a Officer addAUserNoImpersonateNoRevert(gUsers[1], AccessType.Officer); assertEq(dao.getUserCount(), 2); // Remove gUsers[1] as owner removeAUserNoImpersonateWithRevert(gUsers[1], CreateErorrCallData(gRemovalAuthIdentifier, uint256(AccessType.Admin), uint256(AccessType.Officer))); assertEq(dao.getUserCount(), 2); } function testRemoveUserOfficerAsMember() public { // Add gUsers[1] as a Member addAUserNoImpersonateNoRevert(gUsers[1], AccessType.Member); // Add gUsers[2] as an Officer addAUserNoImpersonateNoRevert(gUsers[2], AccessType.Officer); assertEq(dao.getUserCount(), 3); // Remove gUsers[2] as gUsers[1] who is a Member removeAUserWithImpersonateWithRevert(gUsers[2], gUsers[1], "Not authorized to remove"); assertEq(dao.getUserCount(), 3); } function testRemoveUserOfficerAsAdmin() public { // Add gUsers[1] as a Admin addAUserNoImpersonateNoRevert(gUsers[1], AccessType.Admin); // Add gUsers[2] as an Officer addAUserNoImpersonateNoRevert(gUsers[2], AccessType.Officer); assertEq(dao.getUserCount(), 3); // Remove gUsers[2] as gUsers[1] who is a Admin removeAUserWithImpersonateWithRevert(gUsers[2], gUsers[1], CreateErorrCallData(gRemovalAuthIdentifier, uint256(AccessType.Officer), uint256(AccessType.Officer))); assertEq(dao.getUserCount(), 3); } function testRemoveUserOfficerAsOfficer() public { // Add gUsers[1] and gUsers[2] as Officers addAUserNoImpersonateNoRevert(gUsers[1], AccessType.Officer); addAUserNoImpersonateNoRevert(gUsers[2], AccessType.Officer); assertEq(dao.getUserCount(), 3); // Remove gUsers[2] as gUsers[1] who is a Officer removeAUserWithImpersonateWithRevert(gUsers[2], gUsers[1], CreateErorrCallData(gRemovalAuthIdentifier, uint256(AccessType.Officer), uint256(AccessType.Officer))); assertEq(dao.getUserCount(), 3); } // ============================================ // Test removing Officer user via removeOfficer // ============================================ function testRemoveOfficerAsOwner() public { // Add gUsers[1] as an Officer addAUserNoImpersonateNoRevert(gUsers[1], AccessType.Officer); assertEq(dao.getUserCount(), 2); // Remove gUsers[1] as the owner removeAnOfficerNoImpersonateNoRevert(gUsers[1]); assertEq(dao.getUserCount(), 1); } function testRemoveOfficerAsMember() public { // Add gUsers[1] as an Member addAUserNoImpersonateNoRevert(gUsers[1], AccessType.Member); // Add gUsers[2] as an Officer addAUserNoImpersonateNoRevert(gUsers[2], AccessType.Officer); assertEq(dao.getUserCount(), 3); // Remove gUsers[2] as gUsers[1] who is a Member removeAnOfficerWithImpersonateWithRevert(gUsers[2], gUsers[1], "Only owner is allowed"); assertEq(dao.getUserCount(), 3); } function testRemoveOfficerAsAdmin() public { // Add gUsers[1] as an Admin addAUserNoImpersonateNoRevert(gUsers[1], AccessType.Admin); // Add gUsers[2] as an Officer addAUserNoImpersonateNoRevert(gUsers[2], AccessType.Officer); assertEq(dao.getUserCount(), 3); // Remove gUsers[2] as gUsers[1] who is an Admin removeAnOfficerWithImpersonateWithRevert(gUsers[2], gUsers[1], "Only owner is allowed"); assertEq(dao.getUserCount(), 3); } function testRemoveOfficerAsOfficer() public { // Add gUsers[1] and gUsers[2] as Officers addAUserNoImpersonateNoRevert(gUsers[1], AccessType.Officer); addAUserNoImpersonateNoRevert(gUsers[2], AccessType.Officer); assertEq(dao.getUserCount(), 3); // Remove gUsers[2] as gUsers[1] who is an Officer removeAnOfficerWithImpersonateWithRevert(gUsers[2], gUsers[1], "Only owner is allowed"); assertEq(dao.getUserCount(), 3); } // ========================== // Test Adding MaxUsers Users // ========================== function testAddMaxUsersAsMemberBatched() public { addMaxUsers(true, AccessType.Member, gBatchSize); } function testAddMaxUsersAsMemberNonBatched() public { addMaxUsers(false, AccessType.Member, gBatchSize); } function testAddMaxUsersAsAdminBatched() public { addMaxUsers(true, AccessType.Admin, gBatchSize); } function testAddMaxUsersAsAdminNonBatched() public { addMaxUsers(false, AccessType.Admin, gBatchSize); } function testAddMaxUsersAsOfficerBatched() public { addMaxUsers(true, AccessType.Officer, gBatchSize); } function testAddMaxUsersAsOfficerNonBatched() public { addMaxUsers(false, AccessType.Officer, gBatchSize); } // ============================ // Test Adding MaxUsers+1 Users // ============================ function testAddMaxUsersPlusAddMemberBatched() public { addMaxUsers(true, AccessType.Member, gBatchSize); addAUserNoImpersonateWithRevert(address(uint160(gMaxUsers+1)), AccessType.Member, "Max Users Exceeded"); } function testAddMaxUsersPlusAddMemberNonBatched() public { addMaxUsers(false, AccessType.Member, gBatchSize); addAUserNoImpersonateWithRevert(address(uint160(gMaxUsers+1)), AccessType.Member, "Max Users Exceeded"); } function testAddMaxUsersPlusAddAdminBatched() public { addMaxUsers(true, AccessType.Admin, gBatchSize); addAUserNoImpersonateWithRevert(address(uint160(gMaxUsers+1)), AccessType.Admin, "Max Users Exceeded"); } function testAddMaxUsersPlusAddAdminNonBatched() public { addMaxUsers(false, AccessType.Admin, gBatchSize); addAUserNoImpersonateWithRevert(address(uint160(gMaxUsers+1)), AccessType.Admin, "Max Users Exceeded"); } function testAddMaxUsersPlusAddOfficerBatched() public { addMaxUsers(true, AccessType.Officer, gBatchSize); addAUserNoImpersonateWithRevert(address(uint160(gMaxUsers+1)), AccessType.Officer, "Max Users Exceeded"); } function testAddMaxUsersPlusAddOfficerNonBatched() public { addMaxUsers(false, AccessType.Officer, gBatchSize); addAUserNoImpersonateWithRevert(address(uint160(gMaxUsers+1)), AccessType.Officer, "Max Users Exceeded"); } // =============================== // Test Adding a Member user twice // =============================== function testAddUserTwiceMemberAsOwner() public { // Add gUsers[1] as a Member addAUserNoImpersonateNoRevert(gUsers[1], AccessType.Member); assertEq(dao.getUserCount(), 2); // Try to add gUsers[1] again as a member addAUserNoImpersonateNoRevert(gUsers[1], AccessType.Member); assertEq(dao.getUserCount(), 2); } function testAddUserTwiceMemberAsMember() public { // Add gUsers[1] and gUsers[2] as Members addAUserNoImpersonateNoRevert(gUsers[1], AccessType.Member); addAUserNoImpersonateNoRevert(gUsers[2], AccessType.Member); assertEq(dao.getUserCount(), 3); // Have gUsers[1] try to add gUsers[2] again as a member addAUserWithImpersonateWithRevert(gUsers[2], AccessType.Member, gUsers[1], "Not authorized to grant"); assertEq(dao.getUserCount(), 3); } function testAddUserTwiceMemberAsAdmin() public { // Add gUsers[1] as an Admin addAUserNoImpersonateNoRevert(gUsers[1], AccessType.Admin); // Add gUsers[2] as a Member addAUserNoImpersonateNoRevert(gUsers[2], AccessType.Member); assertEq(dao.getUserCount(), 3); // Have gUsers[1] try to add gUsers[2] again as a member addAUserWithImpersonateNoRevert(gUsers[2], AccessType.Member, gUsers[1]); assertEq(dao.getUserCount(), 3); } function testAddUserTwiceMemberAsOfficer() public { // Add gUsers[1] as an Officer addAUserNoImpersonateNoRevert(gUsers[1], AccessType.Officer); // Add gUsers[2] as a Member addAUserNoImpersonateNoRevert(gUsers[2], AccessType.Member); assertEq(dao.getUserCount(), 3); // Have gUsers[1] try to add gUsers[2] again as a member addAUserWithImpersonateNoRevert(gUsers[2], AccessType.Member, gUsers[1]); assertEq(dao.getUserCount(), 3); } // =============================== // Test Adding an Admin user twice // =============================== function testAddUserTwiceAdminAsOwner() public { // Add gUsers[1] as an Admin addAUserNoImpersonateNoRevert(gUsers[1], AccessType.Admin); assertEq(dao.getUserCount(), 2); // Try to add gUsers[1] again as an Admin addAUserNoImpersonateNoRevert(gUsers[1], AccessType.Admin); assertEq(dao.getUserCount(), 2); } function testAddUserTwiceAdminAsMember() public { // Add gUsers[1] and gUsers[2] as Members addAUserNoImpersonateNoRevert(gUsers[1], AccessType.Member); addAUserNoImpersonateNoRevert(gUsers[2], AccessType.Admin); assertEq(dao.getUserCount(), 3); // Have gUsers[1] try to add gUsers[2] again as a member addAUserWithImpersonateWithRevert(gUsers[2], AccessType.Admin, gUsers[1], "Not authorized to grant"); assertEq(dao.getUserCount(), 3); } function testAddUserTwiceAdminAsAdmin() public { // Add gUsers[1] as an Admin addAUserNoImpersonateNoRevert(gUsers[1], AccessType.Admin); // Add gUsers[2] as an Admin addAUserNoImpersonateNoRevert(gUsers[2], AccessType.Admin); assertEq(dao.getUserCount(), 3); // Have gUsers[1] try to add gUsers[2] again as a Admin addAUserWithImpersonateNoRevert(gUsers[2], AccessType.Admin, gUsers[1]); assertEq(dao.getUserCount(), 3); } function testAddUserTwiceAdminAsOfficer() public { // Add gUsers[1] as an Officer addAUserNoImpersonateNoRevert(gUsers[1], AccessType.Officer); // Add gUsers[2] as a Admin addAUserNoImpersonateNoRevert(gUsers[2], AccessType.Admin); assertEq(dao.getUserCount(), 3); // Have gUsers[1] try to add gUsers[2] again as a Admin addAUserWithImpersonateNoRevert(gUsers[2], AccessType.Admin, gUsers[1]); assertEq(dao.getUserCount(), 3); } // ================================= // Test Adding an Officer user twice // ================================= function testAddUserTwiceOfficerAsOwner() public { // Add gUsers[1] as an Officer addAUserNoImpersonateNoRevert(gUsers[1], AccessType.Officer); assertEq(dao.getUserCount(), 2); // Try to add gUsers[1] again as an Officer addAUserNoImpersonateWithRevert(gUsers[1], AccessType.Officer, CreateErorrCallData(gAccessUpdateAuthIdentifier, uint256(AccessType.Admin), uint256(AccessType.Officer))); assertEq(dao.getUserCount(), 2); } function testAddUserTwiceOfficerAsMember() public { // Add gUsers[1] as a Member addAUserNoImpersonateNoRevert(gUsers[1], AccessType.Member); // Add gUsers[2] as an Officer addAUserNoImpersonateNoRevert(gUsers[2], AccessType.Officer); assertEq(dao.getUserCount(), 3); // Have gUsers[1] try to add gUsers[2] again as a Member addAUserWithImpersonateWithRevert(gUsers[2], AccessType.Officer, gUsers[1], "Not authorized to grant"); assertEq(dao.getUserCount(), 3); } function testAddUserTwiceOfficerAsAdmin() public { // Add gUsers[1] as an Admin addAUserNoImpersonateNoRevert(gUsers[1], AccessType.Admin); // Add gUsers[2] as an Officer addAUserNoImpersonateNoRevert(gUsers[2], AccessType.Officer); assertEq(dao.getUserCount(), 3); // Have gUsers[1] try to add gUsers[2] again as an Officer addAUserWithImpersonateWithRevert(gUsers[2], AccessType.Officer, gUsers[1], "Not authorized to grant"); assertEq(dao.getUserCount(), 3); } function testAddUserTwiceOfficerAsOfficer() public { // Add gUsers[1] as an Officer addAUserNoImpersonateNoRevert(gUsers[1], AccessType.Officer); // Add gUsers[2] as an Officer addAUserNoImpersonateNoRevert(gUsers[2], AccessType.Officer); assertEq(dao.getUserCount(), 3); // Have gUsers[1] try to add gUsers[2] again as an Officer addAUserWithImpersonateWithRevert(gUsers[2], AccessType.Officer, gUsers[1], CreateErorrCallData(gAccessUpdateAuthIdentifier, uint256(AccessType.Officer), uint256(AccessType.Officer))); assertEq(dao.getUserCount(), 3); } // ================================= // Test Removing a Member user twice // ================================= function testRemoveUserTwiceMemberAsOwner() public { // Add gUsers[1] as a Member addAUserNoImpersonateNoRevert(gUsers[1], AccessType.Member); assertEq(dao.getUserCount(), 2); // Remove gUsers[1] removeAUserNoImpersonateNoRevert(gUsers[1]); assertEq(dao.getUserCount(), 1); // Try again and expect failure removeAUserNoImpersonateWithRevert(gUsers[1], CreateErorrCallData(gNotUserIdentifier, uint256(AccessType.Admin))); assertEq(dao.getUserCount(), 1); } function testRemoveUserTwiceMemberAsAdmin() public { // Add gUsers[1] as an Admin addAUserNoImpersonateNoRevert(gUsers[1], AccessType.Admin); // Add gUsers[2] as a Member addAUserNoImpersonateNoRevert(gUsers[2], AccessType.Member); assertEq(dao.getUserCount(), 3); // Remove gUsers[2] as gUsers[1] who is an Admin removeAUserWithImpersonateNoRevert(gUsers[2], gUsers[1]); assertEq(dao.getUserCount(), 2); // Try again and expect failure removeAUserNoImpersonateWithRevert(gUsers[2], CreateErorrCallData(gNotUserIdentifier, uint256(AccessType.Officer))); assertEq(dao.getUserCount(), 2); } function testRemoveUserTwiceMemberAsOfficer() public { // Add gUsers[1] as an Officer addAUserNoImpersonateNoRevert(gUsers[1], AccessType.Officer); // Add gUsers[2] as a Member addAUserNoImpersonateNoRevert(gUsers[2], AccessType.Member); assertEq(dao.getUserCount(), 3); // Remove gUsers[2] as gUsers[1] who is an Officer removeAUserWithImpersonateNoRevert(gUsers[2], gUsers[1]); assertEq(dao.getUserCount(), 2); // Try again and expect failure removeAUserNoImpersonateWithRevert(gUsers[2], CreateErorrCallData(gNotUserIdentifier, uint256(AccessType.Officer))); assertEq(dao.getUserCount(), 2); } // ================================= // Test Removing an Admin user twice // ================================= function testRemoveUserTwiceAdminAsOwner() public { // Add gUsers[1] as a Admin addAUserNoImpersonateNoRevert(gUsers[1], AccessType.Admin); assertEq(dao.getUserCount(), 2); // Remove gUsers[1] removeAUserNoImpersonateNoRevert(gUsers[1]); assertEq(dao.getUserCount(), 1); // Try again and expect failure removeAUserNoImpersonateWithRevert(gUsers[1], CreateErorrCallData(gNotUserIdentifier, uint256(AccessType.Admin))); assertEq(dao.getUserCount(), 1); } function testRemoveUserTwiceAdminAsOfficer() public { // Add gUsers[1] as an Officer addAUserNoImpersonateNoRevert(gUsers[1], AccessType.Officer); // Add gUsers[2] as an Admin addAUserNoImpersonateNoRevert(gUsers[2], AccessType.Admin); assertEq(dao.getUserCount(), 3); // Remove gUsers[2] as gUsers[1] who is an Officer removeAUserWithImpersonateNoRevert(gUsers[2], gUsers[1]); assertEq(dao.getUserCount(), 2); // Try again and expect failure removeAUserNoImpersonateWithRevert(gUsers[2], CreateErorrCallData(gNotUserIdentifier, uint256(AccessType.Officer))); assertEq(dao.getUserCount(), 2); } // =================================== // Test Removing an Officer user twice // =================================== function testRemoveOfficerTwiceAsOwner() public { // Add gUsers[1] as a Officer addAUserNoImpersonateNoRevert(gUsers[1], AccessType.Officer); assertEq(dao.getUserCount(), 2); // Remove gUsers[1] removeAnOfficerNoImpersonateNoRevert(gUsers[1]); assertEq(dao.getUserCount(), 1); // Try again and expect failure removeAnOfficerNoImpersonateWithRevert(gUsers[1], "Not an officer"); assertEq(dao.getUserCount(), 1); } // ============================== // Test Removing users in batches // ============================== function testRemoveUsersBatched() public { for(uint i = 0; i < gUsers.length; i++){ addAUserNoImpersonateNoRevert(gUsers[i], AccessType.Member); } assertEq(dao.getUserCount(), 10); removeUsersNoImpersonateNoRevert(gUsers); assertEq(dao.getUserCount(), 1); } function testRemoveUsersBatchedNonExistingUser() public { address[] memory copy = new address[](gUsers.length); for(uint i = 0; i < gUsers.length; i++){ addAUserNoImpersonateNoRevert(gUsers[i], AccessType.Member); copy[i] = gUsers[i]; } assertEq(dao.getUserCount(), 10); copy[4] = address(0x12345); removeUsersNoImpersonateWithRevert(copy, CreateErorrCallData(gNotUserIdentifier, uint256(uint160(copy[4])))); assertEq(dao.getUserCount(), 10); copy[4] = gUsers[4]; copy[0] = address(0x12345); removeUsersNoImpersonateWithRevert(copy, CreateErorrCallData(gNotUserIdentifier, uint256(uint160(copy[0])))); assertEq(dao.getUserCount(), 10); copy[0] = gUsers[0]; copy[gUsers.length-1] = address(0x12345); removeUsersNoImpersonateWithRevert(copy, CreateErorrCallData(gNotUserIdentifier, uint256(uint160(copy[gUsers.length-1])))); assertEq(dao.getUserCount(), 10); } // ================================================= // Test sending/receiving funds to/from the contract // ================================================= function testDeposit() public { assertEq(dao.getBalance(), 0); payable(address(dao)).transfer(1); assertEq(dao.getBalance(), 1); payable(address(dao)).transfer(10); assertEq(dao.getBalance(), 11); } function testWithdrawl() public { assertEq(dao.getBalance(), 0); payable(address(dao)).transfer(10); uint256 bal_before = address(this).balance; dao.transferHbar(payable(address(this)), 1); assertEq(bal_before, address(this).balance - 1); } function testWithdrawlRevert() public { assertEq(dao.getBalance(), 0); cheats.expectRevert(""); dao.transferHbar(payable(address(this)), 1); } // ================================ // Test promoting a Member to Admin // ================================ function testPromoteMemberToAdminAsMember() public { // Add gUsers[1] as a Member addAUserNoImpersonateNoRevert(gUsers[1], AccessType.Member); // Add gUsers[2] as a Member addAUserNoImpersonateNoRevert(gUsers[2], AccessType.Member); assertEq(dao.getUserCount(), 3); // Promote gUsers[2] to Admin as gUsers[1] who is a Member addAUserWithImpersonateWithRevert(gUsers[2], AccessType.Admin, gUsers[1], "Not authorized to grant"); assertEq(dao.getUserCount(), 3); } function testPromoteMemberToAdminAsAdmin() public { // Add gUsers[1] as an Admin addAUserNoImpersonateNoRevert(gUsers[1], AccessType.Admin); // Add gUsers[2] as a Member addAUserNoImpersonateNoRevert(gUsers[2], AccessType.Member); assertEq(dao.getUserCount(), 3); // Promote gUsers[2] to Admin as gUsers[1] who is an Admin addAUserWithImpersonateNoRevert(gUsers[2], AccessType.Admin, gUsers[1]); assertEq(dao.getUserCount(), 3); } function testPromoteMemberToAdminAsOfficer() public { // Add gUsers[1] as an Officer addAUserNoImpersonateNoRevert(gUsers[1], AccessType.Officer); // Add gUsers[2] as a Member addAUserNoImpersonateNoRevert(gUsers[2], AccessType.Member); assertEq(dao.getUserCount(), 3); // Promote gUsers[2] to Admin as gUsers[1] who is an Officer addAUserWithImpersonateNoRevert(gUsers[2], AccessType.Admin, gUsers[1]); assertEq(dao.getUserCount(), 3); } // ================================== // Test promoting a Member to Officer // ================================== function testPromoteMemberToOfficerAsMember() public { // Add gUsers[1] as a Member addAUserNoImpersonateNoRevert(gUsers[1], AccessType.Member); // Add gUsers[2] as a Member addAUserNoImpersonateNoRevert(gUsers[2], AccessType.Member); assertEq(dao.getUserCount(), 3); // Promote gUsers[2] to Officer as gUsers[1] who is a Member addAUserWithImpersonateWithRevert(gUsers[2], AccessType.Officer, gUsers[1], "Not authorized to grant"); assertEq(dao.getUserCount(), 3); } function testPromoteMemberToOfficerAsAdmin() public { // Add gUsers[1] as an Admin addAUserNoImpersonateNoRevert(gUsers[1], AccessType.Admin); // Add gUsers[2] as a Member addAUserNoImpersonateNoRevert(gUsers[2], AccessType.Member); assertEq(dao.getUserCount(), 3); // Promote gUsers[2] to Officer as gUsers[1] who is an Admin addAUserWithImpersonateWithRevert(gUsers[2], AccessType.Officer, gUsers[1], "Not authorized to grant"); assertEq(dao.getUserCount(), 3); } function testPromoteMemberToOfficerAsOfficer() public { // Add gUsers[1] as an Officer addAUserNoImpersonateNoRevert(gUsers[1], AccessType.Officer); // Add gUsers[2] as a Member addAUserNoImpersonateNoRevert(gUsers[2], AccessType.Member); assertEq(dao.getUserCount(), 3); // Promote gUsers[2] to Officer as gUsers[1] who is an Officer addAUserWithImpersonateNoRevert(gUsers[2], AccessType.Officer, gUsers[1]); assertEq(dao.getUserCount(), 3); } // ================================== // Test promoting an Admin to Officer // ================================== function testPromoteAdminToOfficerAsMember() public { // Add gUsers[1] as a Member addAUserNoImpersonateNoRevert(gUsers[1], AccessType.Member); // Add gUsers[2] as an Admin addAUserNoImpersonateNoRevert(gUsers[2], AccessType.Admin); assertEq(dao.getUserCount(), 3); // Promote gUsers[2] to Officer as gUsers[1] who is a Member addAUserWithImpersonateWithRevert(gUsers[2], AccessType.Officer, gUsers[1], "Not authorized to grant"); assertEq(dao.getUserCount(), 3); } function testPromoteAdminToOfficerAsAdmin() public { // Add gUsers[1] as an Admin addAUserNoImpersonateNoRevert(gUsers[1], AccessType.Admin); // Add gUsers[2] as an Admin addAUserNoImpersonateNoRevert(gUsers[2], AccessType.Admin); assertEq(dao.getUserCount(), 3); // Promote gUsers[2] to Officer as gUsers[1] who is an Admin addAUserWithImpersonateWithRevert(gUsers[2], AccessType.Officer, gUsers[1], "Not authorized to grant"); assertEq(dao.getUserCount(), 3); } function testPromoteAdminToOfficerAsOfficer() public { // Add gUsers[1] as an Officer addAUserNoImpersonateNoRevert(gUsers[1], AccessType.Officer); // Add gUsers[2] as an Admin addAUserNoImpersonateNoRevert(gUsers[2], AccessType.Admin); assertEq(dao.getUserCount(), 3); // Promote gUsers[2] to Officer as gUsers[1] who is a Member addAUserWithImpersonateNoRevert(gUsers[2], AccessType.Officer, gUsers[1]); assertEq(dao.getUserCount(), 3); } // ================================= // Test demoting an Officer to Amdin // ================================= function testDemoteOfficerToAdminAsMember() public { // Add gUsers[1] as a Member addAUserNoImpersonateNoRevert(gUsers[1], AccessType.Member); // Add gUsers[2] as an Officer addAUserNoImpersonateNoRevert(gUsers[2], AccessType.Officer); assertEq(dao.getUserCount(), 3); // Demote gUsers[2] to Admin as gUsers[1] who is a Member addAUserWithImpersonateWithRevert(gUsers[2], AccessType.Admin, gUsers[1], "Not authorized to grant"); assertEq(dao.getUserCount(), 3); } function testDemoteOfficerToAdminAsAdmin() public { // Add gUsers[1] as an Admin addAUserNoImpersonateNoRevert(gUsers[1], AccessType.Admin); // Add gUsers[2] as an Officer addAUserNoImpersonateNoRevert(gUsers[2], AccessType.Officer); assertEq(dao.getUserCount(), 3); // Demote gUsers[2] to Admin as gUsers[1] who is an Admin addAUserWithImpersonateWithRevert(gUsers[2], AccessType.Admin, gUsers[1], CreateErorrCallData(gAccessUpdateAuthIdentifier, uint256(AccessType.Officer), uint256(AccessType.Officer))); assertEq(dao.getUserCount(), 3); } function testDemoteOfficerToAdminAsOfficer() public { // Add gUsers[1] as an Officer addAUserNoImpersonateNoRevert(gUsers[1], AccessType.Officer); // Add gUsers[2] as an Officer addAUserNoImpersonateNoRevert(gUsers[2], AccessType.Officer); assertEq(dao.getUserCount(), 3); // Demote gUsers[2] to Admin as gUsers[1] who is an Officer addAUserWithImpersonateWithRevert(gUsers[2], AccessType.Admin, gUsers[1], CreateErorrCallData(gAccessUpdateAuthIdentifier, uint256(AccessType.Officer), uint256(AccessType.Officer))); assertEq(dao.getUserCount(), 3); } // ================================== // Test demoting an Officer to Member // ================================== function testDemoteOfficerToMemberAsMember() public { // Add gUsers[1] as a Member addAUserNoImpersonateNoRevert(gUsers[1], AccessType.Member); // Add gUsers[2] as an Officer addAUserNoImpersonateNoRevert(gUsers[2], AccessType.Officer); assertEq(dao.getUserCount(), 3); // Demote gUsers[2] to Member as gUsers[1] who is a Member addAUserWithImpersonateWithRevert(gUsers[2], AccessType.Member, gUsers[1], "Not authorized to grant"); assertEq(dao.getUserCount(), 3); } function testDemoteOfficerToMemberAsAdmin() public { // Add gUsers[1] as an Admin addAUserNoImpersonateNoRevert(gUsers[1], AccessType.Admin); // Add gUsers[2] as an Officer addAUserNoImpersonateNoRevert(gUsers[2], AccessType.Officer); assertEq(dao.getUserCount(), 3); // Demote gUsers[2] to Member as gUsers[1] who is an Admin addAUserWithImpersonateWithRevert(gUsers[2], AccessType.Member, gUsers[1], CreateErorrCallData(gAccessUpdateAuthIdentifier, uint256(AccessType.Officer), uint256(AccessType.Officer))); assertEq(dao.getUserCount(), 3); } function testDemoteOfficerToMemberAsOfficer() public { // Add gUsers[1] as an Officer addAUserNoImpersonateNoRevert(gUsers[1], AccessType.Officer); // Add gUsers[2] as an Officer addAUserNoImpersonateNoRevert(gUsers[2], AccessType.Officer); assertEq(dao.getUserCount(), 3); // Demote gUsers[2] to Member as gUsers[1] who is an Officer addAUserWithImpersonateWithRevert(gUsers[2], AccessType.Member, gUsers[1], CreateErorrCallData(gAccessUpdateAuthIdentifier, uint256(AccessType.Officer), uint256(AccessType.Officer))); assertEq(dao.getUserCount(), 3); } // ================================ // Test demoting an Admin to Member // ================================ function testDemoteAdminToMemberAsMember() public { // Add gUsers[1] as a Member addAUserNoImpersonateNoRevert(gUsers[1], AccessType.Member); // Add gUsers[2] as an Admin addAUserNoImpersonateNoRevert(gUsers[2], AccessType.Admin); assertEq(dao.getUserCount(), 3); // Demote gUsers[2] to Member as gUsers[1] who is a Member addAUserWithImpersonateWithRevert(gUsers[2], AccessType.Member, gUsers[1], "Not authorized to grant"); assertEq(dao.getUserCount(), 3); } function testDemoteAdminToMemberAsAdmin() public { // Add gUsers[1] as an Admin addAUserNoImpersonateNoRevert(gUsers[1], AccessType.Admin); // Add gUsers[2] as an Admin addAUserNoImpersonateNoRevert(gUsers[2], AccessType.Admin); assertEq(dao.getUserCount(), 3); // Demote gUsers[2] to Member as gUsers[1] who is an Admin addAUserWithImpersonateNoRevert(gUsers[2], AccessType.Member, gUsers[1]); assertEq(dao.getUserCount(), 3); } function testDemoteAdminToMemberAsOfficer() public { // Add gUsers[1] as an Officer addAUserNoImpersonateNoRevert(gUsers[1], AccessType.Officer); // Add gUsers[2] as an Admin addAUserNoImpersonateNoRevert(gUsers[2], AccessType.Admin); assertEq(dao.getUserCount(), 3); // Demote gUsers[2] to Member as gUsers[1] who is an Officer addAUserWithImpersonateNoRevert(gUsers[2], AccessType.Member, gUsers[1]); assertEq(dao.getUserCount(), 3); } }
Add gUsers[1] as an Member Have gUsers[1] try to add gUsers[2] as an Admin
function testAddUserAdminAsMember() public { addAUserNoImpersonateNoRevert(gUsers[1], AccessType.Member); assertEq(dao.getUserCount(), 2); addAUserWithImpersonateWithRevert(gUsers[2], AccessType.Admin, gUsers[1], "Not authorized to grant"); assertEq(dao.getUserCount(), 2); }
14,053,764
./full_match/1/0xc0a7838017C8f0fC9fe0f0D9c164a9e28F9EF446/sources/contracts/platform/vesting/PlatformVesting.sol
Only platform admin can do amount Target removal liquidity amount Amount will be transfer to sender wallet/
function decreaseLiquidity(uint256 amount) external onlyPlatformAdmin { if(amount == 0) revert ZeroAmount(); uint256 availableSenderBalance = IERC20(_token).balanceOf(address(this)); if(amount > availableSenderBalance) revert InsufficientBalance(); if(totalRemainingAllocatedAmount > availableSenderBalance) revert FatalError("balance less than allocated amount"); uint256 availableBalance = availableSenderBalance - totalRemainingAllocatedAmount; if(amount > availableBalance) revert InsufficientBalance(); address admin = msgSender(); IERC20(_token).safeTransfer(admin, amount); emit DecreaseLiquidity(admin, amount); }
3,011,766
pragma solidity 0.6.12; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/utils/ReentrancyGuard.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; contract StakingPool is Ownable, ReentrancyGuard { using SafeMath for uint256; using SafeERC20 for IERC20; bool public allowReinvest; IERC20 public stakingToken; IERC20 public rewardToken; uint256 public startTime; uint256 public lastRewardTime; uint256 public finishTime; uint256 public allStakedAmount; uint256 public allPaidReward; uint256 public allRewardDebt; uint256 public poolTokenAmount; uint256 public rewardPerSec; uint256 public accTokensPerShare; // Accumulated tokens per share uint256 public participants; //Count of participants // Info of each user. struct UserInfo { uint256 amount; // How many tokens the user has staked. uint256 rewardDebt; // Reward debt bool registrated; } mapping (address => UserInfo) public userInfo; event PoolReplenished(uint256 amount); event TokensStaked(address indexed user, uint256 amount, uint256 reward, bool reinvest); event StakeWithdrawn(address indexed user, uint256 amount, uint256 reward); event EmergencyWithdraw(address indexed user, uint256 amount); event WithdrawPoolRemainder(address indexed user, uint256 amount); event UpdateFinishTime(uint256 addedTokenAmount, uint256 newFinishTime); constructor( IERC20 _stakingToken, IERC20 _poolToken, uint256 _startTime, uint256 _finishTime, uint256 _poolTokenAmount ) public { stakingToken = _stakingToken; rewardToken = _poolToken; require(_startTime < _finishTime, "Start must be less than finish"); require(_startTime > now, "Start must be more than now"); startTime = _startTime; lastRewardTime = startTime; finishTime = _finishTime; poolTokenAmount = _poolTokenAmount; rewardPerSec = _poolTokenAmount.div(_finishTime.sub(_startTime)); allowReinvest = address(stakingToken) == address(rewardToken); } function getUserInfo(address user) external view returns (uint256, uint256) { UserInfo memory info = userInfo[user]; return (info.amount, info.rewardDebt); } function getMultiplier(uint256 _from, uint256 _to) internal view returns (uint256) { if (_from >= _to) { return 0; } if (_to <= finishTime) { return _to.sub(_from); } else if (_from >= finishTime) { return 0; } else { return finishTime.sub(_from); } } // View function to see pending Reward on frontend. function pendingReward(address _user) external view returns (uint256) { UserInfo storage user = userInfo[_user]; uint256 tempAccTokensPerShare = accTokensPerShare; if (now > lastRewardTime && allStakedAmount != 0) { uint256 multiplier = getMultiplier(lastRewardTime, now); uint256 reward = multiplier.mul(rewardPerSec); tempAccTokensPerShare = accTokensPerShare.add( reward.mul(1e18).div(allStakedAmount) ); } return user.amount.mul(tempAccTokensPerShare).div(1e18).sub(user.rewardDebt); } // Update reward variables of the given pool to be up-to-date. function updatePool() public { if (now <= lastRewardTime) { return; } if (allStakedAmount == 0) { lastRewardTime = now; return; } uint256 multiplier = getMultiplier(lastRewardTime, now); uint256 reward = multiplier.mul(rewardPerSec); accTokensPerShare = accTokensPerShare.add( reward.mul(1e18).div(allStakedAmount) ); lastRewardTime = now; } function reinvestTokens() external nonReentrant{ innerStakeTokens(0, true); } function stakeTokens(uint256 _amountToStake) external nonReentrant{ innerStakeTokens(_amountToStake, false); } function innerStakeTokens(uint256 _amountToStake, bool reinvest) private{ updatePool(); uint256 pending = 0; UserInfo storage user = userInfo[msg.sender]; if(!user.registrated){ user.registrated = true; participants +=1; } if (user.amount > 0) { pending = transferPendingReward(user, reinvest); if(reinvest) { require(allowReinvest, "Reinvest disabled"); user.amount = user.amount.add(pending); allStakedAmount = allStakedAmount.add(pending); } } if (_amountToStake > 0) { uint256 balanceBefore = stakingToken.balanceOf(address(this)); stakingToken.safeTransferFrom(msg.sender, address(this), _amountToStake); uint256 received = stakingToken.balanceOf(address(this)) - balanceBefore; _amountToStake = received; user.amount = user.amount.add(_amountToStake); allStakedAmount = allStakedAmount.add(_amountToStake); } allRewardDebt = allRewardDebt.sub(user.rewardDebt); user.rewardDebt = user.amount.mul(accTokensPerShare).div(1e18); allRewardDebt = allRewardDebt.add(user.rewardDebt); emit TokensStaked(msg.sender, _amountToStake, pending, reinvest); } // Leave the pool. Claim back your tokens. // Unclocks the staked + gained tokens and burns pool shares function withdrawStake(uint256 _amount) external nonReentrant { UserInfo storage user = userInfo[msg.sender]; require(user.amount >= _amount, "withdraw: not good"); updatePool(); uint256 pending = transferPendingReward(user, false); if (_amount > 0) { user.amount = user.amount.sub(_amount); stakingToken.safeTransfer(msg.sender, _amount); } allRewardDebt = allRewardDebt.sub(user.rewardDebt); user.rewardDebt = user.amount.mul(accTokensPerShare).div(1e18); allRewardDebt = allRewardDebt.add(user.rewardDebt); allStakedAmount = allStakedAmount.sub(_amount); emit StakeWithdrawn(msg.sender, _amount, pending); } function transferPendingReward(UserInfo memory user, bool reinvest) private returns (uint256) { uint256 pending = user.amount.mul(accTokensPerShare).div(1e18).sub(user.rewardDebt); if (pending > 0) { if(!reinvest){ rewardToken.safeTransfer(msg.sender, pending); } allPaidReward = allPaidReward.add(pending); } return pending; } // Withdraw without caring about rewards. EMERGENCY ONLY. function emergencyWithdraw() external nonReentrant{ UserInfo storage user = userInfo[msg.sender]; if(user.amount > 0) { stakingToken.safeTransfer(msg.sender, user.amount); emit EmergencyWithdraw(msg.sender, user.amount); allStakedAmount = allStakedAmount.sub(user.amount); allRewardDebt = allRewardDebt.sub(user.rewardDebt); user.amount = 0; user.rewardDebt = 0; } } function withdrawPoolRemainder() external onlyOwner nonReentrant{ require(now > finishTime, "Allow after finish"); updatePool(); uint256 pending = allStakedAmount.mul(accTokensPerShare).div(1e18).sub(allRewardDebt); uint256 returnAmount = poolTokenAmount.sub(allPaidReward).sub(pending); allPaidReward = allPaidReward.add(returnAmount); rewardToken.safeTransfer(msg.sender, returnAmount); emit WithdrawPoolRemainder(msg.sender, returnAmount); } function extendDuration(uint256 _addTokenAmount) external onlyOwner nonReentrant{ require(now < finishTime, "Pool was finished"); rewardToken.safeTransferFrom(msg.sender, address(this), _addTokenAmount); poolTokenAmount = poolTokenAmount.add(_addTokenAmount); finishTime = finishTime.add(_addTokenAmount.div(rewardPerSec)); emit UpdateFinishTime(_addTokenAmount, finishTime); } }
Withdraw without caring about rewards. EMERGENCY ONLY.
function emergencyWithdraw() external nonReentrant{ UserInfo storage user = userInfo[msg.sender]; if(user.amount > 0) { stakingToken.safeTransfer(msg.sender, user.amount); emit EmergencyWithdraw(msg.sender, user.amount); allStakedAmount = allStakedAmount.sub(user.amount); allRewardDebt = allRewardDebt.sub(user.rewardDebt); user.amount = 0; user.rewardDebt = 0; } }
12,992,628
./partial_match/3/0x6cc9b43f81C40E3BB3Fe544472F2653EE539E75C/sources/MyLotto.sol
Internal function for checking values for purchaseTicket
function getNumber(uint256 _number) internal returns(uint256){ return _number.div(6); }
5,278,786
// SPDX-License-Identifier: MIT pragma solidity 0.6.12; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "@openzeppelin/contracts/utils/EnumerableSet.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; import "./YFBitcoin.sol"; import "./UniswapV2Pair.sol"; contract YFBTCMaster is Ownable { using SafeMath for *; using SafeERC20 for IERC20; // Info of each user. struct UserInfo { uint256 amount; uint256 rewardDebt; } // Info of each pool. struct PoolInfo { IERC20 lpToken; // Address of LP token contract. uint256 lastRewardBlock; uint256 accYfbtcPerShare; // Accumulated YFBTC per share, times 1e12. See below. uint256 totalSupply; } struct RewardInfo { uint256 startBlock; uint256 endBlock; uint256 rewardFrom; uint256 rewardTo; uint256 rewardPerBlock; } uint256 public lastPrice = 0; uint256 public constant PERIOD = 24 hours; uint256 public constant CHANGE_IN_PERCENTAGE = 5; // hold factory address that will be used to fetch pair address address public pairAddress; // block time of last update uint32 public blockTimestampLast; // The YFBTC TOKEN! YFBitcoin public yfbtc; // Info of each pool. PoolInfo[] public poolInfo; //info of reward pools RewardInfo[] public rewardInfo; // Info of each user that stakes LP tokens. mapping(uint256 => mapping(address => UserInfo)) public userInfo; // The block number when YFBTC mining starts. uint256 public startedBlock; event SetDevAddress(address indexed _devAddress); event SetTransferFee(uint256 _fee); event Deposit(address indexed user, uint256 indexed pid, uint256 amount); event Withdraw(address indexed user, uint256 indexed pid, uint256 amount); event EmergencyWithdraw(address indexed user, uint256 indexed pid, uint256 amount); event EmergencyWithdrawExceptional(address indexed user, uint256 amount); constructor( YFBitcoin _yfbtc, address _pairAddress, uint256 _startedBlock ) public { yfbtc = _yfbtc; pairAddress = _pairAddress; startedBlock = _startedBlock; (uint112 reserve0, uint112 reserve1, uint32 blockTime) = UniswapV2Pair(pairAddress).getReserves(); // gas savings blockTimestampLast = blockTime; lastPrice = reserve1; require(reserve0 != 0 && reserve1 != 0, "ORACLE: NO_RESERVES"); // ensure that there's liquidity in the pair addRewardSet(); } function currentBlockTimestamp() internal view returns (uint32) { return uint32(block.timestamp % 2**32); } function setDevAddress(address _devAddress) external onlyOwner { require(_devAddress != address(0x0), "zero address is not allowed"); yfbtc.setDevAddress(_devAddress); emit SetDevAddress(_devAddress); } function setTransferFee(uint256 _fee) external onlyOwner { require(_fee > 0 && _fee < 1000, "YFBTC: fee should be between 0 and 10"); yfbtc.setTransferFee(_fee); emit SetTransferFee(_fee); } function mint(address _to, uint256 _amount) public onlyOwner { yfbtc.mint(_to, _amount); } function burn(address _sender, uint256 _amount) public onlyOwner { yfbtc.burn(_sender, _amount); } function update() public returns (bool) { uint32 blockTimestamp = currentBlockTimestamp(); uint32 timeElapsed = blockTimestamp - blockTimestampLast; // overflow is desired // ensure that at least one full period has passed since the last update if (timeElapsed >= PERIOD) { uint256 change = 0; (, uint112 _reserve1, ) = UniswapV2Pair(pairAddress).getReserves(); // gas savings uint256 currentPrice = _reserve1; if (lastPrice > currentPrice) { change = lastPrice.sub(currentPrice).mul(100).div(lastPrice); } if (change >= CHANGE_IN_PERCENTAGE) { return false; } else { lastPrice = currentPrice; blockTimestampLast = blockTimestamp; } } return true; } function updateOwnerShip(address newOwner) public onlyOwner { yfbtc.transferOwnership(newOwner); } function poolLength() external view returns (uint256) { return poolInfo.length; } // Add a new lp to the pool. Can only be called by the owner. // XXX DO NOT add the same LP token more than once. Rewards will be messed up if you do. function add(IERC20 _lpToken) external onlyOwner { //EDIT commenting lastRewardBlock per pool (it is now common for all pools) //uint256 lastRewardBlock = block.number > startBlock ? block.number : startBlock; require(address(_lpToken) != address(0), "MC: _lpToken should not be address zero"); for (uint256 i = 0; i < poolInfo.length; i++) { require(address(poolInfo[i].lpToken) != address(_lpToken), "MC: DO NOT add the same LP token more than once"); } uint256 lastRewardBlock = block.number > startedBlock ? block.number : startedBlock; poolInfo.push(PoolInfo({lpToken: _lpToken, accYfbtcPerShare: 0, lastRewardBlock: lastRewardBlock, totalSupply: 0})); } function addRewardSet() internal returns (uint256) { rewardInfo.push( RewardInfo({ startBlock: startedBlock, endBlock: startedBlock.add(172800), rewardFrom: 1900 * 10**18, rewardTo: 3150 * 10**18, rewardPerBlock: 17606095680000000 }) ); rewardInfo.push( RewardInfo({ startBlock: startedBlock.add(172800), endBlock: startedBlock.add(1036800), rewardFrom: 3150 * 10**18, rewardTo: 8960 * 10**18, rewardPerBlock: 8641975309000000 }) ); rewardInfo.push( RewardInfo({ startBlock: startedBlock.add(1036800), endBlock: startedBlock.add(2073600), rewardFrom: 8960 * 10**18, rewardTo: 16590 * 10**18, rewardPerBlock: 4320987654000000 }) ); rewardInfo.push( RewardInfo({ startBlock: startedBlock.add(2073600), endBlock: startedBlock.add(3110400), rewardFrom: 16590 * 10**18, rewardTo: 18830 * 10**18, rewardPerBlock: 2160493827000000 }) ); rewardInfo.push( RewardInfo({ startBlock: startedBlock.add(3110400), endBlock: startedBlock.add(4147200), rewardFrom: 18830 * 10**18, rewardTo: 19950 * 10**18, rewardPerBlock: 1080246914000000 }) ); rewardInfo.push( RewardInfo({ startBlock: startedBlock.add(4147200), endBlock: startedBlock.add(5184000), rewardFrom: 19950 * 10**18, rewardTo: 20510 * 10**18, rewardPerBlock: 540123456800000 }) ); rewardInfo.push( RewardInfo({ startBlock: startedBlock.add(5184000), endBlock: startedBlock.add(6220800), rewardFrom: 20510 * 10**18, rewardTo: 20790 * 10**18, rewardPerBlock: 270061728400000 }) ); rewardInfo.push( RewardInfo({ startBlock: startedBlock.add(6220800), endBlock: startedBlock.add(7257600), rewardFrom: 20790 * 10**18, rewardTo: 20930 * 10**18, rewardPerBlock: 135030864200000 }) ); rewardInfo.push( RewardInfo({ startBlock: startedBlock.add(7257600), endBlock: startedBlock.add(8294400), rewardFrom: 20930 * 10**18, rewardTo: 21000 * 10**18, rewardPerBlock: 67515432100000 }) ); return 0; } function getPoolBaseMultiplier(uint256 _pid) public view returns (uint256) { if (_pid == 0) { return 20; } else if (_pid == 1) { return 4; } else if (_pid == 2) { return 1; } else { return 1; } } // Return reward multiplier over the given _from to _to block. function getMultiplier(uint256 _from, uint256 _to) public view returns (uint256) { uint256 difference = _to.sub(_from); if (difference <= 0 || _from < startedBlock) return 0; uint256 totalReward = 0; uint256 supply = yfbtc.totalSupply(); if (supply >= rewardInfo[rewardInfo.length.sub(1)].rewardTo) return 0; uint256 rewardSetlength = rewardInfo.length; if (_to >= rewardInfo[rewardInfo.length.sub(1)].endBlock) { totalReward = _to.sub(_from).mul(rewardInfo[3].rewardPerBlock); } else { for (uint256 rid = 0; rid < rewardSetlength; ++rid) { // if (supply >= rewardInfo[rid].rewardFrom) { if (_to <= rewardInfo[rid].endBlock) { totalReward = totalReward.add(((_to.sub(_from)).mul(rewardInfo[rid].rewardPerBlock))); break; } else { if (rewardInfo[rid].endBlock <= _from) { continue; } totalReward = totalReward.add(((rewardInfo[rid].endBlock.sub(_from)).mul(rewardInfo[rid].rewardPerBlock))); supply = rewardInfo[rid].rewardTo; _from = rewardInfo[rid].endBlock; } // } } } uint256 totalMultipliers = sumOfMultipliers(); if (totalMultipliers == 0) return 0; uint256 rewardPerPool = totalReward.div(totalMultipliers); return rewardPerPool; } // View function to see pending YFBTC on frontend. function pendingReward(uint256 _pid, address _user) external view returns (uint256) { PoolInfo memory pool = poolInfo[_pid]; require(address(pool.lpToken) != address(0), "MC: _pid is incorrect"); UserInfo memory user = userInfo[_pid][_user]; uint256 accYfbtcPerShare = pool.accYfbtcPerShare; uint256 lpSupply = pool.lpToken.balanceOf(address(this)); if (block.number > pool.lastRewardBlock && lpSupply != 0) { uint256 rewardPerPool = getMultiplier(pool.lastRewardBlock, block.number); accYfbtcPerShare = accYfbtcPerShare.add(rewardPerPool.mul(getPoolBaseMultiplier(_pid)).mul(1e12).div(lpSupply)); } return user.amount.mul(accYfbtcPerShare).div(1e12).sub(user.rewardDebt); } function estimateReward( uint256 _pid, address _user, uint256 to ) external view returns (uint256) { PoolInfo memory pool = poolInfo[_pid]; require(address(pool.lpToken) != address(0), "MC: _pid is incorrect"); UserInfo memory user = userInfo[_pid][_user]; uint256 accYfbtcPerShare = pool.accYfbtcPerShare; uint256 lpSupply = pool.lpToken.balanceOf(address(this)); if (block.number > pool.lastRewardBlock && lpSupply != 0) { uint256 rewardPerPool = getMultiplier(pool.lastRewardBlock, to); accYfbtcPerShare = accYfbtcPerShare.add(rewardPerPool.mul(getPoolBaseMultiplier(_pid)).mul(1e12).div(lpSupply)); } return user.amount.mul(accYfbtcPerShare).div(1e12).sub(user.rewardDebt); } function sumOfMultipliers() internal view returns (uint256) { uint256 eligibleMultipliers = 0; uint256 length = poolInfo.length; // Reward will only be assign to pools when they the staked balance is > 0 for (uint256 pid = 0; pid < length; ++pid) { if (poolInfo[pid].totalSupply > 0) { eligibleMultipliers = eligibleMultipliers.add(getPoolBaseMultiplier(pid)); } } return eligibleMultipliers; } // Update reward variables of the given pool to be up-to-date. function updatePool(uint256 _pid) public { PoolInfo storage pool = poolInfo[_pid]; require(address(pool.lpToken) != address(0), "MC: _pid is incorrect"); if (block.number <= pool.lastRewardBlock) { return; } uint256 lpSupply = pool.lpToken.balanceOf(address(this)); if (lpSupply == 0) { pool.lastRewardBlock = block.number; return; } bool doMint = update(); if (doMint) { uint256 yfbtcReward = getMultiplier(pool.lastRewardBlock, block.number); if (yfbtcReward <= 0) return; yfbtcReward = yfbtcReward.mul(getPoolBaseMultiplier(_pid)); pool.accYfbtcPerShare = pool.accYfbtcPerShare.add(yfbtcReward.mul(1e12).div(lpSupply)); yfbtc.mint(address(this), yfbtcReward); pool.lastRewardBlock = block.number; } } // Deposit LP tokens to MasterChef for YFBTC allocation. function deposit(uint256 _pid, uint256 _amount) external { PoolInfo storage pool = poolInfo[_pid]; require(address(pool.lpToken) != address(0), "MC: _pid is incorrect"); UserInfo storage user = userInfo[_pid][msg.sender]; updatePool(_pid); if (user.amount > 0) { uint256 pending = user.amount.mul(pool.accYfbtcPerShare).div(1e12).sub(user.rewardDebt); if (pending > 0) { safeYfbtcTransfer(msg.sender, pending); } } if (_amount > 0) { pool.lpToken.safeTransferFrom(address(msg.sender), address(this), _amount); pool.totalSupply = pool.totalSupply.add(_amount); user.amount = user.amount.add(_amount); } user.rewardDebt = user.amount.mul(pool.accYfbtcPerShare).div(1e12); emit Deposit(msg.sender, _pid, _amount); } // Withdraw LP tokens from MasterChef. function withdraw(uint256 _pid, uint256 _amount) external { PoolInfo storage pool = poolInfo[_pid]; require(address(pool.lpToken) != address(0), "MC: _pid is incorrect"); UserInfo storage user = userInfo[_pid][msg.sender]; require(user.amount >= _amount, "withdraw: not good"); updatePool(_pid); uint256 pending = user.amount.mul(pool.accYfbtcPerShare).div(1e12).sub(user.rewardDebt); if (pending > 0) { safeYfbtcTransfer(msg.sender, pending); } if (_amount > 0) { user.amount = user.amount.sub(_amount); pool.lpToken.safeTransfer(address(msg.sender), _amount); pool.totalSupply = pool.totalSupply.sub(_amount); } user.rewardDebt = user.amount.mul(pool.accYfbtcPerShare).div(1e12); emit Withdraw(msg.sender, _pid, _amount); } // let user exist in case of emergency function emergencyWithdraw(uint256 _pid) public { PoolInfo storage pool = poolInfo[_pid]; require(address(pool.lpToken) != address(0), "MC: _pid is incorrect"); UserInfo storage user = userInfo[_pid][msg.sender]; uint256 amount = user.amount; user.amount = 0; user.rewardDebt = 0; pool.lpToken.safeTransfer(address(msg.sender), amount); pool.totalSupply = pool.totalSupply.sub(amount); emit EmergencyWithdraw(msg.sender, _pid, amount); } // Safe yfbtcReward transfer function, just in case if rounding error causes pool to not have enough YFBTC. function safeYfbtcTransfer(address _to, uint256 _amount) internal { uint256 yfbtcBal = yfbtc.balanceOf(address(this)); if (_amount > yfbtcBal) { yfbtc.transfer(_to, yfbtcBal); emit EmergencyWithdrawExceptional(_to, _amount); } else { yfbtc.transfer(_to, _amount); } } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "./IERC20.sol"; import "../../math/SafeMath.sol"; import "../../utils/Address.sol"; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using SafeMath for uint256; using Address for address; function safeTransfer(IERC20 token, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove(IERC20 token, address spender, uint256 value) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' // solhint-disable-next-line max-line-length require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).add(value); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero"); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Library for managing * https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive * types. * * Sets have the following properties: * * - Elements are added, removed, and checked for existence in constant time * (O(1)). * - Elements are enumerated in O(n). No guarantees are made on the ordering. * * ``` * contract Example { * // Add the library methods * using EnumerableSet for EnumerableSet.AddressSet; * * // Declare a set state variable * EnumerableSet.AddressSet private mySet; * } * ``` * * As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`) * and `uint256` (`UintSet`) are supported. */ library EnumerableSet { // To implement this library for multiple types with as little code // repetition as possible, we write it in terms of a generic Set type with // bytes32 values. // The Set implementation uses private functions, and user-facing // implementations (such as AddressSet) are just wrappers around the // underlying Set. // This means that we can only create new EnumerableSets for types that fit // in bytes32. struct Set { // Storage of set values bytes32[] _values; // Position of the value in the `values` array, plus 1 because index 0 // means a value is not in the set. mapping (bytes32 => uint256) _indexes; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function _add(Set storage set, bytes32 value) private returns (bool) { if (!_contains(set, value)) { set._values.push(value); // The value is stored at length-1, but we add 1 to all indexes // and use 0 as a sentinel value set._indexes[value] = set._values.length; return true; } else { return false; } } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function _remove(Set storage set, bytes32 value) private returns (bool) { // We read and store the value's index to prevent multiple reads from the same storage slot uint256 valueIndex = set._indexes[value]; if (valueIndex != 0) { // Equivalent to contains(set, value) // To delete an element from the _values array in O(1), we swap the element to delete with the last one in // the array, and then remove the last element (sometimes called as 'swap and pop'). // This modifies the order of the array, as noted in {at}. uint256 toDeleteIndex = valueIndex - 1; uint256 lastIndex = set._values.length - 1; // When the value to delete is the last one, the swap operation is unnecessary. However, since this occurs // so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement. bytes32 lastvalue = set._values[lastIndex]; // Move the last value to the index where the value to delete is set._values[toDeleteIndex] = lastvalue; // Update the index for the moved value set._indexes[lastvalue] = toDeleteIndex + 1; // All indexes are 1-based // Delete the slot where the moved value was stored set._values.pop(); // Delete the index for the deleted slot delete set._indexes[value]; return true; } else { return false; } } /** * @dev Returns true if the value is in the set. O(1). */ function _contains(Set storage set, bytes32 value) private view returns (bool) { return set._indexes[value] != 0; } /** * @dev Returns the number of values on the set. O(1). */ function _length(Set storage set) private view returns (uint256) { return set._values.length; } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function _at(Set storage set, uint256 index) private view returns (bytes32) { require(set._values.length > index, "EnumerableSet: index out of bounds"); return set._values[index]; } // Bytes32Set struct Bytes32Set { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _add(set._inner, value); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _remove(set._inner, value); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) { return _contains(set._inner, value); } /** * @dev Returns the number of values in the set. O(1). */ function length(Bytes32Set storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) { return _at(set._inner, index); } // AddressSet struct AddressSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(AddressSet storage set, address value) internal returns (bool) { return _add(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(AddressSet storage set, address value) internal returns (bool) { return _remove(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(AddressSet storage set, address value) internal view returns (bool) { return _contains(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Returns the number of values in the set. O(1). */ function length(AddressSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(AddressSet storage set, uint256 index) internal view returns (address) { return address(uint160(uint256(_at(set._inner, index)))); } // UintSet struct UintSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(UintSet storage set, uint256 value) internal returns (bool) { return _add(set._inner, bytes32(value)); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(UintSet storage set, uint256 value) internal returns (bool) { return _remove(set._inner, bytes32(value)); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(UintSet storage set, uint256 value) internal view returns (bool) { return _contains(set._inner, bytes32(value)); } /** * @dev Returns the number of values on the set. O(1). */ function length(UintSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(UintSet storage set, uint256 index) internal view returns (uint256) { return uint256(_at(set._inner, index)); } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b > a) return (false, 0); return (true, a - b); } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a / b); } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a % b); } /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a, "SafeMath: subtraction overflow"); return a - b; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) return 0; uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers, reverting on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: division by zero"); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: modulo by zero"); return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); return a - b; } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryDiv}. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a % b; } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "../utils/Context.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor () internal { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } pragma solidity 0.6.12; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "@openzeppelin/contracts/utils/EnumerableSet.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; import "./ERC20.sol"; // YFEToken with Governance. // YFEToken with Governance. contract YFBitcoin is ERC20("AddToken", "ADD"), Ownable { uint256 public transferFee = 1; uint256 public devFee = 300; address public devAddress; uint256 public cap; constructor(uint256 _cap, address _devAddress) public { cap = _cap; devAddress = _devAddress; } function setTransferFee(uint256 _fee) public onlyOwner { require(_fee > 0 && _fee < 1000, "YFBTC: fee should be between 0 and 10"); transferFee = _fee; } function setDevAddress(address _devAddress) public onlyOwner { devAddress = _devAddress; } function burn(address sender, uint256 amount) public onlyOwner { _burn(sender, amount); } /// @notice Creates `_amount` token to `_to`. Must only be called by the owner (MasterChef). function mint(address _to, uint256 _amount) public onlyOwner { _mint(_to, _amount); _moveDelegates(address(0), _delegates[_to], _amount); } function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); _moveDelegates(_delegates[msg.sender], _delegates[recipient], amount); return true; } function transferFrom( address sender, address recipient, uint256 amount ) public virtual override returns (bool) { uint256 allowedAmount = allowance(sender, _msgSender()); _transfer(sender, recipient, amount); _moveDelegates(_delegates[sender], _delegates[recipient], amount); _approve(sender, _msgSender(), allowedAmount.sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } // Copied and modified from YAM code: // https://github.com/yam-finance/yam-protocol/blob/master/contracts/token/YAMGovernanceStorage.sol // https://github.com/yam-finance/yam-protocol/blob/master/contracts/token/YAMGovernance.sol // Which is copied and modified from COMPOUND: // https://github.com/compound-finance/compound-protocol/blob/master/contracts/Governance/Comp.sol mapping(address => address) internal _delegates; /// @notice A checkpoint for marking number of votes from a given block struct Checkpoint { uint32 fromBlock; uint256 votes; } /// @notice A record of votes checkpoints for each account, by index mapping(address => mapping(uint32 => Checkpoint)) public checkpoints; /// @notice The number of checkpoints for each account mapping(address => uint32) public numCheckpoints; /// @notice The EIP-712 typehash for the contract's domain bytes32 public constant DOMAIN_TYPEHASH = keccak256("EIP712Domain(string name,uint256 chainId,address verifyingContract)"); /// @notice The EIP-712 typehash for the delegation struct used by the contract bytes32 public constant DELEGATION_TYPEHASH = keccak256("Delegation(address delegatee,uint256 nonce,uint256 expiry)"); /// @notice A record of states for signing / validating signatures mapping(address => uint256) public nonces; /// @notice An event thats emitted when an account changes its delegate event DelegateChanged(address indexed delegator, address indexed fromDelegate, address indexed toDelegate); /// @notice An event thats emitted when a delegate account's vote balance changes event DelegateVotesChanged(address indexed delegate, uint256 previousBalance, uint256 newBalance); /** * @notice Delegate votes from `msg.sender` to `delegatee` * @param delegator The address to get delegatee for */ function delegates(address delegator) external view returns (address) { return _delegates[delegator]; } /** * @notice Delegate votes from `msg.sender` to `delegatee` * @param delegatee The address to delegate votes to */ function delegate(address delegatee) external { return _delegate(msg.sender, delegatee); } /** * @notice Delegates votes from signatory to `delegatee` * @param delegatee The address to delegate votes to * @param nonce The contract state required to match the signature * @param expiry The time at which to expire the signature * @param v The recovery byte of the signature * @param r Half of the ECDSA signature pair * @param s Half of the ECDSA signature pair */ function delegateBySig( address delegatee, uint256 nonce, uint256 expiry, uint8 v, bytes32 r, bytes32 s ) external { bytes32 domainSeparator = keccak256(abi.encode(DOMAIN_TYPEHASH, keccak256(bytes(name())), getChainId(), address(this))); bytes32 structHash = keccak256(abi.encode(DELEGATION_TYPEHASH, delegatee, nonce, expiry)); bytes32 digest = keccak256(abi.encodePacked("\x19\x01", domainSeparator, structHash)); address signatory = ecrecover(digest, v, r, s); require(signatory != address(0), "YFBTC::delegateBySig: invalid signature"); require(nonce == nonces[signatory]++, "YFBTC::delegateBySig: invalid nonce"); require(now <= expiry, "YFBTC::delegateBySig: signature expired"); return _delegate(signatory, delegatee); } /** * @notice Gets the current votes balance for `account` * @param account The address to get votes balance * @return The number of current votes for `account` */ function getCurrentVotes(address account) external view returns (uint256) { uint32 nCheckpoints = numCheckpoints[account]; return nCheckpoints > 0 ? checkpoints[account][nCheckpoints - 1].votes : 0; } /** * @notice Determine the prior number of votes for an account as of a block number * @dev Block number must be a finalized block or else this function will revert to prevent misinformation. * @param account The address of the account to check * @param blockNumber The block number to get the vote balance at * @return The number of votes the account had as of the given block */ function getPriorVotes(address account, uint256 blockNumber) external view returns (uint256) { require(blockNumber < block.number, "YFBTC::getPriorVotes: not yet determined"); uint32 nCheckpoints = numCheckpoints[account]; if (nCheckpoints == 0) { return 0; } // First check most recent balance if (checkpoints[account][nCheckpoints - 1].fromBlock <= blockNumber) { return checkpoints[account][nCheckpoints - 1].votes; } // Next check implicit zero balance if (checkpoints[account][0].fromBlock > blockNumber) { return 0; } uint32 lower = 0; uint32 upper = nCheckpoints - 1; while (upper > lower) { uint32 center = upper - (upper - lower) / 2; // ceil, avoiding overflow Checkpoint memory cp = checkpoints[account][center]; if (cp.fromBlock == blockNumber) { return cp.votes; } else if (cp.fromBlock < blockNumber) { lower = center; } else { upper = center - 1; } } return checkpoints[account][lower].votes; } function _delegate(address delegator, address delegatee) internal { address currentDelegate = _delegates[delegator]; uint256 delegatorBalance = balanceOf(delegator); // balance of underlying YFEs (not scaled); _delegates[delegator] = delegatee; emit DelegateChanged(delegator, currentDelegate, delegatee); _moveDelegates(currentDelegate, delegatee, delegatorBalance); } function _moveDelegates( address srcRep, address dstRep, uint256 amount ) internal { if (srcRep != dstRep && amount > 0) { if (srcRep != address(0)) { // decrease old representative uint32 srcRepNum = numCheckpoints[srcRep]; uint256 srcRepOld = srcRepNum > 0 ? checkpoints[srcRep][srcRepNum - 1].votes : 0; uint256 srcRepNew = srcRepOld.sub(amount); _writeCheckpoint(srcRep, srcRepNum, srcRepOld, srcRepNew); } if (dstRep != address(0)) { // increase new representative uint32 dstRepNum = numCheckpoints[dstRep]; uint256 dstRepOld = dstRepNum > 0 ? checkpoints[dstRep][dstRepNum - 1].votes : 0; uint256 dstRepNew = dstRepOld.add(amount); _writeCheckpoint(dstRep, dstRepNum, dstRepOld, dstRepNew); } } } function _writeCheckpoint( address delegatee, uint32 nCheckpoints, uint256 oldVotes, uint256 newVotes ) internal { uint32 blockNumber = safe32(block.number, "YFBTC::_writeCheckpoint: block number exceeds 32 bits"); if (nCheckpoints > 0 && checkpoints[delegatee][nCheckpoints - 1].fromBlock == blockNumber) { checkpoints[delegatee][nCheckpoints - 1].votes = newVotes; } else { checkpoints[delegatee][nCheckpoints] = Checkpoint(blockNumber, newVotes); numCheckpoints[delegatee] = nCheckpoints + 1; } emit DelegateVotesChanged(delegatee, oldVotes, newVotes); } function safe32(uint256 n, string memory errorMessage) internal pure returns (uint32) { require(n < 2**32, errorMessage); return uint32(n); } function getChainId() internal pure returns (uint256) { uint256 chainId; assembly { chainId := chainid() } return chainId; } /** * @dev See {ERC20-_beforeTokenTransfer}. * * Requirements: * * - minted tokens must not cause the total supply to go over the cap. */ function _beforeTokenTransfer( address from, address to, uint256 amount ) internal virtual override { super._beforeTokenTransfer(from, to, amount); if (from == address(0)) { // When minting tokens require(totalSupply().add(amount) <= cap, "YFBTC:: cap exceeded"); } } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; interface UniswapV2Pair{ function getReserves() external view returns (uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast); function price0CumulativeLast() external view returns (uint); function price1CumulativeLast() external view returns (uint); } // SPDX-License-Identifier: MIT pragma solidity >=0.6.2 <0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: value }(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.delegatecall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } pragma solidity ^0.6.0; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "@openzeppelin/contracts/utils/EnumerableSet.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; contract ERC20 is Context, IERC20 { using SafeMath for uint256; using Address for address; mapping(address => uint256) private _balances; mapping(address => mapping(address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; uint8 private _decimals; /** * @dev Sets the values for {name} and {symbol}, initializes {decimals} with * a default value of 18. * * To select a different value for {decimals}, use {_setupDecimals}. * * All three of these values are immutable: they can only be set once during * construction. */ constructor(string memory name, string memory symbol) public { _name = name; _symbol = symbol; _decimals = 18; } /** * @dev Returns the name of the token. */ function name() public view returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is * called. * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view returns (uint8) { return _decimals; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}; * * Requirements: * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom( address sender, address recipient, uint256 amount ) public virtual override returns (bool) { _transfer(sender, recipient, amount); _approve( sender, _msgSender(), _allowances[sender][_msgSender()].sub( amount, "ERC20: transfer amount exceeds allowance" ) ); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve( _msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue) ); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { _approve( _msgSender(), spender, _allowances[_msgSender()][spender].sub( subtractedValue, "ERC20: decreased allowance below zero" ) ); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer( address sender, address recipient, uint256 amount ) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); _balances[sender] = _balances[sender].sub( amount, "ERC20: transfer amount exceeds balance" ); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements * * - `to` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); _balances[account] = _balances[account].sub( amount, "ERC20: burn amount exceeds balance" ); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens. * * This internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve( address owner, address spender, uint256 amount ) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Sets {decimals} to a value other than the default one of 18. * * WARNING: This function should only be called from the constructor. Most * applications that interact with token contracts will not expect * {decimals} to ever change, and may work incorrectly if it does. */ function _setupDecimals(uint8 decimals_) internal { _decimals = decimals_; } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be to transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 amount ) internal virtual {} }
Deposit LP tokens to MasterChef for YFBTC allocation.
function deposit(uint256 _pid, uint256 _amount) external { PoolInfo storage pool = poolInfo[_pid]; require(address(pool.lpToken) != address(0), "MC: _pid is incorrect"); UserInfo storage user = userInfo[_pid][msg.sender]; updatePool(_pid); if (user.amount > 0) { uint256 pending = user.amount.mul(pool.accYfbtcPerShare).div(1e12).sub(user.rewardDebt); if (pending > 0) { safeYfbtcTransfer(msg.sender, pending); } } if (_amount > 0) { pool.lpToken.safeTransferFrom(address(msg.sender), address(this), _amount); pool.totalSupply = pool.totalSupply.add(_amount); user.amount = user.amount.add(_amount); } user.rewardDebt = user.amount.mul(pool.accYfbtcPerShare).div(1e12); emit Deposit(msg.sender, _pid, _amount); }
10,076,981
./partial_match/1/0x0429D0A028D6A8a6Ea50eAaCfe1137bB30156E9d/sources/TradeAccounting.sol
Returns Synthetix synth symbol for asset currently held in TokenSet (e.g., sETH for WETH) xSNX contract complex only compatible with Sets that hold a single asset at a time/
function getActiveAssetSynthSymbol() internal view returns (bytes32 synthSymbol) { synthSymbol = getAssetCurrentlyActiveInSet() == setComponentAddresses[0] ? (synthSymbols[0]) : (synthSymbols[1]); }
2,670,670
// SPDX-License-Identifier: MIT pragma solidity ^0.8.4; /** * @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; } } /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } /** * @dev Interface for the optional metadata functions from the ERC20 standard. * * _Available since v4.1._ */ interface IERC20Metadata is IERC20 { /** * @dev Returns the name of the token. */ function name() external view returns (string memory); /** * @dev Returns the symbol of the token. */ function symbol() external view returns (string memory); /** * @dev Returns the decimals places of the token. */ function decimals() external view returns (uint8); } /** * @dev 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 {} } /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() { _setOwner(_msgSender()); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { _setOwner(address(0)); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); _setOwner(newOwner); } function _setOwner(address newOwner) private { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } } /** * @dev 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)); } } /** * @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); } } } } /** * @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"); } } } // helper methods for interacting with ERC20 tokens and sending ETH that do not consistently return true/false library TransferHelper { function safeApprove(address token, address to, uint value) internal { // bytes4(keccak256(bytes('approve(address,uint256)'))); (bool success, bytes memory data) = token.call(abi.encodeWithSelector(0x095ea7b3, to, value)); require(success && (data.length == 0 || abi.decode(data, (bool))), 'TransferHelper: APPROVE_FAILED'); } function safeTransfer(address token, address to, uint value) internal { // bytes4(keccak256(bytes('transfer(address,uint256)'))); (bool success, bytes memory data) = token.call(abi.encodeWithSelector(0xa9059cbb, to, value)); require(success && (data.length == 0 || abi.decode(data, (bool))), 'TransferHelper: TRANSFER_FAILED'); } function safeTransferFrom(address token, address from, address to, uint value) internal { // bytes4(keccak256(bytes('transferFrom(address,address,uint256)'))); (bool success, bytes memory data) = token.call(abi.encodeWithSelector(0x23b872dd, from, to, value)); require(success && (data.length == 0 || abi.decode(data, (bool))), 'TransferHelper: TRANSFER_FROM_FAILED'); } function safeTransferNative(address to, uint value) internal { (bool success,) = to.call{value:value}(new bytes(0)); require(success, 'TransferHelper: Native_TRANSFER_FAILED'); } } /** * @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)); } } /** * @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); } } contract StakingPool is Ownable { using SafeMath for uint256; using SafeERC20 for IERC20; using EnumerableSet for EnumerableSet.AddressSet; EnumerableSet.AddressSet private _governors; struct UserInfo { uint256 amount; uint256 rewardDebt; uint256 lockAmount; uint256 releaseAmount; } struct PoolInfo { IERC20 lpToken; IERC20 rewardToken; uint256 timeStart; uint256 timeEnd; // bonus tokens for per second. uint256 bonusPerSecond; uint256 lockedSeconds; //after exit stake ,need lock time uint256 lpAmount; uint256 lastRewardTime; uint256 accBonusPerShare; uint256 lpTokenType; //0 indicate normal token, 1 is xtoken IERC20 lpTokenFrom; bool open; //pool status } // Info of each pool. PoolInfo[] public poolInfo; // Info of each user that stakes LP tokens. mapping(uint256 => mapping(address => UserInfo)) public userInfo; struct WithdrawOrder { uint256 orderTime; uint256 amount; } mapping(uint256 => mapping(address => WithdrawOrder[])) public userWithdrawInfo; event Deposit(address indexed user, uint256 indexed pid, address token, uint256 amount); event Withdraw(address indexed user, uint256 indexed pid, address token, uint256 amount); event WithdrawUnlock(address indexed user, uint256 indexed pid, address token, uint256 amount); event EmergencyWithdraw(address indexed user, uint256 indexed pid, uint256 amount); event GovernorAdded( address _user); event GovernorDeleted( address _user); bytes32 constant public STAKINGPOOL_CALL_HASH_TYPE = keccak256("withdrawExit(address receiver,uint256 pid,uint256 exitAmount)"); /** * @dev Constructor. */ constructor(){ } function poolLength() external view returns (uint256) { return poolInfo.length; } function getLockLength(uint256 _pid, address _user) public view returns (uint256) { return userWithdrawInfo[_pid][_user].length; } // Add a new staking pool to the pool. Can only be called by the owner. function add( IERC20 _lpToken,IERC20 _rewardToken, uint256 _timeStart, uint256 _timeEnd , uint256 _bonusPerSecond,uint256 _lockedSeconds, uint256 _lpTokenType, IERC20 _lpTokenFrom , bool _open) public onlyGovernor { require( _timeStart > block.timestamp && _timeEnd > _timeStart, "invalid time limit"); poolInfo.push(PoolInfo({ lpToken : _lpToken, rewardToken : _rewardToken, timeStart : _timeStart, timeEnd : _timeEnd, bonusPerSecond : _bonusPerSecond, lockedSeconds : _lockedSeconds, lpAmount : 0, lastRewardTime : _timeStart, accBonusPerShare :0, lpTokenType :_lpTokenType, lpTokenFrom : _lpTokenFrom, open : _open })); //need transfer staking bonus token uint256 _amount = _timeEnd.sub(_timeStart).mul(_bonusPerSecond); TransferHelper.safeTransferFrom( address(_rewardToken), msg.sender, address(this), _amount); } // set staking pool info, only can adjust time where pool is not start harvest. function setPoolInfo( uint256 _pid, uint256 _timeStart, uint256 _timeEnd , uint256 _bonusPerSecond,uint256 _lockedSeconds, uint256 _lpTokenType, IERC20 _lpTokenFrom , bool _open) public onlyGovernor { require( _timeStart > block.timestamp && _timeEnd > _timeStart, "invalid time limit"); PoolInfo storage pool = poolInfo[_pid]; require( pool.timeStart > block.timestamp, "staking is enabled"); require( block.timestamp < pool.timeStart, "pool is mining"); //reward token uint256 _newAmount = _timeEnd.sub(_timeStart).mul(_bonusPerSecond); uint256 _amount = pool.timeEnd.sub(pool.timeStart).mul(pool.bonusPerSecond); if( _newAmount > _amount){ TransferHelper.safeTransferFrom( address(pool.rewardToken), msg.sender, address(this), _newAmount.sub(_amount)); } else if( _newAmount < _amount){ TransferHelper.safeTransfer( address(pool.rewardToken), msg.sender , _amount.sub(_newAmount) ); } pool.timeStart = _timeStart; pool.lastRewardTime = _timeStart; pool.timeEnd = _timeEnd; pool.bonusPerSecond = _bonusPerSecond; pool.lockedSeconds = _lockedSeconds; pool.lpTokenType = _lpTokenType; pool.lpTokenFrom = _lpTokenFrom; pool.open = _open; } //update pool status function setPoolStatus( uint256 _pid, bool _open) public onlyGovernor { PoolInfo storage pool = poolInfo[_pid]; pool.open = _open; } // Update reward variables of the given pool to be up-to-date. function updatePool(uint256 _pid) public { PoolInfo storage pool = poolInfo[_pid]; uint256 number = block.timestamp ; if (number <= pool.lastRewardTime) { return; } if( pool.lastRewardTime >= pool.timeEnd){ return; } //set the end time if( number >= pool.timeEnd ){ number = pool.timeEnd; } uint256 lpSupply = pool.lpAmount; if (lpSupply == 0) { pool.lastRewardTime = number; return; } uint256 multiplier = number.sub(pool.lastRewardTime); uint256 bonusReward = multiplier.mul(pool.bonusPerSecond); pool.accBonusPerShare = pool.accBonusPerShare.add(bonusReward.mul(1e12).div(lpSupply)); pool.lastRewardTime = number; } function pending(uint256 _pid, address _user) external view returns (uint256) { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][_user]; uint256 accBonusPerShare = pool.accBonusPerShare; uint256 lpSupply = pool.lpAmount; uint256 number = block.timestamp; if( number <= pool.timeStart ){ return 0; } if( number > pool.timeEnd ){ number = pool.timeEnd; } if (number > pool.lastRewardTime && lpSupply != 0) { uint256 multiplier = number.sub(pool.lastRewardTime); uint256 bonusReward = multiplier.mul(pool.bonusPerSecond) ; accBonusPerShare = accBonusPerShare.add(bonusReward.mul(1e12).div(lpSupply)); } return user.amount.mul(accBonusPerShare).div(1e12).sub(user.rewardDebt); } // Deposit LP tokens dividends bonus; function deposit(uint256 _pid, uint256 _amount) public { PoolInfo storage pool = poolInfo[_pid]; require( pool.open == true , "pool is closed!"); UserInfo storage user = userInfo[_pid][msg.sender]; updatePool(_pid); if (user.amount > 0) { uint256 pendingAmount = user.amount.mul(pool.accBonusPerShare).div(1e12).sub(user.rewardDebt); if (pendingAmount > 0) { TransferHelper.safeTransfer( address(pool.rewardToken), msg.sender , pendingAmount ); } } if (_amount > 0) { pool.lpToken.safeTransferFrom(address(msg.sender), address(this), _amount); user.amount = user.amount.add(_amount); pool.lpAmount = pool.lpAmount.add(_amount); } user.rewardDebt = user.amount.mul(pool.accBonusPerShare).div(1e12); emit Deposit(msg.sender, _pid, address(pool.lpToken), _amount); } // Withdraw LP tokens. function withdraw(uint256 _pid, uint256 _amount) public { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; require(user.amount >= _amount, "withdraw: not good"); updatePool(_pid); uint256 pendingAmount = user.amount.mul(pool.accBonusPerShare).div(1e12).sub(user.rewardDebt); if (pendingAmount > 0) { TransferHelper.safeTransfer( address(pool.rewardToken), msg.sender , pendingAmount ); } if (_amount > 0 ) { if( pool.lockedSeconds == 0 ){ user.amount = user.amount.sub(_amount); pool.lpAmount = pool.lpAmount.sub(_amount); pool.lpToken.safeTransfer(address(msg.sender), _amount); } else{ user.lockAmount = user.lockAmount.add(_amount); userWithdrawInfo[_pid][msg.sender].push(WithdrawOrder({orderTime: block.timestamp, amount: _amount})); } } user.rewardDebt = user.amount.mul(pool.accBonusPerShare).div(1e12); emit Withdraw(msg.sender, _pid, address(pool.lpToken), _amount); } //unlock lp token function pendingUnlock(uint256 _pid, address _user) external view returns (uint256) { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][_user]; uint256 unlockAmount = 0; uint256 checkTime = block.timestamp; if( user.lockAmount > 0 && pool.lockedSeconds > 0){ WithdrawOrder[] memory orders = userWithdrawInfo[_pid][_user]; uint256 len = orders.length; for (uint256 i = 0; i < len; i++) { if( orders[i].orderTime.add(pool.lockedSeconds) <= checkTime ){ unlockAmount = unlockAmount.add( orders[i].amount); } else{ break;//withdraw orders sorted by ordertime asc } } } return unlockAmount; } //withdraw unlock lp function withdrawUnlock(uint256 _pid) public { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; require(pool.lockedSeconds > 0 , "invalid pool"); updatePool(_pid); uint256 unlockAmount = 0; uint256 checkTime = block.timestamp; uint256 index = 0; if( user.lockAmount > 0 && pool.lockedSeconds > 0){ WithdrawOrder[] memory orders = userWithdrawInfo[_pid][msg.sender]; uint256 len = orders.length; if( len > 0 ){ index = len ; for (uint256 i = 0; i < len; i++) { if( orders[i].orderTime.add(pool.lockedSeconds) <= checkTime ){ unlockAmount = unlockAmount.add( orders[i].amount); } else{ index = i; break; } } //pop some orders for (uint256 i = 0; i < len - index; i++) { userWithdrawInfo[_pid][msg.sender][i] = userWithdrawInfo[_pid][msg.sender][i + index]; } for (uint256 j = len -index; j < len ; j++) { userWithdrawInfo[_pid][msg.sender].pop(); } } } uint256 pendingAmount = user.amount.mul(pool.accBonusPerShare).div(1e12).sub(user.rewardDebt); if (pendingAmount > 0) { TransferHelper.safeTransfer( address(pool.rewardToken), msg.sender , pendingAmount ); } if (unlockAmount > 0 ) { user.amount = user.amount.sub(unlockAmount); user.lockAmount = user.lockAmount.sub(unlockAmount); user.releaseAmount = user.releaseAmount.add( unlockAmount ); pool.lpAmount = pool.lpAmount.sub(unlockAmount); pool.lpToken.safeTransfer(address(msg.sender), unlockAmount); } user.rewardDebt = user.amount.mul(pool.accBonusPerShare).div(1e12); emit WithdrawUnlock(msg.sender, _pid, address(pool.lpToken), unlockAmount); } // Withdraw without caring about rewards. EMERGENCY ONLY. function emergencyWithdraw(uint256 _pid) public { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; uint256 amount = user.amount; if( amount > 0 && pool.lockedSeconds == 0 ){ user.amount = 0; user.rewardDebt = 0; pool.lpToken.safeTransfer(address(msg.sender), amount); } emit EmergencyWithdraw(msg.sender, _pid, amount); } //emergency withdraw function withdrawEmergency(address tokenaddress,address to) public onlyOwner{ TransferHelper.safeTransfer( tokenaddress, to , IERC20(tokenaddress).balanceOf(address(this))); } function withdrawEmergencyNative(address to , uint256 amount) public onlyOwner{ TransferHelper.safeTransferNative(to, amount); } //governor function addGovernor(address _governor) public onlyOwner returns (bool) { require(_governor != address(0), "_governor is the zero address"); emit GovernorAdded( _governor ); return EnumerableSet.add(_governors, _governor); } function delGovernor(address _governor) public onlyOwner returns (bool) { require(_governor != address(0), "_governor is the zero address"); emit GovernorDeleted( _governor ); return EnumerableSet.remove(_governors, _governor); } function getGovernorLength() public view returns (uint256) { return EnumerableSet.length(_governors); } function isGovernor(address account) public view returns (bool) { return EnumerableSet.contains(_governors, account); } function getGovernor(uint256 _index) public view returns (address){ require(_index <= getGovernorLength() - 1, "index out of bounds"); return EnumerableSet.at(_governors, _index); } // modifier for governor function modifier onlyGovernor() { require(isGovernor(msg.sender) || owner() == msg.sender , "caller is not the governor"); _; } }
Update reward variables of the given pool to be up-to-date.set the end time
function updatePool(uint256 _pid) public { PoolInfo storage pool = poolInfo[_pid]; uint256 number = block.timestamp ; if (number <= pool.lastRewardTime) { return; } if( pool.lastRewardTime >= pool.timeEnd){ return; } if( number >= pool.timeEnd ){ number = pool.timeEnd; } uint256 lpSupply = pool.lpAmount; if (lpSupply == 0) { pool.lastRewardTime = number; return; } uint256 multiplier = number.sub(pool.lastRewardTime); uint256 bonusReward = multiplier.mul(pool.bonusPerSecond); pool.accBonusPerShare = pool.accBonusPerShare.add(bonusReward.mul(1e12).div(lpSupply)); pool.lastRewardTime = number; }
1,287,513
pragma solidity ^0.4.18; /** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */ contract Ownable { address public owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ function Ownable() public { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) public onlyOwner { require(newOwner != address(0)); OwnershipTransferred(owner, newOwner); owner = newOwner; } } /** * @title ERC20Basic */ contract ERC20Basic { function totalSupply() public view returns (uint256); function balanceOf(address who) public view returns (uint256); function transfer(address to, uint256 value) public returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); } /** * @title ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/20 */ contract ERC20 is ERC20Basic { function allowance(address owner, address spender) public view returns (uint256); function transferFrom(address from, address to, uint256 value) public returns (bool); function approve(address spender, uint256 value) public returns (bool); event Approval(address indexed owner, address indexed spender, uint256 value); } /** * @title 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&#39;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; } } /** * @title Basic token */ contract BasicToken is ERC20Basic { using SafeMath for uint256; mapping(address => uint256) balances; uint256 totalSupply_; /** * @dev total number of tokens in existence */ function totalSupply() public view returns (uint256) { return totalSupply_; } /** * @dev transfer token for a specified address * @param _to The address to transfer to. * @param _value The amount to be transferred. */ function transfer(address _to, uint256 _value) public returns (bool) { require(_to != address(0)); require(_value <= balances[msg.sender]); // SafeMath.sub will throw if there is not enough balance. balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); Transfer(msg.sender, _to, _value); return true; } /** * @dev Gets the balance of the specified address. * @param _owner The address to query the the balance of. * @return An uint256 representing the amount owned by the passed address. */ function balanceOf(address _owner) public view returns (uint256 balance) { return balances[_owner]; } } contract StandardToken is ERC20, BasicToken { mapping (address => mapping (address => uint256)) internal allowed; /** * @dev Transfer tokens from one address to another * @param _from address The address which you want to send tokens from * @param _to address The address which you want to transfer to * @param _value uint256 the amount of tokens to be transferred */ function transferFrom(address _from, address _to, uint256 _value) public returns (bool) { require(_to != address(0)); require(_value <= balances[_from]); require(_value <= allowed[_from][msg.sender]); balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); Transfer(_from, _to, _value); return true; } /** * @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender. * * Beware that changing an allowance with this method brings the risk that someone may use both the old * and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this * race condition is to first reduce the spender&#39;s allowance to 0 and set the desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * @param _spender The address which will spend the funds. * @param _value The amount of tokens to be spent. */ function approve(address _spender, uint256 _value) public returns (bool) { allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); return true; } /** * @dev Function to check the amount of tokens that an owner allowed to a spender. * @param _owner address The address which owns the funds. * @param _spender address The address which will spend the funds. * @return A uint256 specifying the amount of tokens still available for the spender. */ function allowance(address _owner, address _spender) public view returns (uint256) { return allowed[_owner][_spender]; } /** * @dev Increase the amount of tokens that an owner allowed to a spender. * * approve should be called when allowed[_spender] == 0. To increment * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param _spender The address which will spend the funds. * @param _addedValue The amount of tokens to increase the allowance by. */ function increaseApproval(address _spender, uint _addedValue) public returns (bool) { allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue); Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } /** * @dev Decrease the amount of tokens that an owner allowed to a spender. * * approve should be called when allowed[_spender] == 0. To decrement * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param _spender The address which will spend the funds. * @param _subtractedValue The amount of tokens to decrease the allowance by. */ function decreaseApproval(address _spender, uint _subtractedValue) public returns (bool) { uint oldValue = allowed[msg.sender][_spender]; if (_subtractedValue > oldValue) { allowed[msg.sender][_spender] = 0; } else { allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue); } Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } } /** * @title Mintable token */ contract MintableToken is StandardToken, Ownable { event Mint(address indexed to, uint256 amount); event MintFinished(); event Burn(address sender,uint256 tokencount); bool public mintingFinished = false ; bool public transferAllowed = 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; } function resumeMinting() onlyOwner public returns (bool) { mintingFinished = false; return true; } function burn(address _from) external onlyOwner returns (bool success) { require(balances[_from] != 0); uint256 tokencount = balances[_from]; //address sender = _from; balances[_from] = 0; totalSupply_ = totalSupply_.sub(tokencount); Burn(_from, tokencount); return true; } function startTransfer() external onlyOwner { transferAllowed = true ; } function endTransfer() external onlyOwner { transferAllowed = false ; } function transfer(address _to, uint256 _value) public returns (bool) { require(transferAllowed); super.transfer(_to,_value); return true; } function transferFrom(address _from, address _to, uint256 _value) public returns (bool) { require(transferAllowed); super.transferFrom(_from,_to,_value); return true; } } contract ZebiCoin is MintableToken { string public constant name = "Zebi Coin"; string public constant symbol = "ZCO"; uint64 public constant decimals = 8; } /** * @title ZCrowdsale */ contract ZCrowdsale is Ownable{ using SafeMath for uint256; // The token being sold MintableToken public token; uint64 public tokenDecimals; // start and end timestamps where investments are allowed (both inclusive) uint256 public startTime; uint256 public endTime; uint256 public minTransAmount; uint256 public mintedTokensCap; //max 87 million tokens in presale. //contribution mapping(address => uint256) contribution; //bad contributor mapping(address => bool) cancelledList; // address where funds are collected address public wallet; bool public withinRefundPeriod; // how many token units a buyer gets per ether uint256 public ETHtoZCOrate; // amount of raised money in wei without factoring refunds uint256 public weiRaised; bool public stopped; modifier stopInEmergency { require (!stopped); _; } modifier inCancelledList { require(cancelledList[msg.sender]); _; } modifier inRefundPeriod { require(withinRefundPeriod); _; } /** * event for token purchase logging */ event TokenPurchase(address indexed purchaser, address indexed beneficiary, uint256 value, uint256 amount); event TakeEth(address sender,uint256 value); event Withdraw(uint256 _value); event SetParticipantStatus(address _participant); event Refund(address sender,uint256 refundBalance); function ZCrowdsale(uint256 _startTime, uint256 _endTime, uint256 _ETHtoZCOrate, address _wallet,uint256 _minTransAmount,uint256 _mintedTokensCap) public { require(_startTime >= now); require(_endTime >= _startTime); require(_ETHtoZCOrate > 0); require(_wallet != address(0)); token = new ZebiCoin(); //token = createTokenContract(); startTime = _startTime; endTime = _endTime; ETHtoZCOrate = _ETHtoZCOrate; wallet = _wallet; minTransAmount = _minTransAmount; tokenDecimals = 8; mintedTokensCap = _mintedTokensCap.mul(10**tokenDecimals); // mintedTokensCap is in Zwei } // fallback function can be used to buy tokens function () external payable { buyTokens(msg.sender); } function finishMint() onlyOwner public returns (bool) { token.finishMinting(); return true; } function resumeMint() onlyOwner public returns (bool) { token.resumeMinting(); return true; } function startTransfer() external onlyOwner { token.startTransfer() ; } function endTransfer() external onlyOwner { token.endTransfer() ; } function transferTokenOwnership(address owner) external onlyOwner { token.transferOwnership(owner); } function viewCancelledList(address participant) public view returns(bool){ return cancelledList[participant]; } // low level token purchase function function buyTokens(address beneficiary) public payable { require(beneficiary != address(0)); require(validPurchase()); uint256 weiAmount = msg.value; // calculate token amount to be created uint256 tokens = getTokenAmount(weiAmount); // update state weiRaised = weiRaised.add(weiAmount); token.mint(beneficiary, tokens); contribution[beneficiary] = contribution[beneficiary].add(weiAmount); TokenPurchase(msg.sender, beneficiary, weiAmount, tokens); forwardFunds(); } // creates the token to be sold. // override this method to have crowdsale of a specific mintable token. //function createTokenContract() internal returns (MintableToken) { // return new MintableToken(); // } // returns value in zwei // Override this method to have a way to add business logic to your crowdsale when buying function getTokenAmount(uint256 weiAmount) public view returns(uint256) { uint256 ETHtoZweiRate = ETHtoZCOrate.mul(10**tokenDecimals); return SafeMath.div((weiAmount.mul(ETHtoZweiRate)),(1 ether)); } // send ether to the fund collection wallet function forwardFunds() internal { wallet.transfer(msg.value); } function enableRefundPeriod() external onlyOwner{ withinRefundPeriod = true; } function disableRefundPeriod() external onlyOwner{ withinRefundPeriod = false; } // called by the owner on emergency, triggers stopped state function emergencyStop() external onlyOwner { stopped = true; } // called by the owner on end of emergency, returns to normal state function release() external onlyOwner { stopped = false; } function viewContribution(address participant) public view returns(uint256){ return contribution[participant]; } // @return true if the transaction can buy tokens function validPurchase() internal view returns (bool) { bool withinPeriod = now >= startTime && now <= endTime; //Value(msg.value); //bool nonZeroPurchase = msg.value != 0; bool validAmount = msg.value >= minTransAmount; bool withinmintedTokensCap = mintedTokensCap >= (token.totalSupply() + getTokenAmount(msg.value)); return withinPeriod && validAmount && withinmintedTokensCap; } function refund() external inCancelledList inRefundPeriod { require((contribution[msg.sender] > 0) && token.balanceOf(msg.sender)>0); uint256 refundBalance = contribution[msg.sender]; contribution[msg.sender] = 0; token.burn(msg.sender); msg.sender.transfer(refundBalance); Refund(msg.sender,refundBalance); } function forcedRefund(address _from) external onlyOwner { require(cancelledList[_from]); require((contribution[_from] > 0) && token.balanceOf(_from)>0); uint256 refundBalance = contribution[_from]; contribution[_from] = 0; token.burn(_from); _from.transfer(refundBalance); Refund(_from,refundBalance); } //takes ethers from zebiwallet to smart contract function takeEth() external payable { TakeEth(msg.sender,msg.value); } //transfers ether from smartcontract to zebiwallet function withdraw(uint256 _value) public onlyOwner { wallet.transfer(_value); Withdraw(_value); } function addCancellation (address _participant) external onlyOwner returns (bool success) { cancelledList[_participant] = true; return true; } } contract ZebiCoinCrowdsale is ZCrowdsale { function ZebiCoinCrowdsale(uint256 _startTime, uint256 _endTime, uint256 _rate, address _wallet,uint256 _minTransAmount,uint256 _mintedTokensCap) ZCrowdsale(_startTime, _endTime, _rate, _wallet , _minTransAmount,_mintedTokensCap){ } // creates the token to be sold. // function createTokenContract() internal returns (MintableToken) { // return new ZebiCoin(); // } } contract ZebiCoinTempMgr is Ownable{ using SafeMath for uint256; // address where funds are collected address public wallet; // instance of presale contract ZebiCoinCrowdsale public preSaleCSSC; // instance of token contract ZebiCoin public tsc; // number of decimals allowed in ZCO uint64 tokenDecimals; //bad contributor of presale mapping(address => bool) preSaleCancelledList; // contains token value in zwei mapping(address => uint256) noncsAllocations; // check for refund period bool public withinRefundPeriod; // amount refunded to each investor mapping(address => uint256) preSaleRefunds; modifier inPreSaleCancelledList { require(preSaleCancelledList[msg.sender]); _; } modifier inRefundPeriod { require(withinRefundPeriod); _; } event TakeEth(address sender,uint256 value); event Withdraw(uint256 _value); event PreSaleRefund(address sender,uint256 refundBalance); event AllocatenonCSTokens(address indexed beneficiary,uint256 amount); function ZebiCoinTempMgr(address presaleCrowdsale, address tokenAddress, address _wallet) public { wallet = _wallet; preSaleCSSC = ZebiCoinCrowdsale(presaleCrowdsale); tsc = ZebiCoin(tokenAddress); tokenDecimals = tsc.decimals(); } function finishMint() onlyOwner public returns (bool) { tsc.finishMinting(); return true; } function resumeMint() onlyOwner public returns (bool) { tsc.resumeMinting(); return true; } function startTransfer() external onlyOwner{ tsc.startTransfer() ; } function endTransfer() external onlyOwner{ tsc.endTransfer() ; } function transferTokenOwnership(address owner) external onlyOwner{ tsc.transferOwnership(owner); } function allocatenonCSTokens(address beneficiary,uint256 tokens) external onlyOwner { require(beneficiary != address(0)); uint256 Zweitokens = tokens.mul(10**(tokenDecimals )); noncsAllocations[beneficiary]= Zweitokens.add(noncsAllocations[beneficiary]); tsc.mint(beneficiary, Zweitokens); AllocatenonCSTokens(beneficiary,Zweitokens); } function revertNoncsallocation(address beneficiary) external onlyOwner { require(noncsAllocations[beneficiary]!=0); noncsAllocations[beneficiary]=0; tsc.burn(beneficiary); } function viewNoncsallocations(address participant) public view returns(uint256){ return noncsAllocations[participant]; } function viewPreSaleCancelledList(address participant) public view returns(bool){ return preSaleCancelledList[participant]; } function viewPreSaleRefunds(address participant) public view returns(uint256){ return preSaleRefunds[participant]; } function enableRefundPeriod() external onlyOwner{ withinRefundPeriod = true; } function disableRefundPeriod() external onlyOwner{ withinRefundPeriod = false; } function refund() external inPreSaleCancelledList inRefundPeriod { require((preSaleCSSC.viewContribution(msg.sender) > 0) && tsc.balanceOf(msg.sender)>0); uint256 refundBalance = preSaleCSSC.viewContribution(msg.sender); preSaleRefunds[msg.sender] = refundBalance; tsc.burn(msg.sender); msg.sender.transfer(refundBalance); PreSaleRefund(msg.sender,refundBalance); } function forcedRefund(address _from) external onlyOwner { require(preSaleCancelledList[_from]); require((preSaleCSSC.viewContribution(_from) > 0) && tsc.balanceOf(_from)>0); uint256 refundBalance = preSaleCSSC.viewContribution(_from); preSaleRefunds[_from] = refundBalance; tsc.burn(_from); _from.transfer(refundBalance); PreSaleRefund(_from,refundBalance); } //takes ethers from zebiwallet to smart contract function takeEth() external payable { TakeEth(msg.sender,msg.value); } //transfers ether from smartcontract to zebiwallet function withdraw(uint256 _value) public onlyOwner { wallet.transfer(_value); Withdraw(_value); } function addCancellation (address _participant) external onlyOwner returns (bool success) { preSaleCancelledList[_participant] = true; return true; } } /** * @title ZebiMainCrowdsale */ contract ZebiMainCrowdsale is Ownable{ using SafeMath for uint256; // The token being sold ZebiCoin public token; //calender year count; //uint256 calenderYearCounter; //lockeed tokens minted in current calender year uint256 currentYearMinted; //calenderYearMintCap for Zebi uint256 calenderYearMintCap; //calender year start uint256 calenderYearStart; //calenderYearEnd uint256 calenderYearEnd; //mintinge vested token start time uint256 vestedMintStartTime; //flag : whethere remainingZCO after crowdsale allocated or not //bool remainingZCOAllocated; //TODO uint256 zebiZCOShare; //TODO uint256 crowdsaleZCOCap; //transaction Start time uint256 transStartTime; // presale instance ZebiCoinCrowdsale public zcc; // tempMngr instance ZebiCoinTempMgr public tempMngr; // Number of decimals allowed for ZCO uint64 public tokenDecimals; // start and end timestamps where investments are allowed (both inclusive) uint256 public startTime; uint256 public endTime; //In seconds initialized in constructor only gold list members can buy uint256 public goldListPeriod; //endTime of 2nd bonus period minus startTime in seconds initialized in constructor: 2nd period for bonuses uint256 public postGoldPeriod; // Minimum amount to be invested in wei uint256 public minTransAmount; // Hardcap in wei uint256 public ethCap; // Contribution of each investor in main crowdsale mapping(address => uint256) mainContribution; // Bad contributor mapping(address => bool) mainCancelledList; // Gold Period Cap per address uint256 goldPeriodCap; //is the transaction occurring during gold list period bool goldListPeriodFlag; //goldListPeriod Contribution TODO mapping(address=>uint256) goldListContribution; // Gold List mapping(address => bool) goldList; //discounts mapping number of coins to percentage discount // mapping(uint256 => uint256) discounts; // KYC Accepted List mapping(address => bool) kycAcceptedList; // Address where funds are collected address public wallet; bool public withinRefundPeriod; // amount refunded to each investor mapping(address => uint256) preSaleRefundsInMainSale; uint256 public tokens; // net wei used to buy ZCOs in the transaction uint256 public weiAmount; // how many token units a buyer gets per ether uint256 public ETHtoZWeirate; // amount of raised money in wei without factoring refunds uint256 public mainWeiRaised; modifier inCancelledList { require(mainCancelledList[msg.sender]); _; } modifier inRefundPeriod { require(withinRefundPeriod); _; } event TokenPurchase(address indexed purchaser, uint256 value, uint256 amount); event TakeEth(address sender,uint256 value); event Withdraw(uint256 _value); event SetParticipantStatus(address _participant); event Refund(address sender,uint256 refundBalance); function ZebiMainCrowdsale(uint256 _startTime, uint256 _endTime, uint256 _ETHtoZWeirate, address _wallet,uint256 _minTransAmount,uint256 _ethCap, address tokenAddress, address presaleAddress,address tempMngrAddress,uint256 _goldListPeriod,uint256 _postGoldPeriod,uint256 _goldPeriodCap,uint256 _vestedMintStartTime,uint256 _calenderYearStart) public { require(_startTime >= now); require(_endTime >= _startTime); require(_ETHtoZWeirate > 0); require(_wallet != address(0)); token = ZebiCoin(tokenAddress); zcc = ZebiCoinCrowdsale(presaleAddress); startTime = _startTime; endTime = _endTime; ETHtoZWeirate = _ETHtoZWeirate; wallet = _wallet; minTransAmount = _minTransAmount; tokenDecimals = token.decimals(); ethCap = _ethCap; tempMngr=ZebiCoinTempMgr(tempMngrAddress); goldListPeriod=_goldListPeriod; postGoldPeriod=_postGoldPeriod; zebiZCOShare=SafeMath.mul(500000000,(10**tokenDecimals)); crowdsaleZCOCap=zebiZCOShare; goldPeriodCap=_goldPeriodCap; calenderYearMintCap = SafeMath.div((zebiZCOShare.mul(2)),8); //vestedMintStartTime=(startTime +((18 *30)*1 days)); //vestedMintStartTime=1567296000; //1 Sep 2019 vestedMintStartTime=_vestedMintStartTime; //calenderYearStart=1546300800; //1 Jan 2019 0:0:0 calenderYearStart=_calenderYearStart; //calenderYearEnd=1577836799; // 31 Dec 2019 23:59:59 calenderYearEnd=(calenderYearStart+1 years )- 1; } // Fallback function used to buy tokens function () external payable { buyTokens(msg.sender); } function finishMint() onlyOwner public returns (bool) { token.finishMinting(); return true; } function resumeMint() onlyOwner public returns (bool) { token.resumeMinting(); return true; } function startTransfer() external onlyOwner{ token.startTransfer() ; } function endTransfer() external onlyOwner{ token.endTransfer() ; } function transferTokenOwnership(address owner) external onlyOwner{ token.transferOwnership(owner); } function viewCancelledList(address participant) public view returns(bool){ return mainCancelledList[participant]; } function viewGoldList(address participant) public view returns(bool){ return goldList[participant]; } function addToGoldList (address _participant) external onlyOwner returns (bool ) { goldList[_participant] = true; return true; } function removeFromGoldList(address _participant) external onlyOwner returns(bool ){ goldList[_participant]=false; return true; } function viewKYCAccepted(address participant) public view returns(bool){ return kycAcceptedList[participant]; } function addToKYCList (address _participant) external onlyOwner returns (bool ) { kycAcceptedList[_participant] = true; return true; } function removeFromKYCList (address _participant) external onlyOwner returns (bool){ kycAcceptedList[_participant]=false; } function viewPreSaleRefundsInMainSale(address participant) public view returns(uint256){ return preSaleRefundsInMainSale[participant]; } /*function addToPreSaleRefunds(address participant,uint256 amountInEth) external onlyOwner returns(bool){ preSaleRefundsInMainSale[participant]=amountInEth.add(preSaleRefundsInMainSale[participant]); } function removeFromPreSaleRefunds(address participant,uint256 amountInEth) external onlyOwner returns(bool){ preSaleRefundsInMainSale[participant]=(preSaleRefundsInMainSale[participant]).sub(amountInEth); }*/ // Low level token purchase function function buyTokens(address beneficiary) public payable { transStartTime=now; require(goldList[beneficiary]||kycAcceptedList[beneficiary]); goldListPeriodFlag=false; require(beneficiary != address(0)); require(validPurchase()); uint256 extraEth=0; weiAmount = msg.value; /* if(goldListPeriodFlag){ weiAmount=goldPeriodCap.sub(goldListContribution[msg.sender]); extraEth=(msg.value).sub(weiAmount); }*/ //for partial fulfilment feature : return extra ether transferred by investor if((msg.value>ethCap.sub(mainWeiRaised)) && !goldListPeriodFlag){ weiAmount=ethCap.sub(mainWeiRaised); extraEth=(msg.value).sub(weiAmount); } // calculate token amount to be alloted tokens = getTokenAmount(weiAmount); // update state mainWeiRaised = mainWeiRaised.add(weiAmount); token.mint(beneficiary, tokens); mainContribution[beneficiary] = mainContribution[beneficiary].add(weiAmount); if(goldListPeriodFlag){ goldListContribution[beneficiary] = goldListContribution[beneficiary].add(weiAmount); } //TokenPurchase(msg.sender, beneficiary, weiAmount, tokens); TokenPurchase(beneficiary, weiAmount, tokens); forwardFunds(); if(extraEth>0){ beneficiary.transfer(extraEth); } } // returns value in zwei calculating number of tokens including bonuses function getTokenAmount(uint256 weiAmount1) public view returns(uint256) { //uint256 ETHtoZweiRate = ETHtoZWeirate; uint256 number = SafeMath.div((weiAmount1.mul(ETHtoZWeirate)),(1 ether)); uint256 volumeBonus; uint256 timeBonus; if(number >= 400000000000000) { volumeBonus = SafeMath.div((number.mul(25)),100); } else if(number>= 150000000000000) { volumeBonus = SafeMath.div((number.mul(20)),100); } else if(number>= 80000000000000) { volumeBonus = SafeMath.div((number.mul(15)),100); } else if(number>= 40000000000000) { volumeBonus = SafeMath.div((number.mul(10)),100); } else if(number>= 7500000000000) { volumeBonus = SafeMath.div((number.mul(5)),100); } else{ volumeBonus=0; } // if(goldListPeriodFlag){ timeBonus = SafeMath.div((number.mul(15)),100); } else if(transStartTime <= startTime + postGoldPeriod){ timeBonus = SafeMath.div((number.mul(10)),100); } else{ timeBonus=0; } number=number+timeBonus+volumeBonus; return number; } // send ether to the fund collection wallet function forwardFunds() internal { wallet.transfer(weiAmount); } function enableRefundPeriod() external onlyOwner{ withinRefundPeriod = true; } function disableRefundPeriod() external onlyOwner{ withinRefundPeriod = false; } function viewContribution(address participant) public view returns(uint256){ return mainContribution[participant]; } // checks if the investor can buy tokens function validPurchase() internal view returns (bool) { bool withinPeriod = transStartTime >= startTime && transStartTime <= endTime; bool validAmount = msg.value >= minTransAmount; //bool withinEthCap = ethCap >= (msg.value + mainWeiRaised); bool withinEthCap = ((ethCap.sub(mainWeiRaised))>0); bool goldPeriodValid=true; if(transStartTime <= (startTime + goldListPeriod)){ goldPeriodValid=(goldList[msg.sender])&&(goldListContribution[msg.sender]+msg.value <= goldPeriodCap); goldListPeriodFlag=true; } return withinPeriod && validAmount && withinEthCap && goldPeriodValid; } /*function mintLeftOverZCOToWallet() external onlyOwner returns (bool){ //uint256 Zweitokens = amount; require(!remainingZCOAllocated); require(now>endTime); //uint256 ETHtoZweiRate = ETHtoZWeirate.mul(10**tokenDecimals); //uint256 remainingCap=ethCap.sub(mainWeiRaised); //uint256 amount = SafeMath.div((remainingCap.mul(ETHtoZweiRate)),(1 ether)); //mainWeiRaised = mainWeiRaised.add(amount); //uint256 zweitokens = SafeMath.mul(500000000,10**(tokenDecimals )); uint256 zweitokens=crowdsaleZCOCap.sub(token.totalSupply()); //zweitokens=zweitokens.sub(token.totalSupply()); token.mint(wallet, zweitokens); remainingZCOAllocated=true; return true; }*/ function mintAndAllocateZCO(address partnerAddress,uint256 amountInZWei) external onlyOwner returns(bool){ require((crowdsaleZCOCap.sub(token.totalSupply()))>=amountInZWei); require(partnerAddress!=address(0)); //require(now>endTime); //require(!remainingZCOAllocated); token.mint(partnerAddress,amountInZWei); return true; } function mintvestedTokens (address partnerAddress,uint256 zweitokens) external onlyOwner returns(bool){ require(zweitokens<=zebiZCOShare && zweitokens>0); require(partnerAddress!=address(0)); require(now>=vestedMintStartTime); //year uint256 currentYearCounter=SafeMath.div((SafeMath.sub(now,calenderYearStart)),1 years); //if(currentYearCounter>calenderYearCounter){ if(now>calenderYearEnd && currentYearCounter>=1){ //calenderYearCounter=currentYearCounter; currentYearMinted=0; calenderYearStart=calenderYearEnd+((currentYearCounter-1)*1 years) +1; calenderYearEnd=(calenderYearStart+ 1 years )- 1; } require(currentYearMinted+zweitokens<=calenderYearMintCap); currentYearMinted=currentYearMinted+zweitokens; token.mint(partnerAddress,zweitokens); zebiZCOShare=zebiZCOShare.sub(zweitokens); } function refund() external inCancelledList inRefundPeriod { require(mainCancelledList[msg.sender]); require((mainContribution[msg.sender] > 0) && token.balanceOf(msg.sender)>0); uint256 presaleContribution = zcc.viewContribution(msg.sender); uint256 refundBalance = (mainContribution[msg.sender]).add(presaleContribution) ; uint256 preSaleRefundTemp= tempMngr.viewPreSaleRefunds(msg.sender); uint256 preSaleRefundMain=presaleContribution.sub(preSaleRefundTemp); refundBalance=refundBalance.sub(preSaleRefundTemp); refundBalance=refundBalance.sub(preSaleRefundsInMainSale[msg.sender]); preSaleRefundsInMainSale[msg.sender]=preSaleRefundMain; mainContribution[msg.sender] = 0; token.burn(msg.sender); msg.sender.transfer(refundBalance); Refund(msg.sender,refundBalance); } function forcedRefund(address _from) external onlyOwner { require(mainCancelledList[_from]); require((mainContribution[_from] > 0) && token.balanceOf(_from)>0); uint256 presaleContribution = zcc.viewContribution(_from); uint256 refundBalance = (mainContribution[_from]).add(presaleContribution) ; uint256 preSaleRefundTemp= tempMngr.viewPreSaleRefunds(_from); uint256 preSaleRefundMain=presaleContribution.sub(preSaleRefundTemp); refundBalance=refundBalance.sub(preSaleRefundTemp); refundBalance=refundBalance.sub(preSaleRefundsInMainSale[_from]); preSaleRefundsInMainSale[_from]=preSaleRefundMain; mainContribution[_from] = 0; token.burn(_from); _from.transfer(refundBalance); Refund(_from,refundBalance); } //takes ethers from zebiwallet to smart contract function takeEth() external payable { TakeEth(msg.sender,msg.value); } //transfers ether from smartcontract to zebiwallet function withdraw(uint256 _value) public onlyOwner { wallet.transfer(_value); Withdraw(_value); } //Maintains list of investors with failed KYC validation function addCancellation (address _participant) external onlyOwner returns (bool success) { mainCancelledList[_participant] = true; return true; } }
uint256 ETHtoZweiRate = ETHtoZWeirate;
function getTokenAmount(uint256 weiAmount1) public view returns(uint256) { uint256 number = SafeMath.div((weiAmount1.mul(ETHtoZWeirate)),(1 ether)); uint256 volumeBonus; uint256 timeBonus; if(number >= 400000000000000) { volumeBonus = SafeMath.div((number.mul(25)),100); } else if(number>= 150000000000000) { volumeBonus = SafeMath.div((number.mul(20)),100); } else if(number>= 80000000000000) { volumeBonus = SafeMath.div((number.mul(15)),100); } else if(number>= 40000000000000) { volumeBonus = SafeMath.div((number.mul(10)),100); } else if(number>= 7500000000000) { volumeBonus = SafeMath.div((number.mul(5)),100); } else{ volumeBonus=0; } if(goldListPeriodFlag){ timeBonus = SafeMath.div((number.mul(15)),100); } else if(transStartTime <= startTime + postGoldPeriod){ timeBonus = SafeMath.div((number.mul(10)),100); } else{ timeBonus=0; } number=number+timeBonus+volumeBonus; return number; }
2,115,092
./full_match/42/0x647edA4af725fd1ABbF74dd429DE8E48227D2A85/sources/browser/test.sol
msg.sender.transfer(daiAmountIn);IERC20 daiToken = IERC20(kovanDAI);require(daiToken.approve(msg.sender, daiAmountIn), "approve failed");require(daiToken.transferFrom(msg.sender, address(this), daiAmountIn), "transferFrom failed");require(daiToken.approve(address(this), daiAmountIn), "approve failed");uint deadline = block.timestamp + 15; using 'now' for convenience, for mainnet pass deadline from frontend!uniswapRouter.swapTokensForExactETH(daiAmountIn, minETHAmountToReceieve, getPathForDAItoETH(), myAccount, deadline);
function convertDAItoETH(uint daiAmountIn, uint minETHAmountToReceieve) external { IERC20 daiToken = IERC20(kovanDAI); daiToken.approve(msg.sender, daiAmountIn); daiToken.transfer(address(this), daiAmountIn); }
16,221,237
pragma solidity ^0.5.0; import "../node_modules/openzeppelin-solidity/contracts/math/SafeMath.sol"; contract FlightSuretyData { using SafeMath for uint256; /********************************************************************************************/ /* DATA VARIABLES */ /********************************************************************************************/ address payable private contractOwner; // Account used to deploy contract bool private operational = true; // Blocks all state changes throughout the contract if false uint256 N; mapping(address => bool) authorizedCaller; struct Airline{ bool isRegistered; bool hasDeposited; uint amount; address airline; uint index; } enum State{ InsuranceBought, AmountCredited, AmountTransfered } struct Passenger{ address airline; bytes32 flightKey; address insuree; string flight; uint256 funds; State status; } mapping(address=>Passenger) client; mapping(bytes32=>Passenger[]) clientInsurance; mapping(address=>Airline) private registeredAirline; struct Flight { bool isRegistered; string flight; uint256 timestamp; address airline; } mapping(bytes32 => Flight) private flights; /********************************************************************************************/ /* EVENT DEFINITIONS */ /********************************************************************************************/ /** * @dev Constructor * The deploying account becomes contractOwner */ constructor() public { contractOwner = msg.sender; registeredAirline[contractOwner] = Airline(true, true,10 ether,msg.sender,0); N = 1; } event AirlineFunded(string airline,uint funds); event Log(uint256 valDiv, uint256 valN, uint256 valM, address airline,bool status); event InsurancePayout(string msg, uint val); event InsuranceBought(string msg, uint val); event InsuranceTransferedToClient(string msg, uint val); /********************************************************************************************/ /* FUNCTION MODIFIERS */ /********************************************************************************************/ // Modifiers help avoid duplication of code. They are typically used to validate something // before a function is allowed to be executed. /** * @dev Modifier that requires the "operational" boolean variable to be "true" * This is used on all state changing functions to pause the contract in * the event there is an issue that needs to be fixed */ modifier requireIsOperational() { require(operational, "Contract is currently not operational"); _; // All modifiers require an "_" which indicates where the function body will be added } /** * @dev Modifier that requires the "ContractOwner" account to be the function caller */ modifier requireContractOwner() { require(msg.sender == contractOwner, "Caller is not contract owner"); _; } modifier requireAuthorizedCaller(){ require(authorizedCaller[msg.sender],"Caller is not authorized"); _; } /********************************************************************************************/ /* UTILITY FUNCTIONS */ /********************************************************************************************/ /** * @dev Get operating status of contract * * @return A bool that is the current operating status */ function isOperational() public view returns(bool) { return operational; } function authorizeCaller(address caller ) public requireIsOperational requireContractOwner{ require(!authorizedCaller[caller]," Caller is already authorized "); authorizedCaller[caller] = true; } function deRegisterAuthorizedCaller(address caller) public requireIsOperational requireContractOwner { require(authorizedCaller[caller]," Caller is not authorized "); delete authorizedCaller[caller]; } /** * @dev Sets contract operations on/off * * When operational mode is disabled, all write transactions except for this one will fail */ function setOperatingStatus ( bool mode ) external requireContractOwner { operational = mode; } /********************************************************************************************/ /* SMART CONTRACT FUNCTIONS */ /********************************************************************************************/ /** * @dev Add an airline to the registration queue * Can only be called from FlightSuretyApp contract * */ function registerAirline(address airline ) external { require(!registeredAirline[airline].isRegistered,"Airline Already Registered"); N = N + 1; registeredAirline[airline].isRegistered = true; registeredAirline[airline].airline = msg.sender; emit Log(0,1000000,100000000,airline, registeredAirline[airline].hasDeposited); } function deRegisterAirline(address airline ) external { require(registeredAirline[airline].isRegistered,"Airline is not Registered"); registeredAirline[airline].isRegistered = false; registeredAirline[airline].amount = 0; registeredAirline[airline].hasDeposited = false; N = N -1; } function getN() external returns (uint n){ return N; } /** * @dev Buy insurance for a flight * */ function buy(bytes32 flightKey,address clientAdd) external payable{ require(msg.value <=1 ether && msg.value > 0 ether,"Max 1 ether allowed "); clientInsurance[flightKey].push( Passenger( flights[flightKey].airline,flightKey,clientAdd, flights[flightKey].flight,msg.value,State.InsuranceBought)); emit InsuranceBought("Insurance Bought ",msg.value); } /** * @dev Credits payouts to insurees */ function creditInsurees(bytes32 flightkey) external { require(clientInsurance[flightkey].length > 0,"Client not registered "); for(uint i = 0; i < clientInsurance[flightkey].length ;i++){ clientInsurance[flightkey][i].funds = SafeMath.add(clientInsurance[flightkey][i].funds,SafeMath.div(clientInsurance[flightkey][i].funds,2)); clientInsurance[flightkey][i].status = State.AmountCredited; client[clientInsurance[flightkey][i].insuree] = clientInsurance[flightkey][i]; emit InsurancePayout("Amount credited to insurees account ", clientInsurance[flightkey][i].funds ); } delete clientInsurance[flightkey]; } function registerFlight(address airline,string calldata flight,uint256 timestamp,bool isRegistered) external { bytes32 key = getFlightKey( airline, flight, timestamp); flights[key] = Flight(isRegistered,flight,timestamp,airline); } function getAirline(address airline) public view returns ( bool isRegistered, bool hasDeposited, uint amount ){ return ( registeredAirline[airline].isRegistered, registeredAirline[airline].hasDeposited, registeredAirline[airline].amount ); } function setAirline(address airline, bool isRegistered ) public { registeredAirline[airline].isRegistered = isRegistered; } /** * @dev Transfers eligible payout funds to insuree * */ function pay(address payable insuree) internal { emit Log( 11,11,client[insuree].funds,insuree, true ); require( client[insuree].funds > 0 ether,"Client not registered "); insuree.transfer(client[insuree].funds); emit InsuranceTransferedToClient("Amount transfered to client ", client[insuree].funds); client[insuree].status = State.AmountTransfered; } function getFunds(address payable insuree) external returns(uint256 amount) { pay(insuree); return client[insuree].funds; } /** * @dev Initial funding for the insurance. Unless there are too many delayed flights * resulting in insurance payouts, the contract should be self-sustaining * */ function fund(address airline) public payable requireIsOperational { registeredAirline[airline].hasDeposited = true; registeredAirline[airline].amount = msg.value; registeredAirline[airline].airline = msg.sender; emit AirlineFunded("Ethers paid ",msg.value); // emit Log(msg.value,N,M,airline, registeredAirline[airline].hasDeposited); } function getFlightKey(address airline,string memory flight,uint256 timestamp) pure internal returns(bytes32) { return keccak256(abi.encodePacked(airline, flight, timestamp)); } /** * @dev Fallback function for funding smart contract. * */ function() external payable { fund(msg.sender); } }
Credits payouts to insurees/
function creditInsurees(bytes32 flightkey) external { require(clientInsurance[flightkey].length > 0,"Client not registered "); for(uint i = 0; i < clientInsurance[flightkey].length ;i++){ clientInsurance[flightkey][i].funds = SafeMath.add(clientInsurance[flightkey][i].funds,SafeMath.div(clientInsurance[flightkey][i].funds,2)); clientInsurance[flightkey][i].status = State.AmountCredited; client[clientInsurance[flightkey][i].insuree] = clientInsurance[flightkey][i]; emit InsurancePayout("Amount credited to insurees account ", clientInsurance[flightkey][i].funds ); } delete clientInsurance[flightkey]; }
7,302,199
pragma solidity >=0.5.0 <0.6.0; /* MIT Licence: Copyright (c) 2018-2020 ECDF, TU Berlin https://www.bbblockchain.de 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. */ import "./BBB_Owned.sol"; import "./BBB_Usecase.sol"; contract BBB_Project is BBB_Owned { enum DetailType { NAME, URL, START, END, VISBILITY, DESCRIPTION, DEVELOPER, STAKEHOLDERS, STAKEHOLDERTYPES, IMAGEURL, WEBSITE, POSTALADDRESS } string public name; string public url; string public description; string public developer; string[] public stakeHolders; uint256 public stakeHoldersSize; string[] public stakeHolderTypes; uint256 public stakeHolderTypesSize; string[] public imageUrls; uint256 public imageUrlsSize; string public website; string public postalAddress; uint256 public start; uint256 public end; bool public visible; BBB_Usecase[] public usecases; uint256 public usecasesSize; constructor(address payable _owner, string memory _name, string memory _description, string memory _url, string memory _developer, uint _start, uint _end, bool _visible) BBB_Owned(_owner) public { require(msg.sender == _owner, "New projects can only be deployed by owner."); // Check for unintentionally assigned owner name = _name; url = _url; start = _start; end = _end; visible = _visible; description = _description; developer = _developer; } // Events event NewUsecase( uint indexed usecaseIndex, uint indexed usecaseType ); event ChangedDetail( DetailType indexed detailName ); // Setters function setName(string memory _name) public altering ownerOnly { name = _name; emit ChangedDetail(DetailType.NAME); } function setUrl(string memory _url) public altering ownerOnly { url = _url; emit ChangedDetail(DetailType.URL); } function setStart(uint _start) public altering ownerOnly { start = _start; emit ChangedDetail(DetailType.START); } function setEnd(uint _end) public altering ownerOnly { end = _end; emit ChangedDetail(DetailType.END); } function setVisible(bool _visible) public altering ownerOnly { visible = _visible; emit ChangedDetail(DetailType.VISBILITY); } function setDescription(string memory _description) public altering ownerOnly { description = _description; emit ChangedDetail(DetailType.DESCRIPTION); } function setWebsite(string memory _website) public altering ownerOnly { website = _website; emit ChangedDetail(DetailType.WEBSITE); } function setPostalAddress(string memory _postalAddress) public altering ownerOnly { postalAddress = _postalAddress; emit ChangedDetail(DetailType.POSTALADDRESS); } function setDeveloper(string memory _developer) public altering ownerOnly { developer = _developer; emit ChangedDetail(DetailType.DEVELOPER); } function addStakeHolder(string memory _stakeHolder) public altering ownerOnly { stakeHolders.push(_stakeHolder); stakeHoldersSize++; emit ChangedDetail(DetailType.STAKEHOLDERS); } function addStakeHolderType(string memory _stakeHolderType) public altering ownerOnly { stakeHolderTypes.push(_stakeHolderType); stakeHolderTypesSize++; emit ChangedDetail(DetailType.STAKEHOLDERTYPES); } function addImageUrl(string memory _imageUrl) public altering ownerOnly { imageUrls.push(_imageUrl); imageUrlsSize++; emit ChangedDetail(DetailType.IMAGEURL); } function resetStakeHolder() public altering ownerOnly { stakeHolders.length = 0; stakeHoldersSize = 0; emit ChangedDetail(DetailType.STAKEHOLDERS); } function resetStakeHolderType() public altering ownerOnly { stakeHolderTypes.length = 0; stakeHolderTypesSize = 0; emit ChangedDetail(DetailType.STAKEHOLDERTYPES); } function resetImageUrl() public altering ownerOnly { imageUrls.length = 0; imageUrlsSize = 0; emit ChangedDetail(DetailType.IMAGEURL); } // Add a new use case function addUsecase(BBB_Usecase _usecase) public altering ownerOnly { assert(_usecase.getType() >= 0); assert(usecasesSize < 2**256 - 1); usecases.push(_usecase); emit NewUsecase(usecasesSize, _usecase.getType()); usecasesSize++; } // Search for use case function getUsecase(uint _type) public view returns (address) { for(uint i = 0; i < usecasesSize; i++) { if(usecases[i].getType() == _type) { return address(usecases[i]); } } return address(0); } }
Search for use case
function getUsecase(uint _type) public view returns (address) { for(uint i = 0; i < usecasesSize; i++) { if(usecases[i].getType() == _type) { return address(usecases[i]); } } return address(0); }
12,875,329
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (access/AccessControlEnumerable.sol) pragma solidity ^0.8.0; import "./IAccessControlEnumerableUpgradeable.sol"; import "./AccessControlUpgradeable.sol"; import "../utils/structs/EnumerableSetUpgradeable.sol"; import "../proxy/utils/Initializable.sol"; /** * @dev Extension of {AccessControl} that allows enumerating the members of each role. */ abstract contract AccessControlEnumerableUpgradeable is Initializable, IAccessControlEnumerableUpgradeable, AccessControlUpgradeable { function __AccessControlEnumerable_init() internal onlyInitializing { __Context_init_unchained(); __ERC165_init_unchained(); __AccessControl_init_unchained(); __AccessControlEnumerable_init_unchained(); } function __AccessControlEnumerable_init_unchained() internal onlyInitializing { } using EnumerableSetUpgradeable for EnumerableSetUpgradeable.AddressSet; mapping(bytes32 => EnumerableSetUpgradeable.AddressSet) private _roleMembers; /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IAccessControlEnumerableUpgradeable).interfaceId || super.supportsInterface(interfaceId); } /** * @dev Returns one of the accounts that have `role`. `index` must be a * value between 0 and {getRoleMemberCount}, non-inclusive. * * Role bearers are not sorted in any particular way, and their ordering may * change at any point. * * WARNING: When using {getRoleMember} and {getRoleMemberCount}, make sure * you perform all queries on the same block. See the following * https://forum.openzeppelin.com/t/iterating-over-elements-on-enumerableset-in-openzeppelin-contracts/2296[forum post] * for more information. */ function getRoleMember(bytes32 role, uint256 index) public view override returns (address) { return _roleMembers[role].at(index); } /** * @dev Returns the number of accounts that have `role`. Can be used * together with {getRoleMember} to enumerate all bearers of a role. */ function getRoleMemberCount(bytes32 role) public view override returns (uint256) { return _roleMembers[role].length(); } /** * @dev Overload {_grantRole} to track enumerable memberships */ function _grantRole(bytes32 role, address account) internal virtual override { super._grantRole(role, account); _roleMembers[role].add(account); } /** * @dev Overload {_revokeRole} to track enumerable memberships */ function _revokeRole(bytes32 role, address account) internal virtual override { super._revokeRole(role, account); _roleMembers[role].remove(account); } uint256[49] private __gap; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (access/AccessControl.sol) pragma solidity ^0.8.0; import "./IAccessControlUpgradeable.sol"; import "../utils/ContextUpgradeable.sol"; import "../utils/StringsUpgradeable.sol"; import "../utils/introspection/ERC165Upgradeable.sol"; import "../proxy/utils/Initializable.sol"; /** * @dev Contract module that allows children to implement role-based access * control mechanisms. This is a lightweight version that doesn't allow enumerating role * members except through off-chain means by accessing the contract event logs. Some * applications may benefit from on-chain enumerability, for those cases see * {AccessControlEnumerable}. * * Roles are referred to by their `bytes32` identifier. These should be exposed * in the external API and be unique. The best way to achieve this is by * using `public constant` hash digests: * * ``` * bytes32 public constant MY_ROLE = keccak256("MY_ROLE"); * ``` * * Roles can be used to represent a set of permissions. To restrict access to a * function call, use {hasRole}: * * ``` * function foo() public { * require(hasRole(MY_ROLE, msg.sender)); * ... * } * ``` * * Roles can be granted and revoked dynamically via the {grantRole} and * {revokeRole} functions. Each role has an associated admin role, and only * accounts that have a role's admin role can call {grantRole} and {revokeRole}. * * By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means * that only accounts with this role will be able to grant or revoke other * roles. More complex role relationships can be created by using * {_setRoleAdmin}. * * WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to * grant and revoke this role. Extra precautions should be taken to secure * accounts that have been granted it. */ abstract contract AccessControlUpgradeable is Initializable, ContextUpgradeable, IAccessControlUpgradeable, ERC165Upgradeable { function __AccessControl_init() internal onlyInitializing { __Context_init_unchained(); __ERC165_init_unchained(); __AccessControl_init_unchained(); } function __AccessControl_init_unchained() internal onlyInitializing { } struct RoleData { mapping(address => bool) members; bytes32 adminRole; } mapping(bytes32 => RoleData) private _roles; bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00; /** * @dev Modifier that checks that an account has a specific role. Reverts * with a standardized message including the required role. * * The format of the revert reason is given by the following regular expression: * * /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/ * * _Available since v4.1._ */ modifier onlyRole(bytes32 role) { _checkRole(role, _msgSender()); _; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IAccessControlUpgradeable).interfaceId || super.supportsInterface(interfaceId); } /** * @dev Returns `true` if `account` has been granted `role`. */ function hasRole(bytes32 role, address account) public view override returns (bool) { return _roles[role].members[account]; } /** * @dev Revert with a standard message if `account` is missing `role`. * * The format of the revert reason is given by the following regular expression: * * /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/ */ function _checkRole(bytes32 role, address account) internal view { if (!hasRole(role, account)) { revert( string( abi.encodePacked( "AccessControl: account ", StringsUpgradeable.toHexString(uint160(account), 20), " is missing role ", StringsUpgradeable.toHexString(uint256(role), 32) ) ) ); } } /** * @dev Returns the admin role that controls `role`. See {grantRole} and * {revokeRole}. * * To change a role's admin, use {_setRoleAdmin}. */ function getRoleAdmin(bytes32 role) public view override returns (bytes32) { return _roles[role].adminRole; } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function grantRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) { _grantRole(role, account); } /** * @dev Revokes `role` from `account`. * * If `account` had been granted `role`, emits a {RoleRevoked} event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function revokeRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) { _revokeRole(role, account); } /** * @dev Revokes `role` from the calling account. * * Roles are often managed via {grantRole} and {revokeRole}: this function's * purpose is to provide a mechanism for accounts to lose their privileges * if they are compromised (such as when a trusted device is misplaced). * * If the calling account had been revoked `role`, emits a {RoleRevoked} * event. * * Requirements: * * - the caller must be `account`. */ function renounceRole(bytes32 role, address account) public virtual override { require(account == _msgSender(), "AccessControl: can only renounce roles for self"); _revokeRole(role, account); } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. Note that unlike {grantRole}, this function doesn't perform any * checks on the calling account. * * [WARNING] * ==== * This function should only be called from the constructor when setting * up the initial roles for the system. * * Using this function in any other way is effectively circumventing the admin * system imposed by {AccessControl}. * ==== * * NOTE: This function is deprecated in favor of {_grantRole}. */ function _setupRole(bytes32 role, address account) internal virtual { _grantRole(role, account); } /** * @dev Sets `adminRole` as ``role``'s admin role. * * Emits a {RoleAdminChanged} event. */ function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual { bytes32 previousAdminRole = getRoleAdmin(role); _roles[role].adminRole = adminRole; emit RoleAdminChanged(role, previousAdminRole, adminRole); } /** * @dev Grants `role` to `account`. * * Internal function without access restriction. */ function _grantRole(bytes32 role, address account) internal virtual { if (!hasRole(role, account)) { _roles[role].members[account] = true; emit RoleGranted(role, account, _msgSender()); } } /** * @dev Revokes `role` from `account`. * * Internal function without access restriction. */ function _revokeRole(bytes32 role, address account) internal virtual { if (hasRole(role, account)) { _roles[role].members[account] = false; emit RoleRevoked(role, account, _msgSender()); } } uint256[49] private __gap; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (access/IAccessControlEnumerable.sol) pragma solidity ^0.8.0; import "./IAccessControlUpgradeable.sol"; /** * @dev External interface of AccessControlEnumerable declared to support ERC165 detection. */ interface IAccessControlEnumerableUpgradeable is IAccessControlUpgradeable { /** * @dev Returns one of the accounts that have `role`. `index` must be a * value between 0 and {getRoleMemberCount}, non-inclusive. * * Role bearers are not sorted in any particular way, and their ordering may * change at any point. * * WARNING: When using {getRoleMember} and {getRoleMemberCount}, make sure * you perform all queries on the same block. See the following * https://forum.openzeppelin.com/t/iterating-over-elements-on-enumerableset-in-openzeppelin-contracts/2296[forum post] * for more information. */ function getRoleMember(bytes32 role, uint256 index) external view returns (address); /** * @dev Returns the number of accounts that have `role`. Can be used * together with {getRoleMember} to enumerate all bearers of a role. */ function getRoleMemberCount(bytes32 role) external view returns (uint256); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (access/IAccessControl.sol) pragma solidity ^0.8.0; /** * @dev External interface of AccessControl declared to support ERC165 detection. */ interface IAccessControlUpgradeable { /** * @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole` * * `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite * {RoleAdminChanged} not being emitted signaling this. * * _Available since v3.1._ */ event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole); /** * @dev Emitted when `account` is granted `role`. * * `sender` is the account that originated the contract call, an admin role * bearer except when using {AccessControl-_setupRole}. */ event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Emitted when `account` is revoked `role`. * * `sender` is the account that originated the contract call: * - if using `revokeRole`, it is the admin role bearer * - if using `renounceRole`, it is the role bearer (i.e. `account`) */ event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Returns `true` if `account` has been granted `role`. */ function hasRole(bytes32 role, address account) external view returns (bool); /** * @dev Returns the admin role that controls `role`. See {grantRole} and * {revokeRole}. * * To change a role's admin, use {AccessControl-_setRoleAdmin}. */ function getRoleAdmin(bytes32 role) external view returns (bytes32); /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function grantRole(bytes32 role, address account) external; /** * @dev Revokes `role` from `account`. * * If `account` had been granted `role`, emits a {RoleRevoked} event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function revokeRole(bytes32 role, address account) external; /** * @dev Revokes `role` from the calling account. * * Roles are often managed via {grantRole} and {revokeRole}: this function's * purpose is to provide a mechanism for accounts to lose their privileges * if they are compromised (such as when a trusted device is misplaced). * * If the calling account had been granted `role`, emits a {RoleRevoked} * event. * * Requirements: * * - the caller must be `account`. */ function renounceRole(bytes32 role, address account) external; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (access/Ownable.sol) pragma solidity ^0.8.0; import "../utils/ContextUpgradeable.sol"; import "../proxy/utils/Initializable.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract OwnableUpgradeable is Initializable, ContextUpgradeable { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ function __Ownable_init() internal onlyInitializing { __Context_init_unchained(); __Ownable_init_unchained(); } function __Ownable_init_unchained() internal onlyInitializing { _transferOwnership(_msgSender()); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { _transferOwnership(address(0)); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); _transferOwnership(newOwner); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Internal function without access restriction. */ function _transferOwnership(address newOwner) internal virtual { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } uint256[49] private __gap; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (proxy/utils/Initializable.sol) pragma solidity ^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 {ERC1967Proxy-constructor}. * * CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure * that all initializers are idempotent. This is not verified automatically as constructors are by Solidity. * * [CAUTION] * ==== * Avoid leaving a contract uninitialized. * * An uninitialized contract can be taken over by an attacker. This applies to both a proxy and its implementation * contract, which may impact the proxy. To initialize the implementation contract, you can either invoke the * initializer manually, or you can include a constructor to automatically mark it as initialized when it is deployed: * * [.hljs-theme-light.nopadding] * ``` * /// @custom:oz-upgrades-unsafe-allow constructor * constructor() initializer {} * ``` * ==== */ abstract contract Initializable { /** * @dev Indicates that the contract has been initialized. */ bool private _initialized; /** * @dev Indicates that the contract is in the process of being initialized. */ bool private _initializing; /** * @dev Modifier to protect an initializer function from being invoked twice. */ modifier initializer() { // If the contract is initializing we ignore whether _initialized is set in order to support multiple // inheritance patterns, but we only do this in the context of a constructor, because in other contexts the // contract may have been reentered. require(_initializing ? _isConstructor() : !_initialized, "Initializable: contract is already initialized"); bool isTopLevelCall = !_initializing; if (isTopLevelCall) { _initializing = true; _initialized = true; } _; if (isTopLevelCall) { _initializing = false; } } /** * @dev Modifier to protect an initialization function so that it can only be invoked by functions with the * {initializer} modifier, directly or indirectly. */ modifier onlyInitializing() { require(_initializing, "Initializable: contract is not initializing"); _; } function _isConstructor() private view returns (bool) { return !AddressUpgradeable.isContract(address(this)); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (security/Pausable.sol) pragma solidity ^0.8.0; import "../utils/ContextUpgradeable.sol"; import "../proxy/utils/Initializable.sol"; /** * @dev Contract module which allows children to implement an emergency stop * mechanism that can be triggered by an authorized account. * * This module is used through inheritance. It will make available the * modifiers `whenNotPaused` and `whenPaused`, which can be applied to * the functions of your contract. Note that they will not be pausable by * simply including this module, only once the modifiers are put in place. */ abstract contract PausableUpgradeable is Initializable, ContextUpgradeable { /** * @dev Emitted when the pause is triggered by `account`. */ event Paused(address account); /** * @dev Emitted when the pause is lifted by `account`. */ event Unpaused(address account); bool private _paused; /** * @dev Initializes the contract in unpaused state. */ function __Pausable_init() internal onlyInitializing { __Context_init_unchained(); __Pausable_init_unchained(); } function __Pausable_init_unchained() internal onlyInitializing { _paused = false; } /** * @dev Returns true if the contract is paused, and false otherwise. */ function paused() public view virtual returns (bool) { return _paused; } /** * @dev Modifier to make a function callable only when the contract is not paused. * * Requirements: * * - The contract must not be paused. */ modifier whenNotPaused() { require(!paused(), "Pausable: paused"); _; } /** * @dev Modifier to make a function callable only when the contract is paused. * * Requirements: * * - The contract must be paused. */ modifier whenPaused() { require(paused(), "Pausable: not paused"); _; } /** * @dev Triggers stopped state. * * Requirements: * * - The contract must not be paused. */ function _pause() internal virtual whenNotPaused { _paused = true; emit Paused(_msgSender()); } /** * @dev Returns to normal state. * * Requirements: * * - The contract must be paused. */ function _unpause() internal virtual whenPaused { _paused = false; emit Unpaused(_msgSender()); } uint256[49] private __gap; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC721/ERC721.sol) pragma solidity ^0.8.0; import "./IERC721Upgradeable.sol"; import "./IERC721ReceiverUpgradeable.sol"; import "./extensions/IERC721MetadataUpgradeable.sol"; import "../../utils/AddressUpgradeable.sol"; import "../../utils/ContextUpgradeable.sol"; import "../../utils/StringsUpgradeable.sol"; import "../../utils/introspection/ERC165Upgradeable.sol"; import "../../proxy/utils/Initializable.sol"; /** * @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including * the Metadata extension, but not including the Enumerable extension, which is available separately as * {ERC721Enumerable}. */ contract ERC721Upgradeable is Initializable, ContextUpgradeable, ERC165Upgradeable, IERC721Upgradeable, IERC721MetadataUpgradeable { using AddressUpgradeable for address; using StringsUpgradeable for uint256; // Token name string private _name; // Token symbol string private _symbol; // Mapping from token ID to owner address mapping(uint256 => address) private _owners; // Mapping owner address to token count mapping(address => uint256) private _balances; // Mapping from token ID to approved address mapping(uint256 => address) private _tokenApprovals; // Mapping from owner to operator approvals mapping(address => mapping(address => bool)) private _operatorApprovals; /** * @dev Initializes the contract by setting a `name` and a `symbol` to the token collection. */ function __ERC721_init(string memory name_, string memory symbol_) internal onlyInitializing { __Context_init_unchained(); __ERC165_init_unchained(); __ERC721_init_unchained(name_, symbol_); } function __ERC721_init_unchained(string memory name_, string memory symbol_) internal onlyInitializing { _name = name_; _symbol = symbol_; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165Upgradeable, IERC165Upgradeable) returns (bool) { return interfaceId == type(IERC721Upgradeable).interfaceId || interfaceId == type(IERC721MetadataUpgradeable).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) public view virtual override returns (uint256) { require(owner != address(0), "ERC721: balance query for the zero address"); return _balances[owner]; } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view virtual override returns (address) { address owner = _owners[tokenId]; require(owner != address(0), "ERC721: owner query for nonexistent token"); return owner; } /** * @dev See {IERC721Metadata-name}. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev See {IERC721Metadata-symbol}. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); string memory baseURI = _baseURI(); return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : ""; } /** * @dev Base URI for computing {tokenURI}. If set, the resulting URI for each * token will be the concatenation of the `baseURI` and the `tokenId`. Empty * by default, can be overriden in child contracts. */ function _baseURI() internal view virtual returns (string memory) { return ""; } /** * @dev See {IERC721-approve}. */ function approve(address to, uint256 tokenId) public virtual override { address owner = ERC721Upgradeable.ownerOf(tokenId); require(to != owner, "ERC721: approval to current owner"); require( _msgSender() == owner || isApprovedForAll(owner, _msgSender()), "ERC721: approve caller is not owner nor approved for all" ); _approve(to, tokenId); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view virtual override returns (address) { require(_exists(tokenId), "ERC721: approved query for nonexistent token"); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { _setApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC721-isApprovedForAll}. */ function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev See {IERC721-transferFrom}. */ function transferFrom( address from, address to, uint256 tokenId ) public virtual override { //solhint-disable-next-line max-line-length require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _transfer(from, to, tokenId); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId ) public virtual override { safeTransferFrom(from, to, tokenId, ""); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory _data ) public virtual override { require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _safeTransfer(from, to, tokenId, _data); } /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * `_data` is additional data, it has no specified format and it is sent in call to `to`. * * This internal function is equivalent to {safeTransferFrom}, and can be used to e.g. * implement alternative mechanisms to perform token transfer, such as signature-based. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeTransfer( address from, address to, uint256 tokenId, bytes memory _data ) internal virtual { _transfer(from, to, tokenId); require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); } /** * @dev Returns whether `tokenId` exists. * * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}. * * Tokens start existing when they are minted (`_mint`), * and stop existing when they are burned (`_burn`). */ function _exists(uint256 tokenId) internal view virtual returns (bool) { return _owners[tokenId] != address(0); } /** * @dev Returns whether `spender` is allowed to manage `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) { require(_exists(tokenId), "ERC721: operator query for nonexistent token"); address owner = ERC721Upgradeable.ownerOf(tokenId); return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender)); } /** * @dev Safely mints `tokenId` and transfers it to `to`. * * Requirements: * * - `tokenId` must not exist. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeMint(address to, uint256 tokenId) internal virtual { _safeMint(to, tokenId, ""); } /** * @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is * forwarded in {IERC721Receiver-onERC721Received} to contract recipients. */ function _safeMint( address to, uint256 tokenId, bytes memory _data ) internal virtual { _mint(to, tokenId); require( _checkOnERC721Received(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer" ); } /** * @dev Mints `tokenId` and transfers it to `to`. * * WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible * * Requirements: * * - `tokenId` must not exist. * - `to` cannot be the zero address. * * Emits a {Transfer} event. */ function _mint(address to, uint256 tokenId) internal virtual { require(to != address(0), "ERC721: mint to the zero address"); require(!_exists(tokenId), "ERC721: token already minted"); _beforeTokenTransfer(address(0), to, tokenId); _balances[to] += 1; _owners[tokenId] = to; emit Transfer(address(0), to, tokenId); } /** * @dev Destroys `tokenId`. * The approval is cleared when the token is burned. * * Requirements: * * - `tokenId` must exist. * * Emits a {Transfer} event. */ function _burn(uint256 tokenId) internal virtual { address owner = ERC721Upgradeable.ownerOf(tokenId); _beforeTokenTransfer(owner, address(0), tokenId); // Clear approvals _approve(address(0), tokenId); _balances[owner] -= 1; delete _owners[tokenId]; emit Transfer(owner, address(0), tokenId); } /** * @dev Transfers `tokenId` from `from` to `to`. * As opposed to {transferFrom}, this imposes no restrictions on msg.sender. * * Requirements: * * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * * Emits a {Transfer} event. */ function _transfer( address from, address to, uint256 tokenId ) internal virtual { require(ERC721Upgradeable.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own"); require(to != address(0), "ERC721: transfer to the zero address"); _beforeTokenTransfer(from, to, tokenId); // Clear approvals from the previous owner _approve(address(0), tokenId); _balances[from] -= 1; _balances[to] += 1; _owners[tokenId] = to; emit Transfer(from, to, tokenId); } /** * @dev Approve `to` to operate on `tokenId` * * Emits a {Approval} event. */ function _approve(address to, uint256 tokenId) internal virtual { _tokenApprovals[tokenId] = to; emit Approval(ERC721Upgradeable.ownerOf(tokenId), to, tokenId); } /** * @dev Approve `operator` to operate on all of `owner` tokens * * Emits a {ApprovalForAll} event. */ function _setApprovalForAll( address owner, address operator, bool approved ) internal virtual { require(owner != operator, "ERC721: approve to caller"); _operatorApprovals[owner][operator] = approved; emit ApprovalForAll(owner, operator, approved); } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address. * The call is not executed if the target address is not a contract. * * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function _checkOnERC721Received( address from, address to, uint256 tokenId, bytes memory _data ) private returns (bool) { if (to.isContract()) { try IERC721ReceiverUpgradeable(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) { return retval == IERC721ReceiverUpgradeable.onERC721Received.selector; } catch (bytes memory reason) { if (reason.length == 0) { revert("ERC721: transfer to non ERC721Receiver implementer"); } else { assembly { revert(add(32, reason), mload(reason)) } } } } else { return true; } } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual {} uint256[44] private __gap; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.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 IERC721ReceiverUpgradeable { /** * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom} * by `operator` from `from`, this function is called. * * It must return its Solidity selector to confirm the token transfer. * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted. * * The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`. */ function onERC721Received( address operator, address from, uint256 tokenId, bytes calldata data ) external returns (bytes4); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721.sol) pragma solidity ^0.8.0; import "../../utils/introspection/IERC165Upgradeable.sol"; /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721Upgradeable is IERC165Upgradeable { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes calldata data ) external; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/IERC721Metadata.sol) pragma solidity ^0.8.0; import "../IERC721Upgradeable.sol"; /** * @title ERC-721 Non-Fungible Token Standard, optional metadata extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721MetadataUpgradeable is IERC721Upgradeable { /** * @dev Returns the token collection name. */ function name() external view returns (string memory); /** * @dev Returns the token collection symbol. */ function symbol() external view returns (string memory); /** * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token. */ function tokenURI(uint256 tokenId) external view returns (string memory); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/Address.sol) pragma solidity ^0.8.0; /** * @dev Collection of functions related to the address type */ library AddressUpgradeable { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/Context.sol) pragma solidity ^0.8.0; import "../proxy/utils/Initializable.sol"; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract ContextUpgradeable is Initializable { function __Context_init() internal onlyInitializing { __Context_init_unchained(); } function __Context_init_unchained() internal onlyInitializing { } function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } uint256[50] private __gap; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/Counters.sol) pragma solidity ^0.8.0; /** * @title Counters * @author Matt Condon (@shrugs) * @dev Provides counters that can only be incremented, decremented or reset. This can be used e.g. to track the number * of elements in a mapping, issuing ERC721 ids, or counting request ids. * * Include with `using Counters for Counters.Counter;` */ library CountersUpgradeable { struct Counter { // This variable should never be directly accessed by users of the library: interactions must be restricted to // the library's function. As of Solidity v0.5.2, this cannot be enforced, though there is a proposal to add // this feature: see https://github.com/ethereum/solidity/issues/4637 uint256 _value; // default: 0 } function current(Counter storage counter) internal view returns (uint256) { return counter._value; } function increment(Counter storage counter) internal { unchecked { counter._value += 1; } } function decrement(Counter storage counter) internal { uint256 value = counter._value; require(value > 0, "Counter: decrement overflow"); unchecked { counter._value = value - 1; } } function reset(Counter storage counter) internal { counter._value = 0; } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/Strings.sol) pragma solidity ^0.8.0; /** * @dev String operations. */ library StringsUpgradeable { bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef"; /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0x00"; } uint256 temp = value; uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return toHexString(value, length); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = _HEX_SYMBOLS[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/cryptography/ECDSA.sol) pragma solidity ^0.8.0; import "../StringsUpgradeable.sol"; /** * @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 ECDSAUpgradeable { 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", StringsUpgradeable.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)); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol) pragma solidity ^0.8.0; import "./IERC165Upgradeable.sol"; import "../../proxy/utils/Initializable.sol"; /** * @dev Implementation of the {IERC165} interface. * * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check * for the additional interface id that will be supported. For example: * * ```solidity * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId); * } * ``` * * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation. */ abstract contract ERC165Upgradeable is Initializable, IERC165Upgradeable { function __ERC165_init() internal onlyInitializing { __ERC165_init_unchained(); } function __ERC165_init_unchained() internal onlyInitializing { } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165Upgradeable).interfaceId; } uint256[50] private __gap; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol) pragma solidity ^0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165Upgradeable { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/structs/EnumerableSet.sol) pragma solidity ^0.8.0; /** * @dev Library for managing * https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive * types. * * Sets have the following properties: * * - Elements are added, removed, and checked for existence in constant time * (O(1)). * - Elements are enumerated in O(n). No guarantees are made on the ordering. * * ``` * contract Example { * // Add the library methods * using EnumerableSet for EnumerableSet.AddressSet; * * // Declare a set state variable * EnumerableSet.AddressSet private mySet; * } * ``` * * As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`) * and `uint256` (`UintSet`) are supported. */ library EnumerableSetUpgradeable { // To implement this library for multiple types with as little code // repetition as possible, we write it in terms of a generic Set type with // bytes32 values. // The Set implementation uses private functions, and user-facing // implementations (such as AddressSet) are just wrappers around the // underlying Set. // This means that we can only create new EnumerableSets for types that fit // in bytes32. struct Set { // Storage of set values bytes32[] _values; // Position of the value in the `values` array, plus 1 because index 0 // means a value is not in the set. mapping(bytes32 => uint256) _indexes; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function _add(Set storage set, bytes32 value) private returns (bool) { if (!_contains(set, value)) { set._values.push(value); // The value is stored at length-1, but we add 1 to all indexes // and use 0 as a sentinel value set._indexes[value] = set._values.length; return true; } else { return false; } } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function _remove(Set storage set, bytes32 value) private returns (bool) { // We read and store the value's index to prevent multiple reads from the same storage slot uint256 valueIndex = set._indexes[value]; if (valueIndex != 0) { // Equivalent to contains(set, value) // To delete an element from the _values array in O(1), we swap the element to delete with the last one in // the array, and then remove the last element (sometimes called as 'swap and pop'). // This modifies the order of the array, as noted in {at}. uint256 toDeleteIndex = valueIndex - 1; uint256 lastIndex = set._values.length - 1; if (lastIndex != toDeleteIndex) { bytes32 lastvalue = set._values[lastIndex]; // Move the last value to the index where the value to delete is set._values[toDeleteIndex] = lastvalue; // Update the index for the moved value set._indexes[lastvalue] = valueIndex; // Replace lastvalue's index to valueIndex } // Delete the slot where the moved value was stored set._values.pop(); // Delete the index for the deleted slot delete set._indexes[value]; return true; } else { return false; } } /** * @dev Returns true if the value is in the set. O(1). */ function _contains(Set storage set, bytes32 value) private view returns (bool) { return set._indexes[value] != 0; } /** * @dev Returns the number of values on the set. O(1). */ function _length(Set storage set) private view returns (uint256) { return set._values.length; } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function _at(Set storage set, uint256 index) private view returns (bytes32) { return set._values[index]; } /** * @dev Return the entire set in an array * * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that * this function has an unbounded cost, and using it as part of a state-changing function may render the function * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block. */ function _values(Set storage set) private view returns (bytes32[] memory) { return set._values; } // Bytes32Set struct Bytes32Set { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _add(set._inner, value); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _remove(set._inner, value); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) { return _contains(set._inner, value); } /** * @dev Returns the number of values in the set. O(1). */ function length(Bytes32Set storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) { return _at(set._inner, index); } /** * @dev Return the entire set in an array * * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that * this function has an unbounded cost, and using it as part of a state-changing function may render the function * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block. */ function values(Bytes32Set storage set) internal view returns (bytes32[] memory) { return _values(set._inner); } // AddressSet struct AddressSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(AddressSet storage set, address value) internal returns (bool) { return _add(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(AddressSet storage set, address value) internal returns (bool) { return _remove(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(AddressSet storage set, address value) internal view returns (bool) { return _contains(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Returns the number of values in the set. O(1). */ function length(AddressSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(AddressSet storage set, uint256 index) internal view returns (address) { return address(uint160(uint256(_at(set._inner, index)))); } /** * @dev Return the entire set in an array * * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that * this function has an unbounded cost, and using it as part of a state-changing function may render the function * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block. */ function values(AddressSet storage set) internal view returns (address[] memory) { bytes32[] memory store = _values(set._inner); address[] memory result; assembly { result := store } return result; } // UintSet struct UintSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(UintSet storage set, uint256 value) internal returns (bool) { return _add(set._inner, bytes32(value)); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(UintSet storage set, uint256 value) internal returns (bool) { return _remove(set._inner, bytes32(value)); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(UintSet storage set, uint256 value) internal view returns (bool) { return _contains(set._inner, bytes32(value)); } /** * @dev Returns the number of values on the set. O(1). */ function length(UintSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(UintSet storage set, uint256 index) internal view returns (uint256) { return uint256(_at(set._inner, index)); } /** * @dev Return the entire set in an array * * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that * this function has an unbounded cost, and using it as part of a state-changing function may render the function * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block. */ function values(UintSet storage set) internal view returns (uint256[] memory) { bytes32[] memory store = _values(set._inner); uint256[] memory result; assembly { result := store } return result; } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.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/ERC721/IERC721.sol) pragma solidity ^0.8.0; import "../../utils/introspection/IERC165.sol"; /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721 is IERC165 { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes calldata data ) external; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol) pragma solidity ^0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } //SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "@openzeppelin/contracts-upgradeable/security/PausableUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/access/AccessControlEnumerableUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/token/ERC721/ERC721Upgradeable.sol"; import "@openzeppelin/contracts-upgradeable/utils/CountersUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/utils/cryptography/ECDSAUpgradeable.sol"; import "@openzeppelin/contracts/token/ERC721/IERC721.sol"; import "./interfaces/ICandyToken.sol"; contract UninterestedUnicornsV2 is AccessControlEnumerableUpgradeable, PausableUpgradeable, OwnableUpgradeable, ERC721Upgradeable { using CountersUpgradeable for CountersUpgradeable.Counter; using StringsUpgradeable for uint256; using ECDSAUpgradeable for bytes32; struct Parents { uint16 parent_1; uint16 parent_2; } // Stores quantity of UUs left in a season uint256 public QUANTITY_LEFT; // Access bytes32 public constant TREASURY_ROLE = keccak256("TREASURY_ROLE"); bytes32 public constant QUESTING_ROLE = keccak256("QUESTING_ROLE"); // Breeding Information uint256 public BREEDING_COST; // UCD Breeding Cost uint256 public BREEDING_COST_ETH; // ETH Breeding cost uint256[] public BREEDING_DISCOUNT_THRESHOLD; // UCD to hold for discount uint256[] public BREEDING_DISCOUNT_PERC; // UCD to hold for discount // Signers address private BREED_SIGNER; address private WHITELIST_SIGNER; // External Contracts ICandyToken public CANDY_TOKEN; IERC721 public UU; // GNOSIS SAFE address public TREASURY; // Passive Rewards uint256 public REWARDS_PER_DAY; mapping(uint256 => uint256) public lastClaim; // Private Variables CountersUpgradeable.Counter private _tokenIds; string private baseTokenURI; // UU Status mapping(uint256 => bool) private isBred; // Mapping that determines if the UUv1 is Bred // Toggles bool private breedingOpen; bool private presaleOpen; bool private publicOpen; // Mint Caps mapping(address => uint8) private privateSaleMintedAmount; mapping(address => uint8) private publicSaleMintedAmount; // Nonce mapping(bytes => bool) private _nonceUsed; // Parent Mapping mapping(uint256 => Parents) private _parents; // Reserve Storage (important: New variables should be declared below) uint256 private maxPerTransactionPrivate; uint256 private maxPerTransactionPublic; uint256 private maxPerWalletPrivate; uint256 private maxPerWalletPublic; uint256[46] private ______gap; // ------------------------ EVENTS ---------------------------- event Minted(address indexed minter, uint256 indexed tokenId); event Breed( address indexed minter, uint256 tokenId, uint256 parent_1_tokenId, uint256 parent_2_tokenId ); event RewardsClaimed( address indexed user, uint256 tokenId, uint256 amount, uint256 timestamp ); // ---------------------- MODIFIERS --------------------------- /// @dev Only EOA modifier modifier onlyEOA() { require(msg.sender == tx.origin, "UUv2: Only EOA"); _; } function __UUv2_init( address owner, address _treasury, address _breedSigner, address _whitelistSigner ) public initializer { __Context_init_unchained(); __ERC165_init_unchained(); __ERC721_init_unchained("UninterestedUnicornsV2", "UUv2"); __Ownable_init_unchained(); __AccessControl_init_unchained(); __AccessControlEnumerable_init_unchained(); __Pausable_init_unchained(); transferOwnership(owner); TREASURY = _treasury; REWARDS_PER_DAY = 2 ether; BREEDING_COST = 1000 ether; BREEDING_COST_ETH = 0.1 ether; BREEDING_DISCOUNT_THRESHOLD = [10000 ether, 5000 ether]; BREEDING_DISCOUNT_PERC = [75, 90]; // Percentage Discount BREED_SIGNER = _breedSigner; WHITELIST_SIGNER = _whitelistSigner; QUANTITY_LEFT = 5000; _setupRole(DEFAULT_ADMIN_ROLE, _msgSender()); // To revoke access after deployment grantRole(DEFAULT_ADMIN_ROLE, TREASURY); _setBaseURI( "https://lit-island-00614.herokuapp.com/api/v1/uuv2/chromosomes/" ); } // ------------------------- USER FUNCTION --------------------------- /// @dev Takes the input of 2 genesis UU ids and breed them together /// @dev Ownership verication is done off-chain and signed by BREED_SIGNER function breed( uint16 parent_1_tokenId, uint16 parent_2_tokenId, bytes memory nonce, bytes memory signature ) public { require( breedSigned( msg.sender, nonce, signature, parent_1_tokenId, parent_2_tokenId ), "UUv2: Invalid Signature" ); require(isBreedingOpen(), "UUv2: Breeding is not open"); require( CANDY_TOKEN.balanceOf(msg.sender) >= BREEDING_COST, "UUv2: Insufficient UCD for breeding" ); require(QUANTITY_LEFT != 0, "UUv2: No more UUs available"); require( !isBred[parent_1_tokenId] && !isBred[parent_2_tokenId], "UUv2: UUs have been bred before!" ); // Reduce Quantity Left QUANTITY_LEFT -= 1; // Increase Token ID _tokenIds.increment(); isBred[parent_1_tokenId] = true; isBred[parent_2_tokenId] = true; // Burn UCD Token CANDY_TOKEN.burn(msg.sender, BREEDING_COST); // Store Parent Id _parents[_tokenIds.current()] = Parents( parent_1_tokenId, parent_2_tokenId ); // Set Last Claim lastClaim[_tokenIds.current()] = block.timestamp; // Mint _mint(msg.sender, _tokenIds.current()); emit Breed( _msgSender(), _tokenIds.current(), parent_1_tokenId, parent_2_tokenId ); } /// @dev Mint a random UUv2. Whitelisted addresses only /// @dev Whitelist is done off-chain and signed by WHITELIST_SIGNER function whitelistMint( uint8 _amount, bytes memory nonce, bytes memory signature ) public payable onlyEOA { require(isPresaleOpen(), "UUv2: Presale Mint not open!"); require(!_nonceUsed[nonce], "UUv2: Nonce was used"); require( whitelistSigned(msg.sender, nonce, signature), "UUv2: Invalid signature" ); // Max 2 Per TX require( _amount <= maxPerTransactionPrivate, "UUv2: Mint Per Transaction Exceeded!" ); // Max 2 Per Presale require( privateSaleMintedAmount[msg.sender] + _amount <= maxPerWalletPrivate, "UUv2: Presale Limit Exceeded!" ); // Increase private sale amount privateSaleMintedAmount[msg.sender] += _amount; require( msg.value == getETHPrice(msg.sender) * _amount, "UUv2: Insufficient ETH!" ); // Check Quantity require(QUANTITY_LEFT - _amount != 0, "UUv2: No more UUs available"); // Reduce Quantity QUANTITY_LEFT -= _amount; for (uint8 i; i < _amount; i++) { _tokenIds.increment(); // Set Last Claim lastClaim[_tokenIds.current()] = block.timestamp; _mint(msg.sender, _tokenIds.current()); } (bool success, ) = TREASURY.call{value: msg.value}(""); // forward amount to treasury wallet require(success, "UUv2: Unable to forward message to treasury!"); } /// @dev Mint a random UUv2 function mint(uint8 _amount) public payable onlyEOA { require(isPublicOpen(), "UUv2: Public Mint not open!"); require( _amount <= maxPerTransactionPublic, "UUv2: Maximum of 5 mints per transaction!" ); require( publicSaleMintedAmount[msg.sender] + _amount <= maxPerWalletPublic, "UUv2: Public Limit Exceeded!" ); publicSaleMintedAmount[msg.sender] += _amount; require( msg.value == getETHPrice(msg.sender) * _amount, "UUv2: Insufficient ETH!" ); // Check Quantity require(QUANTITY_LEFT - _amount != 0, "UUv2: No more UUs available"); // Reduce Quantity QUANTITY_LEFT -= _amount; for (uint8 i; i < _amount; i++) { _tokenIds.increment(); // Set Last Claim lastClaim[_tokenIds.current()] = block.timestamp; _mint(msg.sender, _tokenIds.current()); } (bool success, ) = TREASURY.call{value: msg.value}(""); // forward amount to treasury wallet require(success, "UUv2: Unable to forward message to treasury!"); } /// @dev Mint a random UUv2 using UCD. Whitelisted addresses only /// @dev Whitelist is done off-chain and signed by WHITELIST_SIGNER function UCDwhitelistMint( uint8 _amount, bytes memory nonce, bytes memory signature ) public onlyEOA { require(isPresaleOpen(), "UUv2: Presale Mint not open!"); require(!_nonceUsed[nonce], "UUv2: Nonce was used"); require( whitelistSigned(msg.sender, nonce, signature), "UUv2: Invalid signature" ); // Max 2 Per TX require( _amount <= maxPerTransactionPrivate, "UUv2: Mint Per Transaction Exceeded!" ); // Max 2 Per Presale require( privateSaleMintedAmount[msg.sender] + _amount <= maxPerWalletPrivate, "UUv2: Presale Limit Exceeded!" ); // Increase private sale amount privateSaleMintedAmount[msg.sender] += _amount; require( CANDY_TOKEN.balanceOf(msg.sender) >= BREEDING_COST * _amount, "UUv2: Insufficient UCD for minting" ); // Check Quantity require(QUANTITY_LEFT - _amount != 0, "UUv2: No more UUs available"); // Reduce Quantity QUANTITY_LEFT -= _amount; // Burn UCD Token CANDY_TOKEN.burn(msg.sender, BREEDING_COST * _amount); for (uint8 i; i < _amount; i++) { _tokenIds.increment(); // Set Last Claim lastClaim[_tokenIds.current()] = block.timestamp; _mint(msg.sender, _tokenIds.current()); } } /// @dev Mint a random UUv2v using UCD function UCDmint(uint8 _amount) public payable onlyEOA { require(isPublicOpen(), "UUv2: Public Mint not open!"); require(_amount != 0, "UUv2: Amount must not be 0!"); require( _amount <= maxPerTransactionPublic, "UUv2: Maximum of 5 mints per transaction!" ); require( publicSaleMintedAmount[msg.sender] + _amount < maxPerWalletPublic, "UUv2: Public Limit Exceeded!" ); publicSaleMintedAmount[msg.sender] += _amount; require( CANDY_TOKEN.balanceOf(msg.sender) >= BREEDING_COST * _amount, "UUv2: Insufficient UCD for breeding" ); // Check Quantity require(QUANTITY_LEFT - _amount != 0, "UUv2: No more UUs available"); // Reduce Quantity QUANTITY_LEFT -= _amount; // Burn UCD Token CANDY_TOKEN.burn(msg.sender, BREEDING_COST * _amount); for (uint8 i; i < _amount; i++) { _tokenIds.increment(); // Set Last Claim lastClaim[_tokenIds.current()] = block.timestamp; _mint(msg.sender, _tokenIds.current()); } } /// @dev Allow UUv2 Holders to claim UCD Rewards function claimRewards(uint256 tokenId) public { require(isPresaleOpen() && isPublicOpen(), "UUv2: Claiming not Open"); require( ownerOf(tokenId) == msg.sender, "UUv2: Claimant is not the owner!" ); uint256 amount = calculateRewards(tokenId); // Update Last Claim lastClaim[tokenId] = block.timestamp; CANDY_TOKEN.mint(msg.sender, amount); emit RewardsClaimed(msg.sender, tokenId, amount, block.timestamp); } /// @dev Allow UUv2 Holders to claim UCD Rewards for a array of tokens function claimRewardsMultiple(uint256[] memory tokenIds) public { require(isPresaleOpen() && isPublicOpen(), "UUv2: Claiming not Open"); uint256 amount = 0; // Store total amount // Update Last Claim for (uint256 i = 0; i < tokenIds.length; i++) { require( ownerOf(tokenIds[i]) == msg.sender, "UUv2: Claimant is not the owner!" ); uint256 claimAmount = calculateRewards(tokenIds[i]); amount += claimAmount; lastClaim[tokenIds[i]] = block.timestamp; emit RewardsClaimed( msg.sender, tokenIds[i], claimAmount, block.timestamp ); } // Claim all tokens in 1 transaction CANDY_TOKEN.mint(msg.sender, amount); } // --------------------- VIEW FUNCTIONS --------------------- /// @dev Determines if UU has already been used for breeding function canBreed(uint256 tokenId) public view returns (bool) { return !isBred[tokenId]; } function getLastClaim(uint256 tokenId) public view returns (uint256) { return lastClaim[tokenId]; } /** * @dev Get Token URI Concatenated with Base URI */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require( _exists(tokenId), "ERC721URIStorage: URI query for nonexistent token" ); string memory currentBaseURI = _baseURI(); return bytes(currentBaseURI).length > 0 ? string(abi.encodePacked(currentBaseURI, tokenId.toString())) : ""; } /// @dev Get ETH Mint Price. Discounts are calculated here. function getETHPrice(address _user) public view returns (uint256) { uint256 discount; if (CANDY_TOKEN.balanceOf(_user) >= BREEDING_DISCOUNT_THRESHOLD[0]) { discount = BREEDING_DISCOUNT_PERC[0]; } else if ( CANDY_TOKEN.balanceOf(_user) >= BREEDING_DISCOUNT_THRESHOLD[1] ) { discount = BREEDING_DISCOUNT_PERC[1]; } else { discount = 100; } return (BREEDING_COST_ETH * discount) / 100; } /// @dev Get UCD cost for breeding function getUCDPrice() public view returns (uint256) { return BREEDING_COST; } /// @dev Determine if breeding is open function isBreedingOpen() public view returns (bool) { return breedingOpen; } /// @dev Determine if pre-sale is open function isPresaleOpen() public view returns (bool) { return presaleOpen; } /// @dev Determine if public sale is open function isPublicOpen() public view returns (bool) { return publicOpen; } function supportsInterface(bytes4 interfaceId) public view virtual override(AccessControlEnumerableUpgradeable, ERC721Upgradeable) returns (bool) { return super.supportsInterface(interfaceId); } function getParents(uint256 tokenId) public view returns (Parents memory) { return _parents[tokenId]; } // ----------------------- CALCULATION FUNCTIONS ---------------------- /// @dev Checks if the the signature is signed by a valid signer for breeding function breedSigned( address sender, bytes memory nonce, bytes memory signature, uint256 parent_1_id, uint256 parent_2_id ) private view returns (bool) { bytes32 hash = keccak256( abi.encodePacked(sender, nonce, parent_1_id, parent_2_id) ); return BREED_SIGNER == hash.recover(signature); } /// @dev Checks if the the signature is signed by a valid signer for whitelists function whitelistSigned( address sender, bytes memory nonce, bytes memory signature ) private view returns (bool) { bytes32 hash = keccak256(abi.encodePacked(sender, nonce)); return WHITELIST_SIGNER == hash.recover(signature); } /// @dev Calculates the amount of UCD that can be claimed function calculateRewards(uint256 tokenId) public view returns (uint256 rewardAmount) { rewardAmount = ((REWARDS_PER_DAY) * (block.timestamp - getLastClaim(tokenId))) / (1 days); } /** @dev Calculates the amount of UCD that can be claimed for multiple tokens @notice Since ERC721Enumerable is not used, we must get the tokenIds owned by the user off-chain using Moralis. */ function calculateRewardsMulti(uint256[] memory tokenIds) public view returns (uint256 rewardAmount) { for (uint256 i; i < tokenIds.length; i++) { rewardAmount += calculateRewards(tokenIds[i]); } } // ---------------------- ADMIN FUNCTIONS ----------------------- /// @dev Airdrop UUv2 to addresses function airdrop(address[] memory addresses) public onlyRole(DEFAULT_ADMIN_ROLE) { require( QUANTITY_LEFT >= addresses.length, "UUv2: No more UUs available" ); QUANTITY_LEFT -= addresses.length; for (uint256 i; i < addresses.length; i++) { _tokenIds.increment(); // Set Last Claim lastClaim[_tokenIds.current()] = block.timestamp; _mint(addresses[i], _tokenIds.current()); } } /// @dev Set UCD Contract function setCandyToken(address _addr) public onlyRole(DEFAULT_ADMIN_ROLE) { CANDY_TOKEN = ICandyToken(_addr); } /// @dev Set Genesis UU Contract function setUU(address _addr) public onlyRole(DEFAULT_ADMIN_ROLE) { UU = IERC721(_addr); } /// @dev Set Quantity of mints/breeds left function setQuantity(uint256 _amount) public onlyRole(DEFAULT_ADMIN_ROLE) { QUANTITY_LEFT = _amount; } /// @dev Set Rewards per day for holding UU function setRewardsPerDay(uint256 _amount) public onlyRole(DEFAULT_ADMIN_ROLE) { REWARDS_PER_DAY = _amount; } /// @dev Set Breeding Cost function setBreedingCost(uint256 _amount) public onlyRole(DEFAULT_ADMIN_ROLE) { BREEDING_COST = _amount; } /// @dev Set Mint Cost function setMintCost(uint256 _amount) public onlyRole(DEFAULT_ADMIN_ROLE) { BREEDING_COST_ETH = _amount; } /// @dev Set maxPerTransactionPrivate function setMaxPerTransactionPrivate(uint256 _amount) public onlyRole(DEFAULT_ADMIN_ROLE) { maxPerTransactionPrivate = _amount; } /// @dev Set maxPerTransactionPublic function setMaxPerTransactionPublic(uint256 _amount) public onlyRole(DEFAULT_ADMIN_ROLE) { maxPerTransactionPublic = _amount; } /// @dev Set maxPerWalletPrivate function setMaxPerWalletPrivate(uint256 _amount) public onlyRole(DEFAULT_ADMIN_ROLE) { maxPerWalletPrivate = _amount; } /// @dev Set maxPerWalletPublic function setMaxPerWalletPublic(uint256 _amount) public onlyRole(DEFAULT_ADMIN_ROLE) { maxPerWalletPublic = _amount; } /// @dev Update token metadata baseURI function updateBaseURI(string memory newURI) public onlyRole(DEFAULT_ADMIN_ROLE) { _setBaseURI(newURI); } /// @dev Toggle Breeding Open function toggleBreeding() public onlyRole(DEFAULT_ADMIN_ROLE) { breedingOpen = !breedingOpen; } /// @dev Toggle Presale Open function togglePresale() public onlyRole(DEFAULT_ADMIN_ROLE) { presaleOpen = !presaleOpen; } /// @dev Toggle Public Open function togglePublicSale() public onlyRole(DEFAULT_ADMIN_ROLE) { publicOpen = !publicOpen; } /// @dev Pauses all token transfers. function pause() public virtual onlyRole(DEFAULT_ADMIN_ROLE) { _pause(); } /// @dev Unpauses all token transfers. function unpause() public virtual onlyRole(DEFAULT_ADMIN_ROLE) { _unpause(); } // --------------------- INTERNAL FUNCTIONS --------------------- /// @dev Set Base URI internal function function _setBaseURI(string memory _baseTokenURI) internal virtual { baseTokenURI = _baseTokenURI; } /// @dev Gets baseToken URI function _baseURI() internal view override returns (string memory) { return baseTokenURI; } function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual override(ERC721Upgradeable) whenNotPaused { super._beforeTokenTransfer(from, to, tokenId); } } //SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; interface ICandyToken is IERC20 { function updateRewardOnMint(address _user, uint256 _amount) external; function updateReward(address _from, address _to) external; function getReward(address _to) external; function burn(address _from, uint256 _amount) external; function mint(address to, uint256 amount) external; function getTotalClaimable(address _user) external view returns (uint256); }
Mint a random UUv2 using UCD. Whitelisted addresses only Whitelist is done off-chain and signed by WHITELIST_SIGNER Max 2 Per TX Max 2 Per Presale Increase private sale amount Check Quantity Reduce Quantity Burn UCD Token Set Last Claim
function UCDwhitelistMint( uint8 _amount, bytes memory nonce, bytes memory signature ) public onlyEOA { require(isPresaleOpen(), "UUv2: Presale Mint not open!"); require(!_nonceUsed[nonce], "UUv2: Nonce was used"); require( whitelistSigned(msg.sender, nonce, signature), "UUv2: Invalid signature" ); require( _amount <= maxPerTransactionPrivate, "UUv2: Mint Per Transaction Exceeded!" ); require( privateSaleMintedAmount[msg.sender] + _amount <= maxPerWalletPrivate, "UUv2: Presale Limit Exceeded!" ); privateSaleMintedAmount[msg.sender] += _amount; require( CANDY_TOKEN.balanceOf(msg.sender) >= BREEDING_COST * _amount, "UUv2: Insufficient UCD for minting" ); require(QUANTITY_LEFT - _amount != 0, "UUv2: No more UUs available"); QUANTITY_LEFT -= _amount; CANDY_TOKEN.burn(msg.sender, BREEDING_COST * _amount); for (uint8 i; i < _amount; i++) { _tokenIds.increment(); lastClaim[_tokenIds.current()] = block.timestamp; _mint(msg.sender, _tokenIds.current()); } }
13,528,775
// SPDX-License-Identifier: MIT pragma solidity 0.7.6; pragma abicoder v2; import "../../../commons/solidity-utils/chainlink/ChainlinkClient.sol"; import "../../../commons/solidity-utils/misc/BokkyPooBahsDateTimeLibrary.sol"; import "../../../commons/solidity-utils/misc/StringConvertor.sol"; import "../../../commons/solidity-utils/openzeppelin/utils/EnumerableSetUpgradeable.sol"; import "../interface/IPriceOracle.sol"; contract ChainlinkPriceOracle is IPriceOracle, ChainlinkClient { using StringConvertor for uint256; using StringConvertor for bytes; using StringConvertor for address; using BokkyPooBahsDateTimeLibrary for uint256; using Chainlink for Chainlink.Request; struct Request { address underlying; bytes32 dateSignature; } event NewAdmin( address oldAdmin, address newAdmin ); event NewPendingAdmin( address oldPendingAdmin, address newPendingAdmin ); event SetPriceOracleManager( address oldPriceOracleManager, address newPriceOracleManager ); event SetJobId( bytes32 oldJobId, bytes32 newJobId ); event SetOraclePayment( uint256 oldOraclePayment, uint256 newOraclePayment ); event SetTokenId( address underlying, uint256 tokenId ); event RefreshPrice( address underlying, uint64 fromDate, uint64 toDate, bytes32 requestId ); address public admin; address public pendingAdmin; address public priceOracleManager; //underlying => datesig => price mapping(address => mapping(bytes32 => int256)) public prices; //underlying => cmc token id mapping(address => uint256) public tokenIds; //requestId => Request mapping(bytes32 => Request) public requests; bytes32 public JOB_ID; uint256 public oraclePayment; modifier onlyAdmin() { require(msg.sender == admin, "only admin"); _; } modifier onlyPriceOracleManager() { require(msg.sender == priceOracleManager, "only priceOracleManager"); _; } constructor(bytes32 jobId_, uint256 oraclePayment_) { JOB_ID = jobId_; admin = msg.sender; oraclePayment = oraclePayment_; } function refreshPrice( address underlying_, uint64 fromDate_, uint64 toDate_ ) external override onlyPriceOracleManager { require(block.timestamp > toDate_, "premature"); string memory fromDate = _getDateString(fromDate_); string memory toDate = _getDateString(toDate_); bytes32 dateSignature = _getDateSignature(fromDate, toDate); require(prices[underlying_][dateSignature] != 0, "already refreshed"); bytes32 requestId = _requestChainlinkOracle( underlying_, fromDate, toDate ); requests[requestId] = Request({ underlying: underlying_, dateSignature: _getDateSignature(fromDate, toDate) }); emit RefreshPrice(underlying_, fromDate_, toDate_, requestId); } function getPrice( address underlying_, uint64 fromDate_, uint64 toDate_ ) external view override returns (int256) { string memory fromDate = _getDateString(fromDate_); string memory toDate = _getDateString(toDate_); bytes32 dateSignature = _getDateSignature(fromDate, toDate); return prices[underlying_][dateSignature]; } function _getDateString(uint64 date_) internal pure returns (string memory) { uint256 year = uint256(date_).getYear(); uint256 month = uint256(date_).getMonth(); uint256 day = uint256(date_).getDay(); return string(abi.encodePacked(year, "-", month, "-", day)); } function _requestChainlinkOracle( address underlying_, string memory fromDate_, string memory toDate_ ) internal returns (bytes32 requestId) { Chainlink.Request memory req = buildChainlinkRequest( JOB_ID, address(this), this.fulfill.selector ); uint256 tokenId = tokenIds[underlying_]; require(tokenId > 0, "invalid underlying"); req.addUint("tokenId", tokenId); req.add("from", fromDate_); req.add("to", toDate_); requestId = sendChainlinkRequest(req, oraclePayment); } function _getDateSignature(string memory fromDate_, string memory toDate_) internal pure returns (bytes32) { return keccak256(abi.encodePacked(fromDate_, toDate_)); } function fulfill(bytes32 requestId_, uint256 value_) public recordChainlinkFulfillment(requestId_) { Request memory request = requests[requestId_]; require(request.underlying != address(0), "invalid request"); prices[request.underlying][request.dateSignature] = int256(value_); } function setJobId(bytes32 jobId_) external onlyAdmin { emit SetJobId(JOB_ID, jobId_); JOB_ID = jobId_; } function setOraclePayment(uint256 payment_) external onlyAdmin { emit SetOraclePayment(oraclePayment, payment_); oraclePayment = payment_; } function setTokenId(address underlying_, uint256 tokenId_) external onlyAdmin { tokenIds[underlying_] = tokenId_; emit SetTokenId(underlying_, tokenId_); } function setPriceOracleManager(address manager_) external onlyAdmin { require(manager_ != address(0), "manager can not be 0 address"); emit SetPriceOracleManager(priceOracleManager, manager_); priceOracleManager = manager_; } function setPendingAdmin(address newPendingAdmin) external { require(msg.sender == admin, "only admin"); // Save current value, if any, for inclusion in log address oldPendingAdmin = pendingAdmin; // Store pendingAdmin with value newPendingAdmin pendingAdmin = newPendingAdmin; // Emit NewPendingAdmin(oldPendingAdmin, newPendingAdmin) emit NewPendingAdmin(oldPendingAdmin, newPendingAdmin); } function acceptAdmin() external { require( msg.sender == pendingAdmin && msg.sender != address(0), "only pending admin" ); // Save current values for inclusion in log address oldAdmin = admin; address oldPendingAdmin = pendingAdmin; // Store admin with value pendingAdmin admin = pendingAdmin; // Clear the pending value pendingAdmin = address(0); emit NewAdmin(oldAdmin, admin); emit NewPendingAdmin(oldPendingAdmin, pendingAdmin); } }
Save current value, if any, for inclusion in log Store pendingAdmin with value newPendingAdmin Emit NewPendingAdmin(oldPendingAdmin, newPendingAdmin)
function setPendingAdmin(address newPendingAdmin) external { require(msg.sender == admin, "only admin"); address oldPendingAdmin = pendingAdmin; pendingAdmin = newPendingAdmin; emit NewPendingAdmin(oldPendingAdmin, newPendingAdmin); }
1,822,662
pragma solidity >=0.4.22 <0.6.0; contract Broadcaster { event Broadcast( string _value ); function broadcast(string memory message) public { // Events are emitted using `emit`, followed by // the name of the event and the arguments // (if any) in parentheses. Any such invocation // (even deeply nested) can be detected from // the JavaScript API by filtering for `Deposit`. emit Broadcast(message); } }
Events are emitted using `emit`, followed by the name of the event and the arguments (if any) in parentheses. Any such invocation (even deeply nested) can be detected from the JavaScript API by filtering for `Deposit`.
function broadcast(string memory message) public { emit Broadcast(message); }
12,625,383
pragma solidity ^0.4.24; contract ERC20 { function totalSupply() public constant returns (uint _totalSupply); function balanceOf(address _owner) public constant returns (uint balance); function transfer(address _to, uint _value) public returns (bool success); function transferFrom(address _from, address _to, uint _value) public returns (bool success); function approve(address _spender, uint _value) public returns (bool success); function allowance(address _owner, address _spender) public constant returns (uint remaining); event Transfer(address indexed _from, address indexed _to, uint _value); event Approval(address indexed _owner, address indexed _spender, uint _value); } contract StibcoMultiSigWallet { address public newownerinsteadofoldowner; address public oldownertoreplace; address public sendto; address public d; address public contractaddress; address public tokensaddress; uint public votestoreplace; uint public votestosend; uint public initiatereplacevote; uint public initiatesendtoevote; uint public amounttosend; uint public areownerscreated; uint public totalowners; uint public isethsent; uint public istokensent; uint public sendwithhex; uint public theFunction; uint public depositype; uint public a; uint public b; uint public c; uint public e; uint public f; uint public g; mapping (address => uint) public ownerbyvotetoreplace; mapping (address => uint) public ownerbyvotetosend; mapping (address => address) public ownerbyaddress; mapping (uint => address) public ownerbyid; modifier ownersrestricted() { require(ownerbyaddress[msg.sender] == msg.sender); _; } //allows other contracts to send to this contract function () payable public { } function CreateOwners(address zinititalowner,address zownertwo, address zownerthree,address zownerfour,address zownerfive) public payable { require(areownerscreated == 0); areownerscreated = 1; totalowners = 5; ownerbyaddress[zinititalowner] = zinititalowner; ownerbyaddress[zownertwo] = zownertwo; ownerbyaddress[zownerthree] = zownerthree; ownerbyaddress[zownerfour] = zownerfour; ownerbyaddress[zownerfive] = zownerfive; ownerbyid[1] = zinititalowner; ownerbyid[2] = zownertwo; ownerbyid[3] = zownerthree; ownerbyid[4] = zownerfour; ownerbyid[5] = zownerfive; contractaddress = address(this); } function initiateReplaceOwner(address theNewOwner,address theOldOwner) ownersrestricted public payable { require(theOldOwner != msg.sender && theNewOwner != msg.sender && totalowners == 5 && initiatereplacevote == 0 && initiatesendtoevote == 0); newownerinsteadofoldowner = theNewOwner; oldownertoreplace = theOldOwner; initiatereplacevote = 1; ownerbyvotetoreplace[msg.sender] = 1; votestoreplace = votestoreplace + 1; } function VoteToReplaceOwner() ownersrestricted public payable { require(initiatereplacevote == 1 && totalowners == 5 && oldownertoreplace != msg.sender && ownerbyvotetoreplace[msg.sender] == 0 && initiatesendtoevote == 0); ownerbyvotetoreplace[msg.sender] = 1; votestoreplace = votestoreplace + 1; if(votestoreplace == 3){ delete ownerbyvotetoreplace[oldownertoreplace]; delete ownerbyvotetosend[oldownertoreplace]; delete ownerbyaddress[oldownertoreplace]; ownerbyvotetosend[newownerinsteadofoldowner] = 0; ownerbyvotetoreplace[newownerinsteadofoldowner] = 0; if(ownerbyid[1] == oldownertoreplace) { ownerbyid[1] = newownerinsteadofoldowner; } else if (ownerbyid[2] == oldownertoreplace) { ownerbyid[2] = newownerinsteadofoldowner; } else if (ownerbyid[3] == oldownertoreplace) { ownerbyid[3] = newownerinsteadofoldowner; } else if (ownerbyid[4] == oldownertoreplace) { ownerbyid[4] = newownerinsteadofoldowner; } else if (ownerbyid[5] == oldownertoreplace) { ownerbyid[5] = newownerinsteadofoldowner; } ownerbyvotetoreplace[ownerbyid[1]] = 0; ownerbyvotetoreplace[ownerbyid[2]] = 0; ownerbyvotetoreplace[ownerbyid[3]] = 0; ownerbyvotetoreplace[ownerbyid[4]] = 0; ownerbyvotetoreplace[ownerbyid[5]] = 0; votestoreplace = 0; initiatereplacevote = 0; } } function initiateSendTransaction(address SendTo,uint ztheFunction,uint amount ,uint zsendwithhex,address tokensaddr,uint dtype) ownersrestricted public payable { require(totalowners == 5 && initiatereplacevote == 0 && initiatesendtoevote == 0 && address(this).balance >= amount ); if(zsendwithhex == 1){ theFunction = ztheFunction; sendwithhex = zsendwithhex; } sendto = SendTo; amounttosend = amount; tokensaddress = tokensaddr; depositype = dtype; votestosend = 1; initiatesendtoevote = 1; ownerbyvotetosend[msg.sender] = 1; } function setCallContractValues(uint thea,uint theb,uint thec,address thed,uint thee,uint thef,uint theg) ownersrestricted public payable{ a = thea; b = theb; c = thec; d = thed; e = thee; f = thef; g = theg; } function VoteToSend() ownersrestricted public payable { require(initiatereplacevote == 0 && totalowners == 5 && initiatesendtoevote == 1 && ownerbyvotetosend[msg.sender] == 0); votestosend = votestosend + 1; ownerbyvotetosend[msg.sender] = 1; if(votestosend == 3){ //here send eth with hex test (dangerous don't use on contract unknown or not verified) if(sendwithhex == 1){ sendto.transfer(amounttosend); if(theFunction == 1) { //create stibco on trade contract ok if(!sendto.call(abi.encodeWithSignature("CreateStibco()"))){ revert(); } } else if (theFunction == 2) { //set settings trade contract ok if(!sendto.call(abi.encodeWithSignature("StibcoFee(uint256,uint256,uint256,address,uint256,uint256,uint256)",a,b,c,d,e,f,g))){ revert(); } } else if (theFunction == 3) { //set settings loans contract ok if(!sendto.call(abi.encodeWithSignature("StibcoFee(uint256,uint256,uint256,address,uint256,uint256)",a,b,c,d,e,f))){ revert(); } } else if (theFunction == 4) { //collect fees contract if(!sendto.call(abi.encodeWithSignature("StiboCollectFee()"))){ revert(); } } else if (theFunction == 5) { //trade dispute select seller as winner if(!sendto.call(abi.encodeWithSignature("DisputeSellerWins(uint256)",a))){ revert(); } } else if (theFunction == 6) { //trade dispute select buyer as winner if(!sendto.call(abi.encodeWithSignature("DisputeBuyerWins(uint256)",a))){ revert(); } } else if (theFunction == 7) { //loans dispute select lender as winner if(!sendto.call(abi.encodeWithSignature("DisputeLenderWins(uint256)",a))){ revert(); } } else if (theFunction == 8) { //loans dispute select borrower as winner if(!sendto.call(abi.encodeWithSignature("DisputeBorrowerWins(uint256)",a))){ revert(); } } else if (theFunction == 9) { //tokens trade set settings if(!sendto.call(abi.encodeWithSignature("StibcoFee(uint256,address,uint256,uint256,uint256)",a,d,c,b,e))){ revert(); } } else if (theFunction == 10) { //tokens loans set settings if(!sendto.call(abi.encodeWithSignature("StibcoFee(uint256,address,uint256,uint256)",a,d,c,b))){ revert(); } } else if (theFunction == 11) { //trade tokens dispute select seller as winner if(!sendto.call(abi.encodeWithSignature("DisputeSellerWins(uint256,address)",a,d))){ revert(); } } else if (theFunction == 12) { //trade tokens dispute select buyer as winner if(!sendto.call(abi.encodeWithSignature("DisputeBuyerWins(uint256,address)",a,d))){ revert(); } } else if (theFunction == 13) { //loans tokens dispute select lender as winner if(!sendto.call(abi.encodeWithSignature("DisputeLenderWins(address,uint256)",d,a))){ revert(); } } else if (theFunction == 14) { //loans tokens dispute select borrower as winner if(!sendto.call(abi.encodeWithSignature("DisputeBorrowerWins(address,uint256)",d,a))){ revert(); } } else if (theFunction == 15) { //add tokens,remove tokens , here will have to delegate if(!sendto.call(abi.encodeWithSignature("Delegate(address)",d))){ revert(); } } else if (theFunction == 16) { //set fee for instant swaps if(!sendto.call(abi.encodeWithSignature("StibcoFee(uint,uint,uint,address)",a,b,c,d))){ revert(); } } }else{ if(depositype == 1){ sendto.transfer(amounttosend); isethsent = 1; }else{ //here we send tokens out ERC20(tokensaddress).transfer(sendto,amounttosend); istokensent = 1; } } ownerbyvotetosend[ownerbyid[1]] = 0; ownerbyvotetosend[ownerbyid[2]] = 0; ownerbyvotetosend[ownerbyid[3]] = 0; ownerbyvotetosend[ownerbyid[4]] = 0; ownerbyvotetosend[ownerbyid[5]] = 0; votestosend = 0; initiatesendtoevote = 0; } } function GetFunctionData() public view returns (uint,uint,uint,address,uint,uint,uint) { return ( a, b, c, d, e, f, g ); } function GetWalletData() public view returns (address,address,address,address,address,address,uint,uint,uint,address,address,address,uint,uint) { return ( contractaddress, ownerbyid[1], ownerbyid[2], ownerbyid[3], ownerbyid[4], ownerbyid[5], amounttosend, votestosend, votestoreplace, sendto, newownerinsteadofoldowner, oldownertoreplace, sendwithhex, theFunction ); } function GetWalletDataTwo() public view returns (address,uint,uint) { return ( tokensaddress, depositype, istokensent ); } function GetBalance() public view returns (uint){ return address(this).balance; } //gets contract tokens balance function getTokenBalance(address tokensadd) public view returns (uint) { return ERC20(tokensadd).balanceOf(address(this)); } //deposit token or eth function Deposit(address tokensadd,uint amount,uint deposittype) public payable { if(deposittype == 1){ ERC20(tokensadd).transferFrom(msg.sender,contractaddress,amount); }else{ require(amount == msg.value); } } }
gets contract tokens balance
function getTokenBalance(address tokensadd) public view returns (uint) { return ERC20(tokensadd).balanceOf(address(this)); }
6,480,716
//SPDX-License-Identifier: GPL-3.0 pragma solidity ^0.8.0; /// @title Horse Race Simulation /// Simulates a betting situation between 6 horses (players) and pays out /// to a randomly chosen winner. contract HorseRaceSim { // Creates empty list of players and empty value for 'admin' address payable[] public players; address public owner; constructor() { // Makes contract's initializing account, 'admin' owner = msg.sender; } modifier onlyOwner() { // Ensure only owner can call functions with this modifier require(owner == msg.sender, "Only the owner can call that function!"); _; } /// Receive function allows contract to accept 'bets' of 0.1 Ether function enter() external payable { require(msg.value == 0.01 ether , "Bets placed must be of size 0.01 ETH"); // Add sender's address to players list players.push(payable(msg.sender)); } // Allows anyone to query balance of contract function getBalance() public view returns(uint){ return address(this).balance; } // Allows anyone to query number of players in game function getPlayers() public view returns(uint){ return (players.length); } /// WARNING - not for production due to pseudo-random nature of number. function getRandomNumber() internal view returns(uint){ return uint(keccak256(abi.encodePacked(owner, block.timestamp))); } function pickWinner() public onlyOwner { require(players.length == 6 , "This is a 6 horse race. More players needed"); address payable winner; winner = players[getRandomNumber() % players.length]; // 95% balance to winner uint winnings = getBalance() * 95 / 100; // 5% admin fee for owner uint adminFee = getBalance() * 5 / 100; winner.transfer(winnings); payable(owner).transfer( adminFee); resetPlayers(); } function resetPlayers() internal { players = new address payable[](0); } }
Allows anyone to query number of players in game
function getPlayers() public view returns(uint){ return (players.length); }
1,084,988
// SPDX-License-Identifier: UNLICENSED pragma solidity ^0.8.0; import "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol"; import "@uniswap/v2-periphery/contracts/interfaces/IUniswapV2Router02.sol"; import "./CLendingLibrary.sol"; import "./types/CLendingTypes.sol"; /// This contract and its holdings are the property of CORE DAO /// All unintened use is strictly prohibited. contract CLending is OwnableUpgradeable { using CLendingLibrary for IERC20; IERC20 public constant DAI = IERC20(0x6B175474E89094C44Da98b954EedeAC495271d0F); IERC20 public constant CORE_TOKEN = IERC20(0x62359Ed7505Efc61FF1D56fEF82158CcaffA23D7); mapping(address => DebtorSummary) public debtorSummary; mapping(address => uint256) public collaterabilityOfToken; address public coreDAOTreasury; uint256 public yearlyPercentInterest; uint256 public loanDefaultThresholdPercent; /// @dev upfront storage allocation for further upgrades uint256[52] private _____gap; function initialize( address _coreDAOTreasury, IERC20 _daoToken, uint256 _yearlyPercentInterest, uint256 _loanDefaultThresholdPercent ) public initializer { __Ownable_init(); coreDAOTreasury = _coreDAOTreasury; yearlyPercentInterest = _yearlyPercentInterest; loanDefaultThresholdPercent = _loanDefaultThresholdPercent; collaterabilityOfToken[address(CORE_TOKEN)] = 5500; collaterabilityOfToken[address(_daoToken)] = 1; } receive() external payable { revert("ETH is not accepted"); } // It should be noted that this will change everything backwards in time meaning some people might be liquidated right away function changeLoanTerms(uint256 _yearlyPercentInterest, uint256 _loanDefaultThresholdPercent) public onlyOwner { yearlyPercentInterest = _yearlyPercentInterest; loanDefaultThresholdPercent = _loanDefaultThresholdPercent; } function editTokenCollaterability(address token, uint256 newCollaterability) public onlyOwner { collaterabilityOfToken[token] = newCollaterability; } // Repays the loan supplying collateral and not adding it function repayLoan(IERC20 token, uint256 amount) public { DebtorSummary storage userSummaryStorage = debtorSummary[msg.sender]; (uint256 totalDebt, ) = liquidateDeliquent(msg.sender); require(totalDebt > 0, "No debt to repay"); uint256 tokenCollateralAbility = collaterabilityOfToken[address(token)]; require(tokenCollateralAbility > 0, "Not accepted for loan collateral"); uint256 offeredCollateralValue = amount * tokenCollateralAbility; uint256 _accruedInterest = accruedInterest(msg.sender); require(offeredCollateralValue > _accruedInterest, "not enough to pay interest"); // Has to be done because we have to update debt time // Note that acured interest is never bigger than 10% of supplied collateral because of liquidateDeliquent call above if (offeredCollateralValue > totalDebt) { amount = totalDebt / tokenCollateralAbility; userSummaryStorage.amountDAIBorrowed = 0; } else { userSummaryStorage.amountDAIBorrowed = userSummaryStorage.amountDAIBorrowed - offeredCollateralValue + _accruedInterest; // Send the repayment amt updateDebtTime(userSummaryStorage); } token.safeTransferFrom(msg.sender, amount); // Send the accrued interest back to the DAO token.transfer(coreDAOTreasury, _accruedInterest / tokenCollateralAbility); } function _supplyCollateral( DebtorSummary storage userSummaryStorage, address user, IERC20 token, uint256 amount ) private { liquidateDeliquent(user); require(token != DAI, "DAI is not allowed as collateral"); uint256 tokenCollateralAbility = collaterabilityOfToken[address(token)]; require(tokenCollateralAbility != 0, "Not accepted as loan collateral"); token.safeTransferFrom(user, amount); // We pay interest already accrued with the same mechanism as repay fn uint256 _accruedInterest = accruedInterest(user) / tokenCollateralAbility; require(_accruedInterest <= amount, "Not enough to repay interest"); amount = amount - _accruedInterest; // We add collateral into the user struct _addCollateral(userSummaryStorage, token, amount); } function addCollateral(IERC20 token, uint256 amount) public { DebtorSummary storage userSummaryStorage = debtorSummary[msg.sender]; _supplyCollateral(userSummaryStorage, msg.sender, token, amount); updateDebtTime(userSummaryStorage); } function addCollateralAndBorrow( IERC20 tokenCollateral, uint256 amountCollateral, uint256 amountBorrow ) public { DebtorSummary storage userSummaryStorage = debtorSummary[msg.sender]; _supplyCollateral(userSummaryStorage, msg.sender, tokenCollateral, amountCollateral); _borrow(userSummaryStorage, msg.sender, amountBorrow); } function borrow(uint256 amount) public { DebtorSummary storage userSummaryStorage = debtorSummary[msg.sender]; _borrow(userSummaryStorage, msg.sender, amount); } function _borrow( DebtorSummary storage userSummaryStorage, address user, uint256 amountBorrow ) private { uint256 totalDebt = userTotalDebt(user); // This is with interest uint256 totalCollateral = userCollateralValue(user); require(totalDebt <= totalCollateral && !isLiquidable(totalDebt, totalCollateral), "Over debted"); uint256 userRemainingCollateral = totalCollateral - totalDebt; if (amountBorrow > userRemainingCollateral) { uint256 totalBorrowed = totalDebt + amountBorrow; require(totalBorrowed <= totalCollateral, "Too much borrowed"); amountBorrow = totalCollateral - totalBorrowed; } editAmountBorrowed(userSummaryStorage, amountBorrow); DAI.transfer(user, amountBorrow); } function _addCollateral( DebtorSummary storage userSummaryStorage, IERC20 token, uint256 amount ) private { bool alreadySupplied; // Loops over all provided collateral, checks if its there and if it is edit it for (uint256 i = 0; i < userSummaryStorage.collateral.length; i++) { if (userSummaryStorage.collateral[i].collateralAddress == address(token)) { userSummaryStorage.collateral[i].suppliedCollateral = userSummaryStorage.collateral[i].suppliedCollateral + amount; alreadySupplied = true; break; } } // If it has not been already supplied we push it on if (!alreadySupplied) { userSummaryStorage.collateral.push( Collateral({collateralAddress: address(token), suppliedCollateral: amount}) ); } } function isLiquidable(uint256 totalDebt, uint256 totalCollateral) private view returns (bool) { return (totalDebt * loanDefaultThresholdPercent) / 100 > totalCollateral; } // Liquidates people in default function liquidateDeliquent(address user) private returns (uint256 totalDebt, uint256 totalCollateral) { totalDebt = userTotalDebt(user); // This is with interest totalCollateral = userCollateralValue(user); if (isLiquidable(totalDebt, totalCollateral)) { // user is in default, wipe their debt and collateral delete debtorSummary[user]; return (0, 0); } } function reclaimAllCollateral() public { (uint256 totalDebt, uint256 totalCollateral) = liquidateDeliquent(msg.sender); require(totalCollateral > 0, "No collateral to reclaim or collateral liquidated"); require(totalDebt == 0, "Still in debt"); for (uint256 i = 0; i < debtorSummary[msg.sender].collateral.length; i++) { uint256 supplied = debtorSummary[msg.sender].collateral[i].suppliedCollateral; IERC20(debtorSummary[msg.sender].collateral[i].collateralAddress).transfer(msg.sender, supplied); } // User doesnt have collateral anymore and paid off debt, bye delete debtorSummary[msg.sender]; } function userCollateralValue(address user) public view returns (uint256 collateral) { Collateral[] memory userCollateralTokens = debtorSummary[user].collateral; for (uint256 i = 0; i < userCollateralTokens.length; i++) { Collateral memory currentToken = userCollateralTokens[i]; uint256 tokenDebit = collaterabilityOfToken[currentToken.collateralAddress] * currentToken.suppliedCollateral; collateral = collateral + tokenDebit; } } function userTotalDebt(address user) public view returns (uint256) { return accruedInterest(user) + debtorSummary[user].amountDAIBorrowed; } function accruedInterest(address user) public view returns (uint256) { DebtorSummary memory userSummaryMemory = debtorSummary[user]; uint256 timeSinceLastLoan = block.timestamp - userSummaryMemory.timeLastBorrow; return (userSummaryMemory.amountDAIBorrowed * yearlyPercentInterest / 100 * timeSinceLastLoan) / 365 days; // 365days * 100 } function editAmountBorrowed(DebtorSummary storage userSummaryStorage, uint256 addToBorrowed) private { userSummaryStorage.amountDAIBorrowed = userSummaryStorage.amountDAIBorrowed + addToBorrowed; updateDebtTime(userSummaryStorage); } function updateDebtTime(DebtorSummary storage userSummaryStorage) private { userSummaryStorage.timeLastBorrow = block.timestamp; } }
It should be noted that this will change everything backwards in time meaning some people might be liquidated right away
function changeLoanTerms(uint256 _yearlyPercentInterest, uint256 _loanDefaultThresholdPercent) public onlyOwner { yearlyPercentInterest = _yearlyPercentInterest; loanDefaultThresholdPercent = _loanDefaultThresholdPercent; }
2,574,483
pragma solidity ^0.4.8; contract SmartRouletteToken { uint8 public decimals; function balanceOf( address who ) external constant returns (uint256); function gameListOf( address who ) external constant returns (bool); function getItemHolders(uint256 index) external constant returns(address); function getCountHolders() external constant returns (uint256); function getCountTempHolders() external constant returns(uint256); function getItemTempHolders(uint256 index) external constant returns(address); function tempTokensBalanceOf( address who ) external constant returns (uint256); } contract SmartRouletteDividend { address developer; address manager; SmartRouletteToken smartToken; uint256 decimal; struct DividendInfo { uint256 amountDividend; uint256 blockDividend; bool AllPaymentsSent; } DividendInfo[] dividendHistory; address public gameAddress; uint256 public tokensNeededToGetPayment = 1000; function SmartRouletteDividend() { developer = msg.sender; manager = msg.sender; smartToken = SmartRouletteToken(0xcced5b8288086be8c38e23567e684c3740be4d48); //test 0xc46ed6ba652bd552671a46045b495748cd10fa04 main 0x2a650356bd894370cc1d6aba71b36c0ad6b3dc18 decimal = 10**uint256(smartToken.decimals()); } modifier isDeveloper(){ if (msg.sender!=developer) throw; _; } modifier isManager(){ if (msg.sender!=manager && msg.sender!=developer) throw; _; } function changeTokensLimit(uint256 newTokensLimit) isDeveloper { tokensNeededToGetPayment = newTokensLimit; } function dividendCount() constant returns(uint256) { return dividendHistory.length; } function SetAllPaymentsSent(uint256 DividendNo) isManager { dividendHistory[DividendNo].AllPaymentsSent = true; // all fees (30000 gas * tx.gasprice for each transaction) if (manager.send(this.balance) == false) throw; } function changeDeveloper(address new_developer) isDeveloper { if(new_developer == address(0x0)) throw; developer = new_developer; } function changeManager(address new_manager) isDeveloper { if(new_manager == address(0x0)) throw; manager = new_manager; } function kill() isDeveloper { suicide(developer); } function getDividendInfo(uint256 index) constant returns(uint256 amountDividend, uint256 blockDividend, bool AllPaymentsSent) { amountDividend = dividendHistory[index].amountDividend; blockDividend = dividendHistory[index].blockDividend; AllPaymentsSent = dividendHistory[index].AllPaymentsSent; } // get total count tokens (to calculate profit for one token) function get_CountProfitsToken() constant returns(uint256){ uint256 countProfitsTokens = 0; mapping(address => bool) uniqueHolders; uint256 countHolders = smartToken.getCountHolders(); for(uint256 i=0; i<countHolders; i++) { address holder = smartToken.getItemHolders(i); if(holder!=address(0x0) && !uniqueHolders[holder]) { uint256 holdersTokens = smartToken.balanceOf(holder); if(holdersTokens>0) { uint256 tempTokens = smartToken.tempTokensBalanceOf(holder); if((holdersTokens+tempTokens)/decimal >= tokensNeededToGetPayment) { uniqueHolders[holder]=true; countProfitsTokens += (holdersTokens+tempTokens); } } } } uint256 countTempHolders = smartToken.getCountTempHolders(); for(uint256 j=0; j<countTempHolders; j++) { address temp_holder = smartToken.getItemTempHolders(j); if(temp_holder!=address(0x0) && !uniqueHolders[temp_holder]) { uint256 token_balance = smartToken.balanceOf(temp_holder); if(token_balance==0) { uint256 count_tempTokens = smartToken.tempTokensBalanceOf(temp_holder); if(count_tempTokens>0 && count_tempTokens/decimal >= tokensNeededToGetPayment) { uniqueHolders[temp_holder]=true; countProfitsTokens += count_tempTokens; } } } } return countProfitsTokens; } function get_CountAllHolderForProfit() constant returns(uint256){ uint256 countAllHolders = 0; mapping(address => bool) uniqueHolders; uint256 countHolders = smartToken.getCountHolders(); for(uint256 i=0; i<countHolders; i++) { address holder = smartToken.getItemHolders(i); if(holder!=address(0x0) && !uniqueHolders[holder]) { uint256 holdersTokens = smartToken.balanceOf(holder); if(holdersTokens>0) { uint256 tempTokens = smartToken.tempTokensBalanceOf(holder); if((holdersTokens+tempTokens)/decimal >= tokensNeededToGetPayment) { uniqueHolders[holder] = true; countAllHolders += 1; } } } } uint256 countTempHolders = smartToken.getCountTempHolders(); for(uint256 j=0; j<countTempHolders; j++) { address temp_holder = smartToken.getItemTempHolders(j); if(temp_holder!=address(0x0) && !uniqueHolders[temp_holder]) { uint256 token_balance = smartToken.balanceOf(temp_holder); if(token_balance==0) { uint256 coun_tempTokens = smartToken.tempTokensBalanceOf(temp_holder); if(coun_tempTokens>0 && coun_tempTokens/decimal >= tokensNeededToGetPayment) { uniqueHolders[temp_holder] = true; countAllHolders += 1; } } } } return countAllHolders; } // get holders addresses to make payment each of them function get_Holders(uint256 position) constant returns(address[64] listHolders, uint256 nextPosition) { uint8 n = 0; uint256 countHolders = smartToken.getCountHolders(); for(; position < countHolders; position++){ address holder = smartToken.getItemHolders(position); if(holder!=address(0x0)){ uint256 holdersTokens = smartToken.balanceOf(holder); if(holdersTokens>0){ uint256 tempTokens = smartToken.tempTokensBalanceOf(holder); if((holdersTokens+tempTokens)/decimal >= tokensNeededToGetPayment){ // listHolders[n++] = holder; if (n == 64) { nextPosition = position + 1; return; } } } } } if (position >= countHolders) { uint256 countTempHolders = smartToken.getCountTempHolders(); for(uint256 j=position-countHolders; j<countTempHolders; j++) { address temp_holder = smartToken.getItemTempHolders(j); if(temp_holder!=address(0x0)){ uint256 token_balance = smartToken.balanceOf(temp_holder); if(token_balance==0){ uint256 count_tempTokens = smartToken.tempTokensBalanceOf(temp_holder); if(count_tempTokens>0 && count_tempTokens/decimal >= tokensNeededToGetPayment){ listHolders[n++] = temp_holder; if (n == 64) { nextPosition = position + 1; return; } } } } position = position + 1; } } nextPosition = 0; } // Get profit for specified token holder // Function should be executed in blockDividend ! (see struct DividendInfo) // Don't call this function via etherescan.io // Example how to call via JavaScript and web3 // var abiDividend = [...]; // var holderAddress = "0xdd94ddf50485f41491c415e7133100e670cd4ef3"; // var dividendIndex = 1; // starts from zero // var blockDividend = 3527958; // see function getDividendInfo // web3.eth.contract(abiDividend).at("0x600e18779b6aC789b95a12C30b5863E842F4ae1d").get_HoldersProfit(dividendIndex, holderAddress, blockDividend, function(err, profit){ // alert("Your profit " + web3.fromWei(profit).toString(10) + "ETH"); // }); function get_HoldersProfit(uint256 dividendPaymentNum, address holder) constant returns(uint256){ uint256 profit = 0; if(holder != address(0x0) && dividendHistory.length > 0 && dividendPaymentNum < dividendHistory.length){ uint256 count_tokens = smartToken.balanceOf(holder) + smartToken.tempTokensBalanceOf(holder); if(count_tokens/decimal >= tokensNeededToGetPayment){ profit = (count_tokens*dividendHistory[dividendPaymentNum].amountDividend)/get_CountProfitsToken(); } } return profit; } // Since the full cycle of calculations in a smart contract costs a big amount of gas and the smart contract is not able to calculate the exact block // the major part of calculations is transferred to the server out of the smart contract (though using functions of reading the smart contract) // In order to confirm fairness of dividends distribution the validating interface with open source code is used (the open version is available at https://smartroulette.io/dividends) // The source code is available at the address https://github.com/Smartroulette/SmartRouletteDividends function send_DividendToAddress(address holder, uint256 amount) isManager { uint256 avgGasValue = 30000; if (amount < avgGasValue * tx.gasprice) throw; if(holder.send(amount - avgGasValue * tx.gasprice) == false) throw; } function () payable { if(smartToken.gameListOf(msg.sender)) { // only the one game can be attached to this contract if (gameAddress == 0) gameAddress = msg.sender; else if (gameAddress != msg.sender) throw; // do not send new payment until previous is done if (dividendHistory.length > 0 && dividendHistory[dividendHistory.length - 1].AllPaymentsSent == false) throw; dividendHistory.push(DividendInfo(msg.value, block.number, false)); } else { throw; } } }
get holders addresses to make payment each of them
function get_Holders(uint256 position) constant returns(address[64] listHolders, uint256 nextPosition) { uint8 n = 0; uint256 countHolders = smartToken.getCountHolders(); for(; position < countHolders; position++){ address holder = smartToken.getItemHolders(position); if(holder!=address(0x0)){ uint256 holdersTokens = smartToken.balanceOf(holder); if(holdersTokens>0){ uint256 tempTokens = smartToken.tempTokensBalanceOf(holder); if((holdersTokens+tempTokens)/decimal >= tokensNeededToGetPayment){ listHolders[n++] = holder; if (n == 64) { nextPosition = position + 1; return; } } } } } if (position >= countHolders) { uint256 countTempHolders = smartToken.getCountTempHolders(); for(uint256 j=position-countHolders; j<countTempHolders; j++) { address temp_holder = smartToken.getItemTempHolders(j); if(temp_holder!=address(0x0)){ uint256 token_balance = smartToken.balanceOf(temp_holder); if(token_balance==0){ uint256 count_tempTokens = smartToken.tempTokensBalanceOf(temp_holder); if(count_tempTokens>0 && count_tempTokens/decimal >= tokensNeededToGetPayment){ listHolders[n++] = temp_holder; if (n == 64) { nextPosition = position + 1; return; } } } } position = position + 1; } } nextPosition = 0; }
2,475,932
./full_match/62621/0x8A6B18132c1dDdc08816F32e62266b33C140d1BF/sources/SingleFrameFixed_flat.sol
transfer governance token to feeAddress transfer governance token to creator transfer governance token to owner
function singleBuy(uint256 _id, address sender) public payable { require(_id <= currentPairId && pairs[_id].pairId == _id, "Could not find item"); require(pairs[_id].bValid, "invalid Pair id"); require(pairs[_id].owner != sender, "owner can not buy"); Pair memory pair = pairs[_id]; uint256 totalAmount = pair.price; uint256 feeAmount = totalAmount.mul(feeAdmin).div(PERCENTS_DIVIDER); uint256 createrAmount = totalAmount.mul(pair.creatorFee).div(PERCENTS_DIVIDER); uint256 ownerAmount = totalAmount.sub(feeAmount).sub(createrAmount); if (pairs[_id].tokenAdr == address(0x0)) { require(msg.value >= totalAmount, "too small amount"); if (feeAmount > 0)payable(adminAddress).transfer(feeAmount); if (createrAmount > 0)payable(pair.creator).transfer(createrAmount); payable(pair.owner).transfer(ownerAmount); totalEarnedCoin = totalEarnedCoin + feeAmount; IERC20 governanceToken = IERC20(pairs[_id].tokenAdr); require(governanceToken.transferFrom(sender, address(this), totalAmount), "insufficient token balance"); if (feeAmount > 0)require(governanceToken.transfer(adminAddress, feeAmount)); if (createrAmount > 0)require(governanceToken.transfer(pair.creator, createrAmount)); require(governanceToken.transfer(pair.owner, ownerAmount)); totalEarnedToken = totalEarnedToken + feeAmount; } pairs[_id].bValid = false; totalSwapped = totalSwapped.add(1); emit SingleSwapped(sender, pair); }
16,311,221
// File: contracts/token/GovernanceStorage.sol pragma solidity 0.5.16; /* Copyright 2020 Compound Labs, Inc. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ contract GovernanceStorage { /// @notice A record of each accounts delegate mapping (address => address) internal _delegates; /// @notice A checkpoint for marking number of votes from a given block struct Checkpoint { uint32 fromBlock; uint256 votes; } /// @notice A record of votes checkpoints for each account, by index mapping (address => mapping (uint32 => Checkpoint)) public checkpoints; /// @notice The number of checkpoints for each account mapping (address => uint32) public numCheckpoints; } // File: @openzeppelin/contracts/math/SafeMath.sol pragma solidity ^0.5.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. * * _Available since v2.4.0._ */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. * * _Available since v2.4.0._ */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { // Solidity only automatically asserts when dividing by 0 require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. * * _Available since v2.4.0._ */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } // File: contracts/token/TokenStorage.sol // SPDX-License-Identifier: MIT pragma solidity 0.5.16; contract TokenStorage { using SafeMath for uint256; /** * @notice EIP-20 token name for this token */ string public name; /** * @notice EIP-20 token symbol for this token */ string public symbol; /** * @notice EIP-20 token decimals for this token */ uint8 public decimals; /** * @notice Governor for this contract */ address public gov; /** * @notice Pending governance for this contract */ address public pendingGov; /** * @notice Approved token emitter for this contract */ address public emission; /** * @notice Approved token guardian for this contract */ address public guardian; /** * @notice Total supply of LIFE */ uint256 public totalSupply; /** * @notice Used for pausing and unpausing */ bool internal _paused = false; /** * @notice Used for checking validity of Guardian */ uint256 public guardianExpiration = block.timestamp.add(78 weeks); // Guardian expires in 1.5 years /** * @notice used for tracking freeze timestamp */ mapping(address => uint256) internal lastFrozen; uint256 public freezeDelay = 14 days; // Delay between freezing the same target multiple times to avoid abuse /** * @notice Used for balance of the users and allowances */ mapping(address => uint256) internal _balances; mapping(address => mapping(address => uint256)) internal _allowedBalances; bool public initialized = false; uint256 public currentSupply; } // File: contracts/token/TokenInterface.sol // SPDX-License-Identifier: MIT pragma solidity 0.5.16; contract TokenInterface is TokenStorage, GovernanceStorage { /// @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); /*** Gov Events ***/ /** * @notice Event emitted when pendingGov is changed */ event NewPendingGov(address oldPendingGov, address newPendingGov); /** * @notice Event emitted when gov is changed */ event NewGov(address oldGov, address newGov); /** * @notice Event emitted when Emssion is changed */ event NewEmission(address oldEmission, address newEmission); /** * @notice Event emitted when Guardian is changed */ event NewGuardian(address oldGuardian, address newGuardian); /** * @notice Event emitted when the pause is triggered. */ event Paused(address account); /** * @dev Event emitted when the pause is lifted. */ event Unpaused(address account); /* - ERC20 Events - */ /** * @notice EIP20 Transfer event */ event Transfer(address indexed from, address indexed to, uint amount); /** * @notice EIP20 Approval event */ event Approval(address indexed owner, address indexed spender, uint amount); /* - Extra Events - */ /** * @notice Tokens minted event */ event Mint(address to, uint256 amount); event Burn(address from, uint256 amount); // Public functions function transfer(address to, uint256 value) external returns(bool); function transferFrom(address from, address to, uint256 value) external returns(bool); function balanceOf(address who) external view returns(uint256); function allowance(address owner_, address spender) external view returns(uint256); function approve(address spender, uint256 value) external returns (bool); function increaseAllowance(address spender, uint256 addedValue) external returns (bool); function decreaseAllowance(address spender, uint256 subtractedValue) external returns (bool); /* - Governance Functions - */ function getPriorVotes(address account, uint blockNumber) external view returns (uint256); // function delegateBySig(address delegatee, uint nonce, uint expiry, uint8 v, bytes32 r, bytes32 s) external; function delegate(address delegatee) external; function delegates(address delegator) external view returns (address); function getCurrentVotes(address account) external view returns (uint256); /* - Permissioned/Governance functions - */ function mint(address to, uint256 amount) external returns (bool); function _setPendingGov(address pendingGov_) external; function _acceptGov() external; } // File: contracts/token/Governance.sol pragma solidity 0.5.16; /* Copyright 2020 Compound Labs, Inc. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ contract GovernanceToken is TokenInterface { /// @notice An event emitted when an account changes its delegate event DelegateChanged(address indexed delegator, address indexed fromDelegate, address indexed toDelegate); /// @notice An event emitted when a delegate account's vote balance changes event DelegateVotesChanged(address indexed delegate, uint previousBalance, uint newBalance); /** * @notice Get delegatee for an address delegating * @param delegator The address to get delegatee for */ function delegates(address delegator) external view returns (address) { return _delegates[delegator]; } /** * @notice Delegate votes from `msg.sender` to `delegatee` * @param delegatee The address to delegate votes to */ function delegate(address delegatee) external { return _delegate(msg.sender, delegatee); } /** * @notice Gets the current votes balance for `account` * @param account The address to get votes balance * @return The number of current votes for `account` */ function getCurrentVotes(address account) external view returns (uint256) { uint32 nCheckpoints = numCheckpoints[account]; return nCheckpoints > 0 ? checkpoints[account][nCheckpoints - 1].votes : 0; } /** * @notice Determine the prior number of votes for an account as of a block number * @dev Block number must be a finalized block or else this function will revert to prevent misinformation. * @param account The address of the account to check * @param blockNumber The block number to get the vote balance at * @return The number of votes the account had as of the given block */ function getPriorVotes(address account, uint blockNumber) external view returns (uint256) { require(blockNumber < block.number, "LIFE::getPriorVotes: not yet determined"); uint32 nCheckpoints = numCheckpoints[account]; if (nCheckpoints == 0) { return 0; } // First check most recent balance if (checkpoints[account][nCheckpoints - 1].fromBlock <= blockNumber) { return checkpoints[account][nCheckpoints - 1].votes; } // Next check implicit zero balance if (checkpoints[account][0].fromBlock > blockNumber) { return 0; } uint32 lower = 0; uint32 upper = nCheckpoints - 1; while (upper > lower) { uint32 center = upper - (upper - lower) / 2; // ceil, avoiding overflow Checkpoint memory cp = checkpoints[account][center]; if (cp.fromBlock == blockNumber) { return cp.votes; } else if (cp.fromBlock < blockNumber) { lower = center; } else { upper = center - 1; } } return checkpoints[account][lower].votes; } function _delegate(address delegator, address delegatee) internal { address currentDelegate = _delegates[delegator]; uint256 delegatorBalance = _balances[delegator]; _delegates[delegator] = delegatee; emit DelegateChanged(delegator, currentDelegate, delegatee); _moveDelegates(currentDelegate, delegatee, delegatorBalance); } function _moveDelegates(address srcRep, address dstRep, uint256 amount) internal { if (srcRep != dstRep && amount > 0) { if (srcRep != address(0)) { // decrease old representative uint32 srcRepNum = numCheckpoints[srcRep]; uint256 srcRepOld = srcRepNum > 0 ? checkpoints[srcRep][srcRepNum - 1].votes : 0; uint256 srcRepNew = srcRepOld.sub(amount); _writeCheckpoint(srcRep, srcRepNum, srcRepOld, srcRepNew); } if (dstRep != address(0)) { // increase new representative uint32 dstRepNum = numCheckpoints[dstRep]; uint256 dstRepOld = dstRepNum > 0 ? checkpoints[dstRep][dstRepNum - 1].votes : 0; uint256 dstRepNew = dstRepOld.add(amount); _writeCheckpoint(dstRep, dstRepNum, dstRepOld, dstRepNew); } } } function _writeCheckpoint( address delegatee, uint32 nCheckpoints, uint256 oldVotes, uint256 newVotes ) internal { uint32 blockNumber = safe32(block.number, "LIFE::_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); } } // File: @openzeppelin/contracts/token/ERC20/IERC20.sol pragma solidity ^0.5.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. Does not include * the optional functions; to access them see {ERC20Detailed}. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // File: @openzeppelin/contracts/utils/Address.sol pragma solidity ^0.5.5; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // According to EIP-1052, 0x0 is the value returned for not-yet created accounts // and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned // for accounts without code, i.e. `keccak256('')` bytes32 codehash; bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; // solhint-disable-next-line no-inline-assembly assembly { codehash := extcodehash(account) } return (codehash != accountHash && codehash != 0x0); } /** * @dev Converts an `address` into `address payable`. Note that this is * simply a type cast: the actual underlying value is not changed. * * _Available since v2.4.0._ */ function toPayable(address account) internal pure returns (address payable) { return address(uint160(account)); } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. * * _Available since v2.4.0._ */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-call-value (bool success, ) = recipient.call.value(amount)(""); require(success, "Address: unable to send value, recipient may have reverted"); } } // File: @openzeppelin/contracts/access/Roles.sol pragma solidity ^0.5.0; /** * @title Roles * @dev Library for managing addresses assigned to a Role. */ library Roles { struct Role { mapping (address => bool) bearer; } /** * @dev Give an account access to this role. */ function add(Role storage role, address account) internal { require(!has(role, account), "Roles: account already has role"); role.bearer[account] = true; } /** * @dev Remove an account's access to this role. */ function remove(Role storage role, address account) internal { require(has(role, account), "Roles: account does not have role"); role.bearer[account] = false; } /** * @dev Check if an account has this role. * @return bool */ function has(Role storage role, address account) internal view returns (bool) { require(account != address(0), "Roles: account is the zero address"); return role.bearer[account]; } } // File: Modifier from : @openzeppelin/contracts/access/roles/MinterRole.sol pragma solidity ^0.5.0; contract Frozen { using Roles for Roles.Role; event AccountFrozen(address indexed account); event AccountUnfrozen(address indexed account); Roles.Role private _frozen; modifier checkFrozen(address from) { require(!isFrozen(from), "Frozen: Sender's tranfers are frozen"); _; } function isFrozen(address account) public view returns (bool) { return _frozen.has(account); } function _freezeAccount(address account) internal { _frozen.add(account); emit AccountFrozen(account); } function _unfreezeAccount(address account) internal { _frozen.remove(account); emit AccountUnfrozen(account); } } // File: @openzeppelin/contracts/token/ERC20/SafeERC20.sol pragma solidity ^0.5.0; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for ERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using SafeMath for uint256; using Address for address; function safeTransfer(IERC20 token, address to, uint256 value) internal { callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal { callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } function safeApprove(IERC20 token, address spender, uint256 value) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' // solhint-disable-next-line max-line-length require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).add(value); callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero"); callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. // A Solidity high level call has three parts: // 1. The target address is checked to verify it contains contract code // 2. The call itself is made, and success asserted // 3. The return value is decoded, which in turn checks the size of the returned data. // solhint-disable-next-line max-line-length require(address(token).isContract(), "SafeERC20: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = address(token).call(data); require(success, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // File: contracts/LIFE.sol // SPDX-License-Identifier: GPL-3.0-or-later pragma solidity 0.5.16; contract LIFEToken is GovernanceToken, Frozen { // Modifiers modifier onlyGov() { require(msg.sender == gov, "only governance"); _; } modifier onlyMinter() { require( msg.sender == emission || msg.sender == gov, "not minter" ); _; } modifier onlyEmergency() { require( msg.sender == guardian || msg.sender == gov, "not guardian or governor" ); _; } modifier whenNotPaused() { require(_paused == false, "Pausable: paused"); _; } modifier validRecipient(address to) { require(to != address(0x0)); require(to != address(this)); _; } function initialize( string memory name_, string memory symbol_, uint8 decimals_ ) public { require(initialized == false, "already initialized"); name = name_; symbol = symbol_; decimals = decimals_; } /** * @notice Allows the pausing and unpausing of certain functions . * @dev Limited to onlyMinter modifier */ function pause() public onlyEmergency { _paused = true; emit Paused(msg.sender); } function unpause() public onlyEmergency { _paused = false; emit Unpaused(msg.sender); } /** * @notice Mints new tokens, increasing currentSupply . * @dev Limited to onlyMinter modifier */ function mint(address to, uint256 amount) external onlyMinter whenNotPaused returns (bool) { _mint(to, amount); return true; } function _mint(address to, uint256 amount) internal { require(currentSupply.add(amount) <= totalSupply, "Emission exceeds total supply"); // increase currentSupply currentSupply = currentSupply.add(amount); // add balance _balances[to] = _balances[to].add(amount); // add delegates to the minter _moveDelegates(address(0), _delegates[to], amount); emit Mint(to, amount); emit Transfer(address(0), to, amount); } /** * @notice Burns tokens, decreasing totalSupply, currentSupply, and a users balance. */ function burn(uint256 amount) external returns (bool) { _burn(msg.sender, amount); return true; } function _burn(address from, uint256 amount) internal { // decrease totalSupply totalSupply = totalSupply.sub(amount); // decrease currentSupply currentSupply = currentSupply.sub(amount); // sub balance, will revert on underflow _balances[from] = _balances[from].sub(amount); // remove delegates from the minter _moveDelegates(_delegates[from], address(0), amount); emit Burn(from, amount); emit Transfer(from, address(0), amount); } /* - ERC20 functionality - */ /** * @dev Transfer tokens to a specified address. * @param to The address to transfer to. * @param value The amount to be transferred. * @return True on success, false otherwise. */ function transfer(address to, uint256 value) external validRecipient(to) checkFrozen(msg.sender) whenNotPaused returns (bool) { // sub from balance of sender _balances[msg.sender] = _balances[msg.sender].sub(value); // add to balance of receiver _balances[to] = _balances[to].add(value); emit Transfer(msg.sender, to, value); _moveDelegates(_delegates[msg.sender], _delegates[to], value); return true; } /** * @dev Transfer tokens from one address to another. * @param from The address you want to send tokens from. * @param to The address you want to transfer to. * @param value The amount of tokens to be transferred. */ function transferFrom(address from, address to, uint256 value) external validRecipient(to) checkFrozen(from) whenNotPaused returns (bool) { // decrease allowance _allowedBalances[from][msg.sender] = _allowedBalances[from][msg.sender].sub(value); // sub from balance _balances[from] = _balances[from].sub(value); _balances[to] = _balances[to].add(value); emit Transfer(from, to, value); _moveDelegates(_delegates[from], _delegates[to], value); return true; } /** * @param who The address to query. * @return The balance of the specified address. */ function balanceOf(address who) external view returns (uint256) { return _balances[who]; } /** * @dev Function to check the amount of tokens that an owner has allowed to a spender. * @param owner_ The address which owns the funds. * @param spender The address which will spend the funds. * @return The number of tokens still available for the spender. */ function allowance(address owner_, address spender) external view returns (uint256) { return _allowedBalances[owner_][spender]; } /** * @dev Approve the passed address to spend the specified amount of tokens on behalf of * msg.sender. This method is included for ERC20 compatibility. * increaseAllowance and decreaseAllowance should be used instead. * Changing an allowance with this method brings the risk that someone may transfer both * the old and the new allowance - if they are both greater than zero - if a transfer * transaction is mined before the later approve() call is mined. * * @param spender The address which will spend the funds. * @param value The amount of tokens to be spent. */ function approve(address spender, uint256 value) external returns (bool) { _allowedBalances[msg.sender][spender] = value; emit Approval(msg.sender, spender, value); return true; } /** * @dev Increase the amount of tokens that an owner has allowed to a spender. * This method should be used instead of approve() to avoid the double approval vulnerability * described above. * @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) external returns (bool) { _allowedBalances[msg.sender][spender] = _allowedBalances[msg.sender][spender].add(addedValue); emit Approval(msg.sender, spender, _allowedBalances[msg.sender][spender]); return true; } /** * @dev Decrease the amount of tokens that an owner has allowed to a spender. * * @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) external returns (bool) { uint256 oldValue = _allowedBalances[msg.sender][spender]; if (subtractedValue >= oldValue) { _allowedBalances[msg.sender][spender] = 0; } else { _allowedBalances[msg.sender][spender] = oldValue.sub(subtractedValue); } emit Approval(msg.sender, spender, _allowedBalances[msg.sender][spender]); return true; } /* - Governance Functions - */ /** @notice sets the emission * @param emission_ The address of the emission contract to use for authentication. */ function _setEmission(address emission_) external onlyGov { address oldEmission = emission; emission = emission_; emit NewEmission(oldEmission, emission_); } /** @notice sets the emission * @param guardian_ The address of the guardian contract to use for authentication. */ function _setGuardian(address guardian_) external onlyEmergency { require(block.timestamp < guardianExpiration); // Can only set new guardian if guardian powers havn't expired yet address oldGuardian = guardian; guardian = guardian_; emit NewGuardian(oldGuardian, guardian_); } function freezeTargetFunds(address target) external onlyEmergency { require(lastFrozen[target].add(freezeDelay) < block.timestamp, "Target was Frozen recently"); lastFrozen[target] = block.timestamp; _freezeAccount(target); } function unfreezeTargetFunds(address target) external onlyEmergency { _unfreezeAccount(target); } /** @notice lets msg.sender abolish guardian * */ function abolishGuardian() external { require(msg.sender == guardian || block.timestamp >= guardianExpiration); // Can be abolished by anyone after expiration or anytime by guardian themselves guardian = address(0); } /** @notice sets the pendingGov * @param pendingGov_ The address of the governor contract to use for authentication. */ function _setPendingGov(address pendingGov_) external onlyGov { address oldPendingGov = pendingGov; pendingGov = pendingGov_; emit NewPendingGov(oldPendingGov, pendingGov_); } /** @notice lets msg.sender accept governance * */ function _acceptGov() external { require(msg.sender == pendingGov, "!pending"); address oldGov = gov; gov = pendingGov; pendingGov = address(0); emit NewGov(oldGov, gov); } // Rescue tokens function rescueTokens( address token, address to, uint256 amount ) external onlyGov returns (bool) { // transfer to SafeERC20.safeTransfer(IERC20(token), to, amount); return true; } } contract LIFE is LIFEToken { constructor() public {} /** * @notice Initialize the new money market * @param name_ ERC-20 name of this token * @param symbol_ ERC-20 symbol of this token * @param decimals_ ERC-20 decimal precision of this token */ function initialize( string memory name_, string memory symbol_, uint8 decimals_, address initial_owner, uint256 initSupply_, uint256 totalSupply_ ) public { super.initialize(name_, symbol_, decimals_); initialized = true; currentSupply = initSupply_; totalSupply = totalSupply_; _balances[initial_owner] = currentSupply; gov = initial_owner; guardian = initial_owner; } }
sets the emission guardian_ The address of the guardian contract to use for authentication./
function _setGuardian(address guardian_) external onlyEmergency { address oldGuardian = guardian; guardian = guardian_; emit NewGuardian(oldGuardian, guardian_); }
7,016,258
// Dependency file: openzeppelin-solidity/contracts/math/SafeMath.sol // pragma solidity ^0.4.24; /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { /** * @dev Multiplies two numbers, throws on overflow. */ function mul(uint256 _a, uint256 _b) internal pure returns (uint256 c) { // Gas optimization: this is cheaper than asserting 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522 if (_a == 0) { return 0; } c = _a * _b; assert(c / _a == _b); return c; } /** * @dev Integer division of two numbers, truncating the quotient. */ function div(uint256 _a, uint256 _b) internal pure returns (uint256) { // assert(_b > 0); // Solidity automatically throws when dividing by 0 // uint256 c = _a / _b; // assert(_a == _b * c + _a % _b); // There is no case in which this doesn't hold return _a / _b; } /** * @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 _a, uint256 _b) internal pure returns (uint256) { assert(_b <= _a); return _a - _b; } /** * @dev Adds two numbers, throws on overflow. */ function add(uint256 _a, uint256 _b) internal pure returns (uint256 c) { c = _a + _b; assert(c >= _a); return c; } } // Dependency file: openzeppelin-solidity/contracts/introspection/ERC165.sol // pragma solidity ^0.4.24; /** * @title ERC165 * @dev https://github.com/ethereum/EIPs/blob/master/EIPS/eip-165.md */ interface ERC165 { /** * @notice Query if a contract implements an interface * @param _interfaceId The interface identifier, as specified in ERC-165 * @dev Interface identification is specified in ERC-165. This function * uses less than 30,000 gas. */ function supportsInterface(bytes4 _interfaceId) external view returns (bool); } // Dependency file: openzeppelin-solidity/contracts/token/ERC721/ERC721Basic.sol // pragma solidity ^0.4.24; // import "openzeppelin-solidity/contracts/introspection/ERC165.sol"; /** * @title ERC721 Non-Fungible Token Standard basic interface * @dev see https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md */ contract ERC721Basic is ERC165 { bytes4 internal constant InterfaceId_ERC721 = 0x80ac58cd; /* * 0x80ac58cd === * bytes4(keccak256('balanceOf(address)')) ^ * bytes4(keccak256('ownerOf(uint256)')) ^ * bytes4(keccak256('approve(address,uint256)')) ^ * bytes4(keccak256('getApproved(uint256)')) ^ * bytes4(keccak256('setApprovalForAll(address,bool)')) ^ * bytes4(keccak256('isApprovedForAll(address,address)')) ^ * bytes4(keccak256('transferFrom(address,address,uint256)')) ^ * bytes4(keccak256('safeTransferFrom(address,address,uint256)')) ^ * bytes4(keccak256('safeTransferFrom(address,address,uint256,bytes)')) */ bytes4 internal constant InterfaceId_ERC721Exists = 0x4f558e79; /* * 0x4f558e79 === * bytes4(keccak256('exists(uint256)')) */ bytes4 internal constant InterfaceId_ERC721Enumerable = 0x780e9d63; /** * 0x780e9d63 === * bytes4(keccak256('totalSupply()')) ^ * bytes4(keccak256('tokenOfOwnerByIndex(address,uint256)')) ^ * bytes4(keccak256('tokenByIndex(uint256)')) */ bytes4 internal constant InterfaceId_ERC721Metadata = 0x5b5e139f; /** * 0x5b5e139f === * bytes4(keccak256('name()')) ^ * bytes4(keccak256('symbol()')) ^ * bytes4(keccak256('tokenURI(uint256)')) */ event Transfer( address indexed _from, address indexed _to, uint256 indexed _tokenId ); event Approval( address indexed _owner, address indexed _approved, uint256 indexed _tokenId ); event ApprovalForAll( address indexed _owner, address indexed _operator, bool _approved ); function balanceOf(address _owner) public view returns (uint256 _balance); function ownerOf(uint256 _tokenId) public view returns (address _owner); function exists(uint256 _tokenId) public view returns (bool _exists); function approve(address _to, uint256 _tokenId) public; function getApproved(uint256 _tokenId) public view returns (address _operator); function setApprovalForAll(address _operator, bool _approved) public; function isApprovedForAll(address _owner, address _operator) public view returns (bool); function transferFrom(address _from, address _to, uint256 _tokenId) public; function safeTransferFrom(address _from, address _to, uint256 _tokenId) public; function safeTransferFrom( address _from, address _to, uint256 _tokenId, bytes _data ) public; } // Dependency file: openzeppelin-solidity/contracts/token/ERC721/ERC721.sol // pragma solidity ^0.4.24; // import "openzeppelin-solidity/contracts/token/ERC721/ERC721Basic.sol"; /** * @title ERC-721 Non-Fungible Token Standard, optional enumeration extension * @dev See https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md */ contract ERC721Enumerable is ERC721Basic { function totalSupply() public view returns (uint256); function tokenOfOwnerByIndex( address _owner, uint256 _index ) public view returns (uint256 _tokenId); function tokenByIndex(uint256 _index) public view returns (uint256); } /** * @title ERC-721 Non-Fungible Token Standard, optional metadata extension * @dev See https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md */ contract ERC721Metadata is ERC721Basic { function name() external view returns (string _name); function symbol() external view returns (string _symbol); function tokenURI(uint256 _tokenId) public view returns (string); } /** * @title ERC-721 Non-Fungible Token Standard, full implementation interface * @dev See https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md */ contract ERC721 is ERC721Basic, ERC721Enumerable, ERC721Metadata { } // Dependency file: openzeppelin-solidity/contracts/introspection/SupportsInterfaceWithLookup.sol // pragma solidity ^0.4.24; // import "openzeppelin-solidity/contracts/introspection/ERC165.sol"; /** * @title SupportsInterfaceWithLookup * @author Matt Condon (@shrugs) * @dev Implements ERC165 using a lookup table. */ contract SupportsInterfaceWithLookup is ERC165 { bytes4 public constant InterfaceId_ERC165 = 0x01ffc9a7; /** * 0x01ffc9a7 === * bytes4(keccak256('supportsInterface(bytes4)')) */ /** * @dev a mapping of interface id to whether or not it's supported */ mapping(bytes4 => bool) internal supportedInterfaces; /** * @dev A contract implementing SupportsInterfaceWithLookup * implement ERC165 itself */ constructor() public { _registerInterface(InterfaceId_ERC165); } /** * @dev implement supportsInterface(bytes4) using a lookup table */ function supportsInterface(bytes4 _interfaceId) external view returns (bool) { return supportedInterfaces[_interfaceId]; } /** * @dev private method for registering an interface */ function _registerInterface(bytes4 _interfaceId) internal { require(_interfaceId != 0xffffffff); supportedInterfaces[_interfaceId] = true; } } // Dependency file: @evolutionland/common/contracts/interfaces/IMintableERC20.sol // pragma solidity ^0.4.23; contract IMintableERC20 { function mint(address _to, uint256 _value) public; } // Dependency file: @evolutionland/common/contracts/interfaces/ISettingsRegistry.sol // pragma solidity ^0.4.24; contract ISettingsRegistry { enum SettingsValueTypes { NONE, UINT, STRING, ADDRESS, BYTES, BOOL, INT } function uintOf(bytes32 _propertyName) public view returns (uint256); function stringOf(bytes32 _propertyName) public view returns (string); function addressOf(bytes32 _propertyName) public view returns (address); function bytesOf(bytes32 _propertyName) public view returns (bytes); function boolOf(bytes32 _propertyName) public view returns (bool); function intOf(bytes32 _propertyName) public view returns (int); function setUintProperty(bytes32 _propertyName, uint _value) public; function setStringProperty(bytes32 _propertyName, string _value) public; function setAddressProperty(bytes32 _propertyName, address _value) public; function setBytesProperty(bytes32 _propertyName, bytes _value) public; function setBoolProperty(bytes32 _propertyName, bool _value) public; function setIntProperty(bytes32 _propertyName, int _value) public; function getValueTypeOf(bytes32 _propertyName) public view returns (uint /* SettingsValueTypes */ ); event ChangeProperty(bytes32 indexed _propertyName, uint256 _type); } // Dependency file: @evolutionland/common/contracts/interfaces/IAuthority.sol // pragma solidity ^0.4.24; contract IAuthority { function canCall( address src, address dst, bytes4 sig ) public view returns (bool); } // Dependency file: @evolutionland/common/contracts/DSAuth.sol // pragma solidity ^0.4.24; // import '/Users/echo/workspace/contract/evolutionlandorg/land/node_modules/@evolutionland/common/contracts/interfaces/IAuthority.sol'; contract DSAuthEvents { event LogSetAuthority (address indexed authority); event LogSetOwner (address indexed owner); } /** * @title DSAuth * @dev The DSAuth contract is reference implement of https://github.com/dapphub/ds-auth * But in the isAuthorized method, the src from address(this) is remove for safty concern. */ contract DSAuth is DSAuthEvents { IAuthority public authority; address public owner; constructor() public { owner = msg.sender; emit LogSetOwner(msg.sender); } function setOwner(address owner_) public auth { owner = owner_; emit LogSetOwner(owner); } function setAuthority(IAuthority authority_) public auth { authority = authority_; emit LogSetAuthority(authority); } modifier auth { require(isAuthorized(msg.sender, msg.sig)); _; } modifier onlyOwner() { require(msg.sender == owner); _; } function isAuthorized(address src, bytes4 sig) internal view returns (bool) { if (src == owner) { return true; } else if (authority == IAuthority(0)) { return false; } else { return authority.canCall(src, this, sig); } } } // Dependency file: @evolutionland/common/contracts/SettingIds.sol // pragma solidity ^0.4.24; /** Id definitions for SettingsRegistry.sol Can be used in conjunction with the settings registry to get properties */ contract SettingIds { bytes32 public constant CONTRACT_RING_ERC20_TOKEN = "CONTRACT_RING_ERC20_TOKEN"; bytes32 public constant CONTRACT_KTON_ERC20_TOKEN = "CONTRACT_KTON_ERC20_TOKEN"; bytes32 public constant CONTRACT_GOLD_ERC20_TOKEN = "CONTRACT_GOLD_ERC20_TOKEN"; bytes32 public constant CONTRACT_WOOD_ERC20_TOKEN = "CONTRACT_WOOD_ERC20_TOKEN"; bytes32 public constant CONTRACT_WATER_ERC20_TOKEN = "CONTRACT_WATER_ERC20_TOKEN"; bytes32 public constant CONTRACT_FIRE_ERC20_TOKEN = "CONTRACT_FIRE_ERC20_TOKEN"; bytes32 public constant CONTRACT_SOIL_ERC20_TOKEN = "CONTRACT_SOIL_ERC20_TOKEN"; bytes32 public constant CONTRACT_OBJECT_OWNERSHIP = "CONTRACT_OBJECT_OWNERSHIP"; bytes32 public constant CONTRACT_TOKEN_LOCATION = "CONTRACT_TOKEN_LOCATION"; bytes32 public constant CONTRACT_LAND_BASE = "CONTRACT_LAND_BASE"; bytes32 public constant CONTRACT_USER_POINTS = "CONTRACT_USER_POINTS"; bytes32 public constant CONTRACT_INTERSTELLAR_ENCODER = "CONTRACT_INTERSTELLAR_ENCODER"; bytes32 public constant CONTRACT_DIVIDENDS_POOL = "CONTRACT_DIVIDENDS_POOL"; bytes32 public constant CONTRACT_TOKEN_USE = "CONTRACT_TOKEN_USE"; bytes32 public constant CONTRACT_REVENUE_POOL = "CONTRACT_REVENUE_POOL"; bytes32 public constant CONTRACT_ERC721_BRIDGE = "CONTRACT_ERC721_BRIDGE"; bytes32 public constant CONTRACT_PET_BASE = "CONTRACT_PET_BASE"; // Cut owner takes on each auction, measured in basis points (1/100 of a percent). // this can be considered as transaction fee. // Values 0-10,000 map to 0%-100% // set ownerCut to 4% // ownerCut = 400; bytes32 public constant UINT_AUCTION_CUT = "UINT_AUCTION_CUT"; // Denominator is 10000 bytes32 public constant UINT_TOKEN_OFFER_CUT = "UINT_TOKEN_OFFER_CUT"; // Denominator is 10000 // Cut referer takes on each auction, measured in basis points (1/100 of a percent). // which cut from transaction fee. // Values 0-10,000 map to 0%-100% // set refererCut to 4% // refererCut = 400; bytes32 public constant UINT_REFERER_CUT = "UINT_REFERER_CUT"; bytes32 public constant CONTRACT_LAND_RESOURCE = "CONTRACT_LAND_RESOURCE"; } // Dependency file: @evolutionland/common/contracts/interfaces/IInterstellarEncoder.sol // pragma solidity ^0.4.24; contract IInterstellarEncoder { uint256 constant CLEAR_HIGH = 0x00000000000000000000000000000000ffffffffffffffffffffffffffffffff; uint256 public constant MAGIC_NUMBER = 42; // Interstellar Encoding Magic Number. uint256 public constant CHAIN_ID = 1; // Ethereum mainet. uint256 public constant CURRENT_LAND = 1; // 1 is Atlantis, 0 is NaN. enum ObjectClass { NaN, LAND, APOSTLE, OBJECT_CLASS_COUNT } function registerNewObjectClass(address _objectContract, uint8 objectClass) public; function registerNewTokenContract(address _tokenAddress) public; function encodeTokenId(address _tokenAddress, uint8 _objectClass, uint128 _objectIndex) public view returns (uint256 _tokenId); function encodeTokenIdForObjectContract( address _tokenAddress, address _objectContract, uint128 _objectId) public view returns (uint256 _tokenId); function getContractAddress(uint256 _tokenId) public view returns (address); function getObjectId(uint256 _tokenId) public view returns (uint128 _objectId); function getObjectClass(uint256 _tokenId) public view returns (uint8); function getObjectAddress(uint256 _tokenId) public view returns (address); } // Dependency file: @evolutionland/common/contracts/interfaces/ITokenUse.sol // pragma solidity ^0.4.24; contract ITokenUse { uint48 public constant MAX_UINT48_TIME = 281474976710655; function isObjectInHireStage(uint256 _tokenId) public view returns (bool); function isObjectReadyToUse(uint256 _tokenId) public view returns (bool); function getTokenUser(uint256 _tokenId) public view returns (address); function createTokenUseOffer(uint256 _tokenId, uint256 _duration, uint256 _price, address _acceptedActivity) public; function cancelTokenUseOffer(uint256 _tokenId) public; function takeTokenUseOffer(uint256 _tokenId) public; function addActivity(uint256 _tokenId, address _user, uint256 _endTime) public; function removeActivity(uint256 _tokenId, address _user) public; } // Dependency file: @evolutionland/common/contracts/interfaces/IActivity.sol // pragma solidity ^0.4.24; // import "openzeppelin-solidity/contracts/introspection/ERC165.sol"; contract IActivity is ERC165 { bytes4 internal constant InterfaceId_IActivity = 0x6086e7f8; /* * 0x6086e7f8 === * bytes4(keccak256('activityStopped(uint256)')) */ function activityStopped(uint256 _tokenId) public; } // Dependency file: @evolutionland/common/contracts/interfaces/IMinerObject.sol // pragma solidity ^0.4.24; // import "openzeppelin-solidity/contracts/introspection/ERC165.sol"; contract IMinerObject is ERC165 { bytes4 internal constant InterfaceId_IMinerObject = 0x64272b75; /* * 0x64272b752 === * bytes4(keccak256('strengthOf(uint256,address)')) */ function strengthOf(uint256 _tokenId, address _resourceToken, uint256 _landTokenId) public view returns (uint256); } // Dependency file: contracts/interfaces/ILandBase.sol // pragma solidity ^0.4.24; contract ILandBase { /* * Event */ event ModifiedResourceRate(uint indexed tokenId, address resourceToken, uint16 newResourceRate); event HasboxSetted(uint indexed tokenId, bool hasBox); event ChangedReourceRateAttr(uint indexed tokenId, uint256 attr); event ChangedFlagMask(uint indexed tokenId, uint256 newFlagMask); event CreatedNewLand(uint indexed tokenId, int x, int y, address beneficiary, uint256 resourceRateAttr, uint256 mask); function defineResouceTokenRateAttrId(address _resourceToken, uint8 _attrId) public; function setHasBox(uint _landTokenID, bool isHasBox) public; function isReserved(uint256 _tokenId) public view returns (bool); function isSpecial(uint256 _tokenId) public view returns (bool); function isHasBox(uint256 _tokenId) public view returns (bool); function getResourceRateAttr(uint _landTokenId) public view returns (uint256); function setResourceRateAttr(uint _landTokenId, uint256 _newResourceRateAttr) public; function getResourceRate(uint _landTokenId, address _resouceToken) public view returns (uint16); function setResourceRate(uint _landTokenID, address _resourceToken, uint16 _newResouceRate) public; function getFlagMask(uint _landTokenId) public view returns (uint256); function setFlagMask(uint _landTokenId, uint256 _newFlagMask) public; function resourceToken2RateAttrId(address _resourceToken) external view returns (uint256); } // Dependency file: contracts/LandSettingIds.sol // pragma solidity ^0.4.24; // import "@evolutionland/common/contracts/SettingIds.sol"; contract LandSettingIds is SettingIds { } // Root file: contracts/LandResourceV4.sol pragma solidity ^0.4.23; // import "openzeppelin-solidity/contracts/math/SafeMath.sol"; // import "openzeppelin-solidity/contracts/token/ERC721/ERC721.sol"; // import "openzeppelin-solidity/contracts/introspection/SupportsInterfaceWithLookup.sol"; // import "@evolutionland/common/contracts/interfaces/IMintableERC20.sol"; // import "@evolutionland/common/contracts/interfaces/ISettingsRegistry.sol"; // import "@evolutionland/common/contracts/DSAuth.sol"; // import "@evolutionland/common/contracts/SettingIds.sol"; // import "@evolutionland/common/contracts/interfaces/IInterstellarEncoder.sol"; // import "@evolutionland/common/contracts/interfaces/ITokenUse.sol"; // import "@evolutionland/common/contracts/interfaces/IActivity.sol"; // import "@evolutionland/common/contracts/interfaces/IMinerObject.sol"; // import "contracts/interfaces/ILandBase.sol"; // import "contracts/LandSettingIds.sol"; /** * @title LandResource * @dev LandResource is registry that manage the element resources generated on Land, and related resource releasing speed. * difference between LandResourceV2: 1. add function landWorkingOn to get which land the apostle is working on 2. add function updateMinerStrength to update miner strength on land 3. add event UpdateMiningStrength */ contract LandResourceV4 is SupportsInterfaceWithLookup, DSAuth, IActivity, LandSettingIds { using SafeMath for *; // For every seconds, the speed will decrease by current speed multiplying (DENOMINATOR_in_seconds - seconds) / DENOMINATOR_in_seconds // resource will decrease 1/10000 every day. uint256 public constant DENOMINATOR = 10000; uint256 public constant TOTAL_SECONDS = DENOMINATOR * (1 days); bool private singletonLock = false; ISettingsRegistry public registry; uint256 public resourceReleaseStartTime; // TODO: move to global settings contract. uint256 public attenPerDay = 1; uint256 public recoverAttenPerDay = 20; // Struct for recording resouces on land which have already been pinged. // 金, Evolution Land Gold // 木, Evolution Land Wood // 水, Evolution Land Water // 火, Evolution Land fire // 土, Evolution Land Silicon struct ResourceMineState { mapping(address => uint256) mintedBalance; mapping(address => uint256[]) miners; mapping(address => uint256) totalMinerStrength; uint256 lastUpdateSpeedInSeconds; uint256 lastDestoryAttenInSeconds; uint256 industryIndex; uint128 lastUpdateTime; uint64 totalMiners; uint64 maxMiners; } struct MinerStatus { uint256 landTokenId; address resource; uint64 indexInResource; } mapping(uint256 => ResourceMineState) public land2ResourceMineState; mapping(uint256 => MinerStatus) public miner2Index; /* * Event */ event StartMining(uint256 minerTokenId, uint256 landTokenId, address _resource, uint256 strength); event StopMining(uint256 minerTokenId, uint256 landTokenId, address _resource, uint256 strength); event ResourceClaimed(address owner, uint256 landTokenId, uint256 goldBalance, uint256 woodBalance, uint256 waterBalance, uint256 fireBalance, uint256 soilBalance); event UpdateMiningStrengthWhenStop(uint256 apostleTokenId, uint256 landTokenId, uint256 strength); event UpdateMiningStrengthWhenStart(uint256 apostleTokenId, uint256 landTokenId, uint256 strength); /* * Modifiers */ modifier singletonLockCall() { require(!singletonLock, "Only can call once"); _; singletonLock = true; } function initializeContract(address _registry, uint256 _resourceReleaseStartTime) public singletonLockCall { // Ownable constructor owner = msg.sender; emit LogSetOwner(msg.sender); registry = ISettingsRegistry(_registry); resourceReleaseStartTime = _resourceReleaseStartTime; _registerInterface(InterfaceId_IActivity); } // get amount of speed uint at this moment function _getReleaseSpeedInSeconds(uint256 _tokenId, uint256 _time) internal view returns (uint256 currentSpeed) { require(_time >= resourceReleaseStartTime, "Should after release time"); require(_time >= land2ResourceMineState[_tokenId].lastUpdateTime, "Should after release last update time"); // after 10000 days from start // the resource release speed decreases to 0 if (TOTAL_SECONDS < _time - resourceReleaseStartTime) { return 0; } // max amount of speed unit of _tokenId for now // suppose that speed_uint = 1 in this function uint256 availableSpeedInSeconds = TOTAL_SECONDS.sub(_time - resourceReleaseStartTime); // time from last update uint256 timeBetween = _time - land2ResourceMineState[_tokenId].lastUpdateTime; // the recover speed is 20/10000, 20 times. // recoveryRate overall from lasUpdateTime til now + amount of speed uint at lastUpdateTime uint256 nextSpeedInSeconds = land2ResourceMineState[_tokenId].lastUpdateSpeedInSeconds + timeBetween * recoverAttenPerDay; // destroyRate overall from lasUpdateTime til now amount of speed uint at lastUpdateTime uint256 destroyedSpeedInSeconds = timeBetween * land2ResourceMineState[_tokenId].lastDestoryAttenInSeconds; if (nextSpeedInSeconds < destroyedSpeedInSeconds) { nextSpeedInSeconds = 0; } else { nextSpeedInSeconds = nextSpeedInSeconds - destroyedSpeedInSeconds; } if (nextSpeedInSeconds > availableSpeedInSeconds) { nextSpeedInSeconds = availableSpeedInSeconds; } return nextSpeedInSeconds; } function getReleaseSpeed(uint256 _tokenId, address _resourceToken, uint256 _time) public view returns (uint256 currentSpeed) { return ILandBase(registry.addressOf(CONTRACT_LAND_BASE)) .getResourceRate(_tokenId, _resourceToken).mul(_getReleaseSpeedInSeconds(_tokenId, _time)) .div(TOTAL_SECONDS); } /** * @dev Get and Query the amount of resources available from lastUpdateTime to now for use on specific land. * @param _tokenId The token id of specific land. */ function _getMinableBalance(uint256 _tokenId, address _resourceToken, uint256 _currentTime, uint256 _lastUpdateTime) public view returns (uint256 minableBalance) { uint256 speed_in_current_period = ILandBase(registry.addressOf(CONTRACT_LAND_BASE)) .getResourceRate(_tokenId, _resourceToken).mul(_getReleaseSpeedInSeconds(_tokenId, ((_currentTime + _lastUpdateTime) / 2))).mul(1 ether).div(1 days).div(TOTAL_SECONDS); // calculate the area of trapezoid minableBalance = speed_in_current_period.mul(_currentTime - _lastUpdateTime); } function _getMaxMineBalance(uint256 _tokenId, address _resourceToken, uint256 _currentTime, uint256 _lastUpdateTime) internal view returns (uint256) { // totalMinerStrength is in wei uint256 mineSpeed = land2ResourceMineState[_tokenId].totalMinerStrength[_resourceToken]; return mineSpeed.mul(_currentTime - _lastUpdateTime).div(1 days); } function mine(uint256 _landTokenId) public { _mineAllResource( _landTokenId, registry.addressOf(CONTRACT_GOLD_ERC20_TOKEN), registry.addressOf(CONTRACT_WOOD_ERC20_TOKEN), registry.addressOf(CONTRACT_WATER_ERC20_TOKEN), registry.addressOf(CONTRACT_FIRE_ERC20_TOKEN), registry.addressOf(CONTRACT_SOIL_ERC20_TOKEN) ); } function _mineAllResource(uint256 _landTokenId, address _gold, address _wood, address _water, address _fire, address _soil) internal { require(IInterstellarEncoder(registry.addressOf(CONTRACT_INTERSTELLAR_ENCODER)).getObjectClass(_landTokenId) == 1, "Token must be land."); if (land2ResourceMineState[_landTokenId].lastUpdateTime == 0) { land2ResourceMineState[_landTokenId].lastUpdateTime = uint128(resourceReleaseStartTime); land2ResourceMineState[_landTokenId].lastUpdateSpeedInSeconds = TOTAL_SECONDS; } _mineResource(_landTokenId, _gold); _mineResource(_landTokenId, _wood); _mineResource(_landTokenId, _water); _mineResource(_landTokenId, _fire); _mineResource(_landTokenId, _soil); land2ResourceMineState[_landTokenId].lastUpdateSpeedInSeconds = _getReleaseSpeedInSeconds(_landTokenId, now); land2ResourceMineState[_landTokenId].lastUpdateTime = uint128(now); } function _mineResource(uint256 _landTokenId, address _resourceToken) internal { // the longest seconds to zero speed. uint minedBalance = _calculateMinedBalance(_landTokenId, _resourceToken, now); land2ResourceMineState[_landTokenId].mintedBalance[_resourceToken] += minedBalance; } function _calculateMinedBalance(uint256 _landTokenId, address _resourceToken, uint256 _currentTime) internal returns (uint256) { uint256 currentTime = _currentTime; uint256 minedBalance; uint256 minableBalance; if (currentTime > (resourceReleaseStartTime + TOTAL_SECONDS)) { currentTime = (resourceReleaseStartTime + TOTAL_SECONDS); } uint256 lastUpdateTime = land2ResourceMineState[_landTokenId].lastUpdateTime; require(currentTime >= lastUpdateTime); if (lastUpdateTime >= (resourceReleaseStartTime + TOTAL_SECONDS)) { minedBalance = 0; minableBalance = 0; } else { minedBalance = _getMaxMineBalance(_landTokenId, _resourceToken, currentTime, lastUpdateTime); minableBalance = _getMinableBalance(_landTokenId, _resourceToken, currentTime, lastUpdateTime); } if (minedBalance > minableBalance) { minedBalance = minableBalance; } return minedBalance; } function claimAllResource(uint256 _landTokenId) public { require(msg.sender == ERC721(registry.addressOf(CONTRACT_OBJECT_OWNERSHIP)).ownerOf(_landTokenId), "Must be the owner of the land"); address gold = registry.addressOf(CONTRACT_GOLD_ERC20_TOKEN); address wood = registry.addressOf(CONTRACT_WOOD_ERC20_TOKEN); address water = registry.addressOf(CONTRACT_WATER_ERC20_TOKEN); address fire = registry.addressOf(CONTRACT_FIRE_ERC20_TOKEN); address soil = registry.addressOf(CONTRACT_SOIL_ERC20_TOKEN); _mineAllResource(_landTokenId, gold, wood, water, fire, soil); uint goldBalance; uint woodBalance; uint waterBalance; uint fireBalance; uint soilBalance; if (land2ResourceMineState[_landTokenId].mintedBalance[gold] > 0) { goldBalance = land2ResourceMineState[_landTokenId].mintedBalance[gold]; IMintableERC20(gold).mint(msg.sender, goldBalance); land2ResourceMineState[_landTokenId].mintedBalance[gold] = 0; } if (land2ResourceMineState[_landTokenId].mintedBalance[wood] > 0) { woodBalance = land2ResourceMineState[_landTokenId].mintedBalance[wood]; IMintableERC20(wood).mint(msg.sender, woodBalance); land2ResourceMineState[_landTokenId].mintedBalance[wood] = 0; } if (land2ResourceMineState[_landTokenId].mintedBalance[water] > 0) { waterBalance = land2ResourceMineState[_landTokenId].mintedBalance[water]; IMintableERC20(water).mint(msg.sender, waterBalance); land2ResourceMineState[_landTokenId].mintedBalance[water] = 0; } if (land2ResourceMineState[_landTokenId].mintedBalance[fire] > 0) { fireBalance = land2ResourceMineState[_landTokenId].mintedBalance[fire]; IMintableERC20(fire).mint(msg.sender, fireBalance); land2ResourceMineState[_landTokenId].mintedBalance[fire] = 0; } if (land2ResourceMineState[_landTokenId].mintedBalance[soil] > 0) { soilBalance = land2ResourceMineState[_landTokenId].mintedBalance[soil]; IMintableERC20(soil).mint(msg.sender, soilBalance); land2ResourceMineState[_landTokenId].mintedBalance[soil] = 0; } emit ResourceClaimed(msg.sender, _landTokenId, goldBalance, woodBalance, waterBalance, fireBalance, soilBalance); } // both for own _tokenId or hired one function startMining(uint256 _tokenId, uint256 _landTokenId, address _resource) public { ITokenUse tokenUse = ITokenUse(registry.addressOf(CONTRACT_TOKEN_USE)); tokenUse.addActivity(_tokenId, msg.sender, 0); // require the permission from land owner; require(msg.sender == ERC721(registry.addressOf(CONTRACT_OBJECT_OWNERSHIP)).ownerOf(_landTokenId), "Must be the owner of the land"); // make sure that _tokenId won't be used repeatedly require(miner2Index[_tokenId].landTokenId == 0); // update status! mine(_landTokenId); uint256 _index = land2ResourceMineState[_landTokenId].miners[_resource].length; land2ResourceMineState[_landTokenId].totalMiners += 1; if (land2ResourceMineState[_landTokenId].maxMiners == 0) { land2ResourceMineState[_landTokenId].maxMiners = 5; } require(land2ResourceMineState[_landTokenId].totalMiners <= land2ResourceMineState[_landTokenId].maxMiners); address miner = IInterstellarEncoder(registry.addressOf(CONTRACT_INTERSTELLAR_ENCODER)).getObjectAddress(_tokenId); uint256 strength = IMinerObject(miner).strengthOf(_tokenId, _resource, _landTokenId); land2ResourceMineState[_landTokenId].miners[_resource].push(_tokenId); land2ResourceMineState[_landTokenId].totalMinerStrength[_resource] += strength; miner2Index[_tokenId] = MinerStatus({ landTokenId : _landTokenId, resource : _resource, indexInResource : uint64(_index) }); emit StartMining(_tokenId, _landTokenId, _resource, strength); } function batchStartMining(uint256[] _tokenIds, uint256[] _landTokenIds, address[] _resources) public { require(_tokenIds.length == _landTokenIds.length && _landTokenIds.length == _resources.length, "input error"); uint length = _tokenIds.length; for (uint i = 0; i < length; i++) { startMining(_tokenIds[i], _landTokenIds[i], _resources[i]); } } function batchClaimAllResource(uint256[] _landTokenIds) public { uint length = _landTokenIds.length; for (uint i = 0; i < length; i++) { claimAllResource(_landTokenIds[i]); } } // Only trigger from Token Activity. function activityStopped(uint256 _tokenId) public auth { _stopMining(_tokenId); } function stopMining(uint256 _tokenId) public { ITokenUse(registry.addressOf(CONTRACT_TOKEN_USE)).removeActivity(_tokenId, msg.sender); } function _stopMining(uint256 _tokenId) internal { // remove the miner from land2ResourceMineState; uint64 minerIndex = miner2Index[_tokenId].indexInResource; address resource = miner2Index[_tokenId].resource; uint256 landTokenId = miner2Index[_tokenId].landTokenId; // update status! mine(landTokenId); uint64 lastMinerIndex = uint64(land2ResourceMineState[landTokenId].miners[resource].length.sub(1)); uint256 lastMiner = land2ResourceMineState[landTokenId].miners[resource][lastMinerIndex]; land2ResourceMineState[landTokenId].miners[resource][minerIndex] = lastMiner; land2ResourceMineState[landTokenId].miners[resource][lastMinerIndex] = 0; land2ResourceMineState[landTokenId].miners[resource].length -= 1; miner2Index[lastMiner].indexInResource = minerIndex; land2ResourceMineState[landTokenId].totalMiners -= 1; address miner = IInterstellarEncoder(registry.addressOf(CONTRACT_INTERSTELLAR_ENCODER)).getObjectAddress(_tokenId); uint256 strength = IMinerObject(miner).strengthOf(_tokenId, resource, landTokenId); // for backward compatibility // if strength can fluctuate some time in the future if (land2ResourceMineState[landTokenId].totalMinerStrength[resource] != 0) { if (land2ResourceMineState[landTokenId].totalMinerStrength[resource] > strength) { land2ResourceMineState[landTokenId].totalMinerStrength[resource] = land2ResourceMineState[landTokenId].totalMinerStrength[resource].sub(strength); } else { land2ResourceMineState[landTokenId].totalMinerStrength[resource] = 0; } } if (land2ResourceMineState[landTokenId].totalMiners == 0) { land2ResourceMineState[landTokenId].totalMinerStrength[resource] = 0; } delete miner2Index[_tokenId]; emit StopMining(_tokenId, landTokenId, resource, strength); } function getMinerOnLand(uint _landTokenId, address _resourceToken, uint _index) public view returns (uint256) { return land2ResourceMineState[_landTokenId].miners[_resourceToken][_index]; } function getTotalMiningStrength(uint _landTokenId, address _resourceToken) public view returns (uint256) { return land2ResourceMineState[_landTokenId].totalMinerStrength[_resourceToken]; } function availableResources(uint256 _landTokenId, address[5] _resourceTokens) public view returns (uint256, uint256, uint256, uint256, uint256) { uint availableGold = _calculateMinedBalance(_landTokenId, _resourceTokens[0], now) + land2ResourceMineState[_landTokenId].mintedBalance[_resourceTokens[0]]; uint availableWood = _calculateMinedBalance(_landTokenId, _resourceTokens[1], now) + land2ResourceMineState[_landTokenId].mintedBalance[_resourceTokens[1]]; uint availableWater = _calculateMinedBalance(_landTokenId, _resourceTokens[2], now) + land2ResourceMineState[_landTokenId].mintedBalance[_resourceTokens[2]]; uint availableFire = _calculateMinedBalance(_landTokenId, _resourceTokens[3], now) + land2ResourceMineState[_landTokenId].mintedBalance[_resourceTokens[3]]; uint availableSoil = _calculateMinedBalance(_landTokenId, _resourceTokens[4], now) + land2ResourceMineState[_landTokenId].mintedBalance[_resourceTokens[4]]; return (availableGold, availableWood, availableWater, availableFire, availableSoil); } function mintedBalanceOnLand(uint256 _landTokenId, address _resourceToken) public view returns (uint256) { return land2ResourceMineState[_landTokenId].mintedBalance[_resourceToken]; } function landWorkingOn(uint256 _apostleTokenId) public view returns (uint256 landTokenId) { landTokenId = miner2Index[_apostleTokenId].landTokenId; } function _updateMinerStrength(uint256 _apostleTokenId, bool _isStop) internal returns (uint256, uint256){ // require that this apostle uint256 landTokenId = landWorkingOn(_apostleTokenId); require(landTokenId != 0, "this apostle is not mining."); address resource = miner2Index[_apostleTokenId].resource; address miner = IInterstellarEncoder(registry.addressOf(CONTRACT_INTERSTELLAR_ENCODER)).getObjectAddress(_apostleTokenId); uint256 strength = IMinerObject(miner).strengthOf(_apostleTokenId, resource, landTokenId); mine(landTokenId); if (_isStop) { land2ResourceMineState[landTokenId].totalMinerStrength[resource] = land2ResourceMineState[landTokenId].totalMinerStrength[resource].sub(strength); } else { land2ResourceMineState[landTokenId].totalMinerStrength[resource] += strength; } return (landTokenId, strength); } // when a mirrorToken or a pet has tied to apostle // we need to update status and remove this apostle from mining list first // open authority to PetBase // can only be called by PetBase function updateMinerStrengthWhenStop(uint256 _apostleTokenId) public auth { uint256 landTokenId; uint256 strength; (landTokenId, strength) = _updateMinerStrength(_apostleTokenId, true); // _isStop == true - minus strength // _isStop == false - add strength emit UpdateMiningStrengthWhenStop(_apostleTokenId, landTokenId, strength); } function updateMinerStrengthWhenStart(uint256 _apostleTokenId) public auth { uint256 landTokenId; uint256 strength; (landTokenId, strength) = _updateMinerStrength(_apostleTokenId, false); // _isStop == true - minus strength // _isStop == false - add strength emit UpdateMiningStrengthWhenStart(_apostleTokenId, landTokenId, strength); } }
Get and Query the amount of resources available from lastUpdateTime to now for use on specific land. _tokenId The token id of specific land./ calculate the area of trapezoid
function _getMinableBalance(uint256 _tokenId, address _resourceToken, uint256 _currentTime, uint256 _lastUpdateTime) public view returns (uint256 minableBalance) { uint256 speed_in_current_period = ILandBase(registry.addressOf(CONTRACT_LAND_BASE)) .getResourceRate(_tokenId, _resourceToken).mul(_getReleaseSpeedInSeconds(_tokenId, ((_currentTime + _lastUpdateTime) / 2))).mul(1 ether).div(1 days).div(TOTAL_SECONDS); minableBalance = speed_in_current_period.mul(_currentTime - _lastUpdateTime); }
5,394,035